repoName
stringlengths
7
77
tree
stringlengths
0
2.85M
readme
stringlengths
0
4.9M
love-and-coffee-archive_near-challenge-3-v2
.eslintrc.yml .gitpod.yml .travis.yml README-Gitpod.md README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts guestbook.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.js neardev shared-test-staging test.near.json shared-test test.near.json package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
Guest Book ========== [![Build Status](https://travis-ci.com/near-examples/guest-book.svg?branch=master)](https://travis-ci.com/near-examples/guest-book) [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/guest-book) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend. Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`) 2. Run the local development server: `yarn && yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app. Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html](/src/index.html) is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli -------------------------- You need near-cli installed globally. Here's how: npm install --global near-cli This will give you the `near` [CLI] tool. Ensure that it's installed with: near --version Step 1: Create an account for the contract ------------------------------------------ Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account. Now authorize NEAR CLI for this new account, and follow the instructions it gives you: near login Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!' Step 3: change remote URL if you cloned this repo ------------------------- Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to Github Pages from the command line. 1) go to GitHub and create a new repository for this project 2) open your terminal and in the root of this project enter the following: $ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git` Step 4: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contracts to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. [NEAR]: https://nearprotocol.com/ [yarn]: https://yarnpkg.com/ [AssemblyScript]: https://docs.assemblyscript.org/ [React]: https://reactjs.org [smart contract docs]: https://docs.nearprotocol.com/docs/roles/developer/contracts/assemblyscript [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.nearprotocol.com/docs/concepts/account [NEAR Wallet]: https://wallet.nearprotocol.com [near-cli]: https://github.com/nearprotocol/near-cli [CLI]: https://www.w3schools.com/whatis/whatis_cli.asp [create-near-app]: https://github.com/nearprotocol/create-near-app [gh-pages]: https://github.com/tschaub/gh-pages
quan191_NearQuiz
README.md nearQuiz .cache 00 99d8f2ca596a60a3f1643eb4ab567f.json 01 4dd27210d19295a3d687a1b48817e4.json 6fbda58eb9a47f8690667478410746.json 02 a9d64a34a74eb0f9f0727dd15f7ca9.json 06 3cb5ca7d5d922aa7517f6ffb0c2526.json f26311a2dfdcd50569def0d7b8baf2.json ffb1273d703bf9c12af49118327f91.json 07 b01e0346a178877e89ae5f7d820b71.json 08 21731c8fe09c7e34c95ab1b9295e52.json 35a7f2d4edcb081eb9905f4f8f72d4.json f367da0c7a9048061d32261328836f.json 09 036e3d04304d461dcf5ba3f710da75.json ba677c5215799c5820d4c1b71ffef1.json 0d 3134511d41681f0153e7f6bb3b0b3a.json 7fca075fd3f71a0ef82bce10542e7e.json 0f 2b217300660cb91929d600bd52399a.json c0922f08ecec9549376b843f4a8422.json 10 5f512f99efce9f6225e195209709ac.json a6fea27cce0501befea03bfb917c5e.json dd9214d51c4c958985cd92cfb14555.json 12 5cbff43fdac848590efaa41149fe82.json 15 c8c90c67a0337bb30e12b799ed8ecd.json 16 2bbfbf541e0e83a73e6dd43610d46c.json 17 1e4cc7ce7a53ff0fbdf0568dbb3143.json 18 9eb75f3d63204e2a57f08c7872785e.json 1a 343c5f44f03bc2c235fdabceebd96f.json dfa1e6e780b353567fd259838a026a.json 1b 7ce8ad7e71e57be9480a6c914c8f77.json a8a714114ba7385d48731a2d1f544a.json 1c ad2ef0f60620bef3a9f2b658e8babf.json ee0dd4659b892294215db612e54645.json fd4cea820b2fa55cc41a1166e5bd66.json 1d b3509c1db39a7eba07023e5f443c29.json 1e 7bdc9dd41e0a391feb5246f424373e.json f52d91a8350148cc66851e1efecb12.json 1f 0ea620ed20d87528160a96f695a495.json baf5ddece9b2098a008dba2a6a8ec0.json d0d41f1c8109895f370a66b4942b62.json 21 04c8ea0b6a9e2bd5446e19b3ff727e.json 23 4ce5a7a74306284c3bb38fb572eb8d.json 63077110cef0e16ad5b370ce6200e2.json 24 37bb08479ecfc4c72d9b99d1e7d9b0.json cc7193f5d01940fb561dea73756411.json 26 ce0226739170dadac95e50005382a8.json d68ae2dbe0177a4a1515c54ae0bd42.json dc1088c90f9524c7d6a722b40acb31.json 29 b2c79cfc494844e820dbe7ce01a8af.json de33d57d2b4dc5c0f85e3daf043e8b.json 2b ffda1076e61fbfd04515dd05e35fa0.json 2d 3ec3c33111c0b703e8e239ddb5520e.json 6cdbcbc339206be56f6c607498eabd.json a3bad9c50b003528a578a8cf7c6edd.json ef484232ec505da80dc7452bae6c3d.json 2e 2f8ec4a03222d2f664aa09444167ea.json 2f 20efd18ae6dd6efc81a89f3b309b0c.json 54c12f86a01033038b5cd0718e9e93.json 30 c829cde2e5ff75ea1ac28ceb6b526e.json 31 f0248bdceb69108cb0385c7fd7d510.json 32 d7e9be4c7764f0744936b7994ba98e.json 33 5895618ddab2d3397faeac0348ae3d.json c01d5538e8705880628d1f67dd521b.json 34 55c78847eaa2dd5d12c0e3f805cbec.json 35 8719e8ba5c169fb8c70df87cd3f5ea.json dc3cfad10de5423e17b0758f89909c.json 37 e5ad1cb6696bc35226bdc4a7d7d5d3.json f392b9e925e2c88aef21e1de37959b.json fd50b336c37cbea9cc3ad08e739111.json 39 90032d6354dc68f7f70d6e603f0c05.json 3a 3424d2870d48311098abfe47117742.json 3b 4b6bdf6e3ca1acfa89c466bb1659fe.json 3c b555c8118c1824dbc3ff78ff977f75.json 3d a12fd9710f2d84d8b9c1bb5db25e18.json dc11cf4088135bf5dacebe3875636e.json fd2b4d3a75cf91ca1510cd65e33ae8.json 3e 08cf73505a6fd8fc3757e2ff090586.json 20c820bcf9c6d3e1e9cf6c6fdd0872.json 25759426d196797fae6ffe4c72433d.json 4cb2105dba4c0583313c78e5746b3a.json 8d475050ecb8ce905486dd2a6d3ee6.json 9ff1130575c0a00f03298c16dfd079.json a1cb9d5f67b2cafd8a7d4dc1d097a8.json 3f 86adeb96c48b746e83d4c8f36e09d3.json 86d1d943ed483f3a99d599035f3aef.json c8d574b03952576c466958f60e5913.json 40 1cb59dec251e84c3c52187f9d70096.json c1d229b6622a31c1741859537905c1.json 41 0b28a5aba7519b11d15699c903b12a.json 5cfb35a1f6a576ffe8ce3e7f6a1986.json 42 83e1e72230bcd42d555b39071b6b1d.json cf3aba2eb380edfad76bd9d27482e8.json 43 282d0d5330baae337adf7834cf8693.json d2be92bf5e3fb372c48296b80754e1.json 44 94c4b8c048d63da9614777f454c0ca.json 46 db8c29e095165b4beb830ded88d1c4.json 47 c5ca2cc0b9a0ed659b45a39a0708fc.json 49 d6a37c3399832b02e414971c595ffc.json f9fdb7d02c0fb4773cea04eb6e60d4.json 4c fd15b8c7379df57fe81203e0c31278.json 4d 644b156341a1e3868048cc6254db00.json 958252b229d87c8bf7f9cf3e120082.json f99bf803342b7553272ca667f92fdb.json 4e e24ea098888fcb51a4cb6d08852ef7.json 4f 1d07388f57870b4ab00db7c09e0ff8.json 50 6fb46126cae350961281e032b4050f.json d07f707c940e79879aaa02401605ac.json 51 81ce74e256e2555813747f86b6a782.json 52 7e360296651256b1daba32ba0ad6b4.json 905fcafcb87c503a1b05c6e1abc69c.json 53 2d8e596f7f17b46d25e35e1959aba1.json 726db0512e9fd7381e3674c8988af5.json 99b5a0f386b30cdff640f00d4e669d.json 54 85842e91bef7a261b7b145f456ba45.json 8d1b30bdb06e8d79f6c297dc126f3f.json 55 3ae564867a769e4518be7648a6d674.json 56 8fc51cc4ea6315aca20c37e9723e32.json b543a2c5c42bcaa8c358709c7a2780.json 57 ae0c0f2c8a6baa990f74ad718b0410.json d0af708ccfe7b27af10e2e48c8f716.json 58 0a03b3bbc5cf738d2dd8dde32de920.json 64e10c1d7332b0dff99a35388172b7.json d53b4be542889a8ff94bc927a64b58.json 59 7a6a06fb5e7fe1ab14422806020fca.json cfcf15ea0587cc2c5938ac092ccba2.json 5a 2c702fedc95872d55f8953d78f7ee5.json 5e 75c828df42298733eb4eebfc18ae3f.json ff08d1fd8e07acae16a9406b250bb6.json 5f ac6f763f147542f3222d85e434fe2d.json f3890f0b9d1d5310ceceb8228cf1ae.json 60 789f6550da493992b842004ec4a089.json f50da4903f46e3c63dd0abb6437b17.json 61 0d4576cf679d87129e91a610e901f8.json 6521198a59997a6635ebc4432a18ee.json a6b2157ce40477ce8713a32ab1b6fa.json 62 2e0c19258eb73291fd3512ff622884.json c01644a38ff8169b29172806a614c6.json 63 89cc0d5e92a2dbd9b157f8d562f6f0.json c61deb573b156b1e463dc5f5de5e9d.json 66 29959dc0818fc76e53240ca3474d8d.json 67 042ae6e43bb0d39785e361342d57a8.json 435ff9ec0a52a08b74219f06366c05.json 9e12822d1bc6bb3f3882d839cb5e8f.json 68 16d0c1e0081c8fc7fad30c706b9094.json 69 5b9e760250f5612c4d839417bee6f7.json a38ec0fc126b88b3d243639f163807.json 6b 1d05dc765ec55903e2897151b51d6e.json a5b70ed1c822dc83cc3dc68eb54f40.json cca4424dc03799167c22e221a6892b.json 6c 74a770c2015e2708a89378264e0c52.json a61a202fb86ed36d4ad8b2fca3aece.json 6d 5b7aae52f3612dae3a93aedb171afe.json 63638601d1181e22b48f15659190e5.json 6f 048bd2a2a3fc3f8c2c794ef3a6063d.json 87664ee8d685d053037633ea9e4b9f.json 70 75e4073c5149b65bf2f288e63e68d6.json 85d2f3a3467f29a67b52a60eb2690a.json cf09b30bf750bbc9e87fd2d3572a12.json 71 90a9987fd498690f829d03414c65c6.json e6036c3bf637f6c1c9d2c43ce3bde6.json 74 3e012c9c3e4bbf70e18952aab51905.json 93ffb2503bf7f7b478240e98314c8d.json 98f7452f9b313702ef5f64795c4aa4.json 9996b431a2a0c1d7a3f796361eaa4f.json 75 81731df6cc2d2003a21510e2bd1e80.json 9df01710bc9d66675a346a91097885.json dbc57d388858a927771a7096f5ba84.json 77 1557fcfa26dcb8f3d04483e17abb36.json 78 53a65b04eac647dbae5f82c7714bc2.json 79 0ebbb5d6eb0cf4bdfff3d6e9cc09fb.json c3ccacf6ab56a602fd5220181540f7.json 7b 0bccf936fc88a7f0a7ba0619e09685.json 7c 25f48d3f1197148a5fc94f61124bec.json 6bce76f99f2c11da48a1cf8567e47e.json 9699ff6ea5a66425e3747d0f3b6b81.json 7d c71aff7e0571018c4eadead3a19b9a.json 7e c5673b0ed4586203168e8342f3a1fd.json 7f 356e81724cc9bb2300310383029de2.json d102bad7515bd96d5c537a4d27ec75.json 82 b93069b3794e6893ec47c0022823a0.json 83 47c60983164ddc4eb7e61ddcde53b8.json d3631de02e4c1cc515abeff1a5cd4f.json 85 2ea54706bf972190bd54e5090844dd.json 86 d9aad916f8504afd4850065c38f931.json f1afa34635c5c78661ec749ffd0b00.json 87 3a863f83f4f98f9856986c145a8009.json e6f376e638ae27705f12ece315a7a5.json 88 e6d5be07ea36011e996f1deab962d9.json 89 0e8e7a9109eba30a943adf5289e309.json 5f7f7b607195c3ecea40886c140ce9.json 8a 62a5b8fdcb466974aebd862e0811b2.json 8b 298d7e92e1ec687fad7b279ec4f59b.json 8c 4d4c4519a9b8925e89740bc6d23a8d.json 8d 40e80fc3b379e8208fd44601d497b6.json 780a150b83d816d6e345605c9d4c3c.json 8e 426de9337db58907ca1cd06929a29f.json 4bfab93f1e96201788dfb10288bb12.json 7d89c579b11a959eb448952b438abc.json 8f ae967cc22c1eb2d75c82cd1d9eb6ac.json 90 4da1fa1b42b76f59053e5107e6d517.json 91 926b69b6f3f7b985e0fec455ff32c7.json 92 743757a1c4fa4393775d0935fd3ea5.json 95 66e630f0a38d81720a14b3a00d3780.json 7391915958a95d51a1639b412d01b3.json 96 a7419668d6815999d333917a933688.json 98 63fe9065319872eac1d603ea33ca3d.json 9b 8a1272fe84b538253f48e9b362298e.json 9c 34c4dd7a0c3ee7b3b09463fe8189cc.json 4b0e20b2bfcab6825d1b53b2becbf7.json 4d0da7033c8f78abc32350b63b5bb7.json 54654b56ed204c2b24ec610f566d09.json c64142ff898541e39fe50b1a6feb17.json 9d aa9ccce1e212874961cdda4f9543a9.json ccab669563da3d61bac0785ccce435.json 9e 40ba4ac32c165f40b6ffa6c31b379b.json a557281162a5b2e9f7c0fe818c36bb.json 9f 60155c49857fc3d8779dc0e6bf35fc.json 6525ecfa6483b52b58a5de96cd314e.json a1 5cc1fe1e47db127d189c2a951b30ed.json 740da99843714cb70fa11e5233e6c7.json 7e2b2bc7dfe801a92ad22db8aea716.json a3 cd7315327317e0c701c2ac2548a92e.json a4 df071f9993e0dcafc6a69558a1141a.json fbbd531ba6384557307a2d379e7d09.json a5 eb520bc6be60518381a2fbc4414f8e.json a6 c81b845c4d0d1c389fee4f3f4de129.json a7 88c0f0384a37ff6d5d58150415987b.json a8 5dee4cb7b620f522a7951aeaaaa878.json a9 0fbf2ee2ec1b9de42cac80a85277b3.json aa bbf934a62eee6360ab7e3ab4d0a85d.json ab 5ecc73c6e3ea5290fcefd8739c23f7.json a5c6cba0d07dbffb9b2443b0b94ba1.json f53f6603b055329ecea1cb694a3324.json ac 41ee0eafd64a687ab312c927f20d20.json b2dbfd2ada00bfec1ba0ba33993960.json c5362ffbca71769dbdb04fcc822d56.json f336c2e52345c4742aadf053d4d8bf.json ad 416d0cb8c83bf874e6968ea10d6d28.json ae 7a7c2d38b06b73b1a511915e5151cc.json af 20ca51ecc45203e4cc7498884586d3.json 213a7823621277d45bd394f6329f93.json b1 4c1cbfe2f1175f94f450e091d81f2c.json ddbdfe0dc048ae4591aafa99dea857.json b2 42c12d0ba76fdac2ae3448bb028a33.json 5e54ebe45290672897c3fc9220df1f.json b3 56ddba1903279983aed5c68ba3a518.json b7 07c3ba883abebe2ceed706425e052a.json d297a89f1a6fb617c8e07b187e7ab6.json b8 d2676f8c78f4b8c32a450978471b7f.json b9 1a5feeded099b577bbafcc5f307357.json ba 23ab890c8ddfddb9f0a1b255d911a1.json bb 05425ab747170210e9ae5207f03b03.json 0882edcbefec84b0f507c02752bdd6.json 513f28c2cec18e3f4f7e8b93d801c4.json ccfb33900171ad1de6af08f56e0cd7.json bc d745210a595c80e7966d5e2b07bc8b.json bd 0f8ab7b5da85490420c7d8f6349196.json 8edf5fce3ff02d2496bd2cd89c276a.json 9cca84d6099815c6379c5fa8be6ba0.json bf d4587b275d0d084bb82ebb7eec00cd.json c0 64eb51cec6f405512d209c407f3276.json a4e91ab2c187b6a1710d6be45142da.json c2 118222474753fccbc4e70b288eef41.json 5b8506693071b3ff16ac06a272712b.json 8fc140fb2b0a0736619ec25575baf9.json a3b5b84527f8dd173871aaf7f10290.json c3 452fafc1ab15a20427272ee929fde8.json ba24c47657037cd065b3d3b4eb364a.json c4 d907c17b4ef6e1f8b9b81bc5aeac46.json c5 16b3e777523b9bcdfdc9c1f04150d7.json c6 29b827bf1fdaa6ed7fc666e57279c3.json c7 71d001592d7bef6cca9e1477952a70.json f361fa1789d414e12d89b57e377085.json c8 6a63e3ec8d4414c1f517b65f1ff462.json c9 259678c23b52861e8113951766c31f.json 9ea0d5298ba569ff11f61b96fe5632.json cc 3df4b3a2ab8874f82678cfafcc840c.json 7ff9949d3aefff37e4e918324cb982.json cd d79945df09f4b943aeeed8d7e983c5.json ce ba9891be0378e378bd5215b9502ffb.json cf e6bcac415fd4b2b084ec55c27baf3d.json d0 09bf9318e3e7656a9f5629374fa981.json d2 3d8c4c1c31655db6c9757e36ac39e6.json d3 53d94c8ba1e45353e649c23302bc4b.json d4 163d0fc4698700af86aaf746352fed.json 6e8a5d30ab9b6ec09b65ffc5f352fc.json d5 681576763fbe6965b0afb24c94c979.json 98789c91faf8a013056a6940705771.json f75e2550ceb0e1b4470a296ea836a9.json d6 f7105c4b7e39edfd6224b869ba52c6.json d7 5909da1335aa96bbfdd22a36d5c2cb.json a842455a20a8baf407e80efcb4b789.json d8 1db4e16dc20a9bbb19dc553cc03894.json 2d0bd7bd2e493491e7795a78d8afc0.json c14d537e88a3323b5f4bad39b99037.json d9 510068171c09397d9007f6861e30ea.json da 9f623383148ac028ca23e04f197c9e.json db f7165f0bea97be7b90830895c8c986.json dc 8310f9595e0a8b385d69ccfd7ad79f.json c0cf6003d4da09048001d53fcd4291.json dd 8b44fd7e29e18f7e878d8c92a7cf4d.json de 10c13c78a730fd063c98c8a1217ee7.json df d34843a9536f0b9fdb5449f7d8223e.json e0 96d9b5b193f8aff62f9bc97927f510.json e1 72ff85b45fbc40451a40d844dba1d7.json 7a2d238ccb4fb8ab23eca3a98bd2dc.json 86e1d15cacd7d49c30d7afccff7ddc.json a998707fbc780b2ec717e022d3215d.json f4c2dfd9e5f879c3a50b31d94d7c26.json e3 102acce233d9bb5ed2d85033191fbe.json 58835cfdfae1cea8704c7f131ac38f.json e4 126bb640faa8c351762339d2b8cd86.json 709e87725ec889ade24f6b6eba8613.json e5 65a5b233babd8397862dee7d797abc.json e6 4da9a80d20c6c6a4337efa8ba9e5f4.json e7 5ea499c2ac5ad08938d3231a4b5c2b.json 7ca8c52f919226ef829bc538480255.json fa4b7a6b96f9cd9e0eafadc3743523.json e9 4b550b53fdee3ad1b789123d3089f3.json 76924450a8e2b3de45bcf2dc45d75c.json eb 95207884ee03a5fb938cf573f9b3fc.json ec 244bf81b327e096dac1a8b0abde48f.json ed 206f7015f98d2cdf38aa2e213b135a.json 8811cb8b6cbb90172fc880da01e570.json f0 13a049fa9ccae12322ac740773374d.json 380afa0bf5747d89c2352f3b61b512.json 5df43f0f3877b38de11e586bd6d7eb.json a3d630a5e3dec1723745e44a3eb9ef.json cfa2e0ab431160484c156dc970be8f.json f2 5ffd0d2b92ae618cd38e98c10f2cf2.json cc00d576855fb223ed1d48ea5f1d93.json f3 55699b2ec3fb86b566cd076f6ecd66.json 713020fb1640439b7f67db82964226.json c762219fc5dc307e8babb5349742df.json f4 1001ab31455b738182154c905dca61.json 276c2321d514c3e36733b701e0dac9.json 306b0459659238322c6faa63ae4a70.json 4e8c566600de7e101d578f8036cf71.json cbb359ecd0de3fb3882dcdff4dc569.json f5 e30f7a853e43ff43ab190c80f5e408.json f6 47bf29be7d9085eee19a79e0b52ef7.json 93514cafca11458cc3d6cb664ecd64.json f7 adbbe873c8e976249c3ccffbf24ccc.json cb4d6048667b07f67b76a9ca87e880.json f8 a8588bc49d5a3fdf061a742b205931.json f9 978c9fabb927df33fbe334d31356ee.json a3d5403f7519a70c27ae797df9ec67.json fa 2bb7b1fd1baac21527be23887738a6.json 708b369b83c7162846241d045f9f41.json fb cbe96eff7c2160b2b95d82e5bf4bc5.json fc 51c3840072cd236efc77178c5ee3fc.json fe 0772f51bf5ef51322f4986a2e3bc6e.json be50fd452fd4d773ed4ec455e34859.json ff 63eb9413c56bfa65a2519b267fbbc1.json 89f9ae69da93022d65db72a880d388.json d2723f1cd283a418907419ff74749c.json e4b1990ad5787255cd197dff114738.json .gitpod.yml README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts model.ts tsconfig.json compile.js package-lock.json package.json dist global.e50bbfba.css global.e50bbfba.js index.html index.js logo-black.eab7a939.svg logo-white.7fec831f.svg src.e31bb0bc.css package.json src App.js assets logo-black.svg logo-white.svg components NavItem.js QuestItem.js config.js global.css index.html index.js main.test.js utils.js wallet login index.html Welcome to debugging React
# NearQuiz nearQuiz Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli nearQuiz ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `nearQuiz.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `nearQuiz.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account nearQuiz.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'nearQuiz.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
Peersyst_swisstype
.github pull_request_template.md | README.md lerna.json package-lock.json package.json packages essential CHANGELOG.md README.md index.d.ts package.json tsconfig.json react CHANGELOG.md README.md index.d.ts package.json tsconfig.json string CHANGELOG.md README.md index.d.ts package.json tsconfig.json scripts build.js tsconfig.json
# SwissType Your faithful Swiss Knife of types. Pick your favorite Swiss Type and enjoy your Typescript programming. But be careful, it's sharp! # @swisstype/essential Your faithful Swiss Knife of essential types. # @swisstype/string Your faithful Swiss Knife of string types. # @swisstype/react Your faithful Swiss Knife of react types.
Peersyst_NanoWallet
CHANGELOG.md ISSUE_TEMPLATE.md README.md build.js gulpfile.js package-lock.json package.json preload.js src app app.js components accountInput.component.js attachMosaic.component.js balance.component.js index.js invoice.component.js marketData.component.js messageArea.component.js multisigSelect.component.js news.component.js node.component.js simpleAndmultisigSelect.component.js txConfirmation.component.js config app.config.js app.constants.js app.run.js nw.js directives decodeMessage.directive.js feeInput.directive.js importAddressBookFile.directive.js importApostilleFiles.directive.js importNtyFile.directive.js index.js paginate.directive.js passwordInput.directive.js readWalletFiles.directive.js show-authed.directive.js signTransaction.directive.js tagLevy.directive.js tagTransaction.directive.js filters filters.js index.js layout app-view.html footer.component.js footer.html header.component.js header.html index.js lines lineImportanceTransfer.html lineMosaicDefinition.html lineMosaicSupply.html lineMultisigModification.html lineProvisionNamespace.html lineTransfer.html partials accountInput.html attachMosaic.html balance.html decodeMessage.html feeInput.html invoice.html marketData.html messageArea.html multisigSelect.html news.html node.html paginate.html passwordInput.html signTransaction.html simpleAndMultisigSelect.html txConfirmation.html modules NEMonster index.js setup NEMonster.config.js NEMonster.controller.js NEMonster.html account account.config.js account.controller.js account.html index.js addressBook addressBook.config.js addressBook.controller.js addressBook.html index.js apostille audit auditApostille.config.js auditApostille.controller.js auditApostille.html create createApostille.config.js createApostille.controller.js createApostille.html history apostilleHistory.config.js apostilleHistory.controller.js apostilleHistory.html index.js message apostilleMessage.config.js apostilleMessage.controller.js apostilleMessage.html catapultOptin catapultOptin catapultOptin.config.js catapultOptin.controller.js catapultOptin.html index.js dashboard dashboard.config.js dashboard.controller.js dashboard.html index.js domainNameSystem domainNameSystem.config.js domainNameSystem.controller.js domainNameSystem.html index.js search dnsSearch.config.js dnsSearch.controller.js dnsSearch.html exchanges changelly changelly.config.js changelly.controller.js changelly.html index.js shapeshift shapeshift.config.js shapeshift.controller.js shapeshift.html explorer accounts accountsExplorer.config.js accountsExplorer.controller.js accountsExplorer.html apostilles explorerApostilles.config.js explorerApostilles.controller.js explorerApostilles.html home explorerHome.config.js explorerHome.controller.js explorerHome.html index.js layout nav.component.js nav.html namespaces-mosaics namespaces-mosaics.config.js namespaces-mosaics.controller.js namespaces-mosaics.html transactions explorerTransactions.config.js explorerTransactions.controller.js explorerTransactions.html faq faq.config.js faq.controller.js faq.html index.js home home.config.js home.controller.js home.html index.js importWalletQrCode importQrCode.config.js importQrCode.controller.js index.html index.js importanceTransfer index.js multisig importanceTransfer.config.js importanceTransfer.controller.js importanceTransfer.html normal importanceTransfer.config.js importanceTransfer.controller.js importanceTransfer.html invoice index.js invoice.config.js invoice.controller.js invoice.html languages cn.js de.js en.js es.js index.js it.js jp.js nl.js pl.js ptbr.js ru.js uk.js ledger hw-app-nem.js hw-app-symbol.js index.js ledger.config.js ledger.controller.js ledger.html ledger.service.js optin BroadcastLedger.js OptInDTO.js cosigOptinDTOLedger.js namespaceOptinDTOLedger.js vrfOptinDTOLedger.js login index.js login.config.js login.controller.js login.html mosaics create createMosaic.config.js createMosaic.controller.js createMosaic.html edit editMosaic.config.js editMosaic.controller.js editMosaic.html index.js multisignature create createMultisig.config.js createMultisig.controller.js createMultisig.html edit editMultisig.config.js editMultisig.controller.js editMultisig.html index.js sign sign.config.js sign.controller.js sign.html namespaces create namespaces.config.js namespaces.controller.js namespaces.html index.js renew renew.config.js renew.controller.js renew.html offlineTransaction broadcast broadcast.config.js broadcast.controller.js broadcast.html create create.config.js create.controller.js create.html index.js portal index.js portal.config.js portal.controller.js portal.html signedMessage index.js sign sign.config.js sign.controller.js sign.html verify verify.config.js verify.controller.js verify.html signup index.js signup.config.js signup.controller.js signup.html transferTransaction index.js transferTransaction.config.js transferTransaction.controller.js transferTransaction.html trezor index.js trezor.config.js trezor.controller.js trezor.html trezor.service.js voting createPoll createPoll.config.js createPoll.controller.js createPoll.html index.js polls polls.config.js polls.controller.js polls.html services addressBook.service.js alert.service.js catapultOptin.service.js dataBridge.service.js dataStore.service.js index.js login.service.js nodes.service.js nty.service.js recipient.service.js voting.service.js votingUtils.service.js wallet.service.js walletBuilder.service.js utils CryptoHelpers.js CryptoHelpersLegacy.js exchanges.js helpers.js languages.js nty.js css NEMonster.css bootstrap.min.css font-awesome.min.css fonts fontawesome-webfont.svg ngToast.min.css images symbol.svg package.json start.html vendors FileSaver.min.js connect.js jszip.min.js kjua.min.js qrcode.js tests data accountData.js wallet.js specs CryptoHelpers.spec.js ImportanceTransferModule.spec.js createMosaicModule.spec.js editMosaicModule.spec.js ledger.spec.js namespaceModule.spec.js transferTransactionModule.spec.js wallet.spec.js walletBuilder.spec.js start.html
# NEM Wallet # ### How to use the NEM Wallet ? ### After downloading the latest version here https://forum.nem.io/t/nano-wallet-beta-1-1-11-5-000-xem-bug-bounty/2791, extract the NEM-Wallet folder from the archive, then you can simply click on start.html to open the app in your default browser. No installation or local server needed. ### How to import NCC wallet ? ### Open NCC and your wallet, clicking on user icon should reveal a drop-down menu with "Export for Lightwallet". Once your have your wallet (.json format), open the NEM Wallet and import the file from the login page. It'll ask for an upgrade and trigger the download of your updated wallet. Do not delete your old NCC wallet and keep it safe somewhere. ### Imported accounts that are already harvesting using NCC ### NCC is using a different way to generate the remote associated with an account. NEM Wallet uses BIP32 to generate it deterministically and make everything easier. In order to manage and monitor harvesting, you'll need to deactivate the old remote account from NCC and activate your new remote account from the NEM Wallet. Alternatively you can use a custom delegated public key in the NEM Wallet importance transaction page. **/!\ Main network: Please note that if you are part of the Supernodes program you'll need to re-enroll your node using your new delegated public key.** ### How to update the NEM Wallet ? ### Before update make sure that you don't have any wallets stored into the NEM-Wallet folder (you can place them anywhere you want). Then, just delete old version and unzip new version. ### Dashboard is empty and no balance is showing ### It is probably that the node you are connected to is down. Look at the navigation bar, at the top of the page. If the circle next to `Node` is red, click on it and select another node from the list. # Developers # ### Build from source ### 1) Install gulp <pre>npm install -g gulp-cli</pre> 2) Open a console to the path of the NEM-Wallet folder and install all the needed dependencies <pre>npm install</pre> 3) Build: <pre>gulp</pre> ##### OR ##### 4) Run the NEM Wallet as App (packaged with chromium browser) <pre>npm run devApp</pre> ##### OR ##### 5) Build NEM Wallet apps, default set to : win64,osx64,linux64 <pre>gulp build-app</pre> 6) Build NEM Wallet Electron apps (only Electron verision support Ledger wallets), default build for MacOS, Windows and Linux <pre>npm run release</pre> ### Known issues ### - Sometimes, depending the node used, unconfirmed data to sign is not incoming from websocket
Learn-NEAR-Hispano_NCD2--ConnectIoT
.cache 0a ef6a5257c569e0a3869d2bd4358962.json 0b 46b0f669dbdf7973b1861cff27eabf.json 0d a1f476b9a50fce603bd425e84c11ed.json 11 15e2bbcbaacab4516e5f83df779c2b.json 14 a904ff3b797f3e027ace8c2cab5e84.json 15 2f0d4ea5db93a16bb214cc4f2b92bc.json 70f6a510e5aa6f83597222c744c9d9.json 16 54f41d4f544b3ff8ac87937810d4f0.json 17 8951bb94a5f0fd733a11ca0203a12d.json c25464edc8d4471cb0edb8118ced91.json 25 c3870514da06e78ca653c74c6eef0d.json c568638344cba4b155949f59e413cd.json 27 88b6e98e46dfdc2531a3cb259374be.json eb3c821682cb31f37bcbe2e95577b9.json 28 93bada5d6b7826d00ded3d77ac1158.json 29 03937b2914d7d20aedd9a700182e2b.json 2c ac8c343ca060d86cbf4d7d77494e93.json 2f 451cdec484f773ac370525536010f3.json a72407af3f31909f9f185ddd101655.json 31 b379b13655d81e90a53b4bcd88d013.json 32 212d0f8dffa36a997e1c3bbb071f09.json 2c24f07217787157180eefb8ca4b28.json 33 58c2a505cf5f67b62562e1c3620491.json e86f8b5bd06725fb35785bd8e19f05.json 3a 68bbcaf090726d58530a575aa820f4.json 3c 74748148d94748548ec7aee984008e.json 3d 30577862439fe97c7f8bc355f809ca.json 42 2fa699704ecb01a09fa029f61b70ee.json 44 00c7305adc0e69e5f2801a52012bc1.json e228745a72238843916564f7d9939a.json 46 9e4def45a1c257e34187481b50a9d0.json 49 de346b9d167cedbab28cb786376581.json 4b 0c167d069d7cc83a25e4dfe0212a3c.json 4c 48070024e7b43445576dda4a2211ce.json 4f e0daa870dc93c38d8ef13fa3f69d04.json 50 24f544ad6e215f8ce449300dc3f79d.json 52 d8e97d9e6f28f988f0b3739cce55cf.json 57 bec642824ebe0124a890ee04654323.json 59 4a1e7ab2baf1696b2533b10aecf3dc.json 5a 22551b884dd1fcc79a07209e215db1.json 62 14ce70ba972abb5f7ed080fcc042e9.json 67 f242d4ce39f73502b8513021565e81.json 6a 232b56b2425781267a6bbc0286052c.json 70 70eaeffb79b0eb279196781bfb9192.json 73 d621b800d5136ced9880104ad781df.json 76 d5ae003d43d273b9f0a6345862881b.json 78 fb18435a887896ecc89afce5760f35.json 7a b383320498574694be4379fd94b1db.json 82 4fd1648c87b0407c5a1fd43ea85e62.json 83 86e02dc1b3278facf03fd2bd963d83.json 8a 13cacbae6e30cd68b148ca0ec8edbc.json f45a35c3b7a767f47fb37af697a201.json 8f 8ba4cb88bb34fabce8ad9479228d85.json 91 20dfd55b2bfe73c29e26062662c181.json 961fc45ef4452f24bab5ec3d77fb57.json fbb7477cad406ba33f756383abc805.json 98 42f9c5a53580bb8a3c7870f0a6d2ab.json 99 936dc9062702bfcb7ba121cb3f06c5.json 9a d8582b802edc43614ec160c6922aa0.json 9d ffe2003cb75e512c8d3383ef455d48.json a2 3c5e8616e7393b53dd3515f19e634f.json a4 38c1e818ed9429b2cdd14e4e1df553.json ad 68a33b58d686b81d3546345f01c054.json 8e4da9b487c2b042ea64c2198213d8.json b1 32f06d2a375c359729945da50058b5.json 42b6856aa2439f373fede82cde9a48.json e36b44b3d068d816874dcf106872ac.json b2 c5e7964ea8344e69059eb938e77911.json bb 841168d71d3b9b75a595825910da7a.json bf a0da81e162611d6d01b6b75f46ce9f.json c1 4b59faa75f91c0694041df414fd583.json c3 69fd3f57ea7f972827315a7af892fc.json 8d319de6f7dc74f17045eb815bb6e9.json c6 91cd034927c2e2b1375e8c99f46fad.json aea2806ddf449ff7f82bacd1fa1dbd.json c8 123f23b57d40461868adee05a1b1f2.json cb 7d98648a4b55a045ba31e820234105.json 818405f66f547f9e60990f9176e05d.json cc 4d796fcc3f3bb7b23c5572741cfd80.json cd db1b674168f095c27710359c1fab99.json d3 98f53950c8d5c0e92ca838d0a35dda.json d9 5c152b271c7072b295e917c4b79d8b.json df acdad9c26c5576a5054021332401b8.json e1 b680c33ce9a6de6414cd3f89d4fd38.json e3 61e30af4e41dc501b225ce1dc0fe35.json f3 96956346662717e45bdd67cc3a395a.json fa 81a133bb00510bf0040514ed253447.json fc c7372786cdf98a522b71254439d2ab.json fd 793b7b78c6a76ce456df2f14b48f0e.json README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts model.ts tsconfig.json compile.js package-lock.json package.json neardev dev-account.env shared-test-staging test.near.json shared-test test.near.json package.json
# 🚧 connectiot ================== > Proyecto realizado para el NCD Bootcamp NEAR Hispano. # ConnectIoT es un servicio que nos permite tener acceso, por medio de la blockchain ,a diferentes dispositivos IoT y monitorearlos de acuerdo a los datos que se de van tomando con el tiempo # ConnectIoT permite realizar las siguientes operaciones: 1. crear nuevos dispositivos 2. cambiar argumentos de los dispositivos ya creados 3. ver el tipo de dispositivo 4. borrar dispositivos 5. autenticar usuarios que quieran ingresar a los dispositivos 6. pedir permiso para entrar a un dispositivo 7. validar el tipo de dispositivo de acuerdo a los datos que arroja 8. ver las solicitudes de acceso 🏁Prerrequisitos 1. node.js >=12 instalado (https://nodejs.org) 2. yarn instalado ```bash npm install --global yarn ``` 3. instalar dependencias ```bash yarn install --frozen-lockfile ``` 4. crear una cuenta de NEAR en [testnet](https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account) 5. instalar NEAR CLI ```bash yarn install --global near-cli ``` 6. autorizar app para dar acceso a la cuenta de NEAR ```bash near login ``` 🐑 Clonar el Repositorio ```bash git clone https://github.com/EbanCuMo/ConnectIoT cd ConnectIoT ``` 🏗 instalar y compilar el contrato ```bash yarn install yarn build:contract:debug ``` 🚀 Deployar el contrato ```bash yarn dev:deploy:contract ``` 🚂 Correr comandos Una vez deployado el contrato, usaremos el Account Id devuelto por la operacion para ejecutar los comandos, que será el account Id del contrato [será utilizado como CONTRACT_ACCOUNT_ID en los ejemplos de comandos] Utilizaremos OWNER_ACCOUNT_ID para identificar el account Id que utilizamos para ser dueños de un dispositivo. Utilizaremos YOUR_ACCOUNT_ID para identificar el account Id que utilizamos para solicitar acceso a un dispositivo. ### Crear Dispositivo Nuevo ```bash near call CONTRACT_ACCOUNT_ID setState '{"ownerId": "OWNER_ACCOUNT_ID","deviceId": "myOximeter","deviceType": "Oximeter","timestamp": "Thu Sep 30 2021 20:09:33 GMT-0500","args": {"bpm":75,"spo2":99}}' --accountId OWNER_ACCOUNT_ID ``` ### Cambiar argumentos de un dispositivo ```bash near call CONTRACT_ACCOUNT_ID updateState '{"deviceId":"myOximeter","deviceType": "Oximeter","timestamp": "Thu Sep 30 2021 20:09:33 GMT-0500","args": {"bpm":70,"spo2":98}}' --accountId OWNER_ACCOUNT_ID ``` ### Ver arguementos de dispositivo ```bash near call CONTRACT_ACCOUNT_ID getState '{"deviceId":"myOximeter","deviceType": "Oximeter"}' --accountId OWNER_ACCOUNT_ID ``` ### Borrar un dispositivo ```bash near call CONTRACT_ACCOUNT_ID deleteDevice'{"deviceId":"myOximeter","deviceType": "Oximeter"}' --accountId OWNER_ACCOUNT_ID ``` ### Autenticar usuarios que quieren entrar al dispositivo ```bash near call CONTRACT_ACCOUNT_ID authenticate '{"deviceId": "myOximeter","deviceType": "Oximeter","accountId": "ACCOUNT_ID"}' --accountId OWNER_COOUNT_ID ``` ### Pedir permiso para acceder a un dispositivo ```bash near call CONTRACT_ACCOUNT_ID askForPermission '{"deviceId": "myOximeter","deviceType": "Oximeter"}' --accountId YOUR_ACCOUNT_ID ``` ### Validar tipo de dispositivo de acuerdo a sus argumentos ```bash near call CONTRACT_ACCOUNT_ID validateData '{"deviceId": "myOximeter","deviceType": "Oximeter","jsonArgs": "{bpm:70,spo2:98}"}' --accountId OWNER_ACCOUNT_ID ``` ### Ver solicitudes de acceso ```bash near call CONTRACT_ACCOUNT_ID getRequests '{"deviceId": "myOximeter","deviceType": "Oximeter"}' --accountId OWNER_ACOUNT_ID ``` ### Caso de uso: ConnectIoT ayudará mucho al sector médico y a los servicios que ofrecen, ya que con este smart contract se puede acceder a los datos continuos qur toman los Smart Devices de los pacientes. Con esto los Médicos podrán saber niveles de oxigenación, temperatura, peso, hidratación, actividad fisica minima, entre muchos más. Con esto los servicios médicos podran atacar de manera más eficiente a los problemas que se enfrenten y tendran todo un registro de datos validados y reales de sus pacientes. Los diseños de esta aplicación se pueden ver en el siguiente link: https://marvelapp.com/project/5880174 connectiot Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli
Kiews-OU_NEAR-Carrd-Donate
.eslintrc.yml .github dependabot.yml workflows deploy.yml tests.yml .gitpod.yml .travis.yml README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts guestbook.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.js carrd carrd-donate-invoke.html carrd-donate-messages.html carrd-donate-panel.html carrd-donatev2.css carrd-donatev2.js neardev shared-test-staging test.near.json shared-test test.near.json package.json src App.js config.js index.html index.js tests integration App-integration.test.js ui App-ui.test.js
Introduction ========== If you have a project to fundraise, the Near Protocol is a very suitable platform for this task. Near Protocol's ability to embed custom functions in the blockchain, Near Protocol, can not only easy transfer money between wallets but also, for example, make a rating of the best investors or philanthropists to stimulate competition between them, display the amount needed to fundraise in real-time, and much more! Now I will show how easy it is to implement these functions with Near. I have created a project ["Let's help homeless pets"](https://near-donate.carrd.co/), with the next features: 1. `addDonate` Make charitable contributions. But instead the base's "send" function of Near Protocol, I created a function - "addDonate", that can add to the transaction name of the philanthropist, date, and message with wishes. 2. `getDonateBalance` Display the amount of raised funds in real-time. 3. `getNumberPhilanthropists` Display the number of philanthropists in real time. 4. `getTopPhilanthropists` The top list of philanthropists, sorted by amount. How to do this and how it works to see on the [video/en](https://www.youtube.com/watch?v=GHJN7xU5reU), [video/ua](https://www.youtube.com/watch?v=_uypyNrGXrQ) And read step by step manual below. Near Carrd Donate Module ========== Near Donate Module for Carrd CMS is a charity fundraising project with a rating of philanthropists. It has some features. Login with Near protocol. Opportunity to donate a certain amount Near. Users can also see the latest donation transactions and the top 5 philanthropists. Prepare Near contract ========== To prepare Near contract, you shoud clone [repository](https://github.com/andersenbel/near-carrd-donate) git clone [email protected]:andersenbel/near-carrd-donate And modify settings in `src/config.js`: const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-contact-name.testnet'; Next, you should to prepare envoriment accoording [Near Quick Start](#near-quick-start) part below, and deploy contract: yarn deploy:contract near deploy --accountId carrd-donate.testnet --wasmFile ./out/main.wasm If all right, you can run the command: near view your-contract.testnet getTopPhilanthropists And get it: View call: your-contract.testnet.getTopPhilanthropists() [] Carrd integration ========== Near project can be integrated with [Carrd.co CMS](https://carrd.co/ ). You shoud to add three embeded block: 1. Near panel and input gorm for authorisied users `card/carrd-donate-panel.html` 2. Output donates lists area `card/carrd-donate-messages.html` 3. Javascript code for start `card/carrd-donate-invoke.html` Also You shoud to modify carrd-donate-invoke.html for your settings: <link media="all" rel="stylesheet" href="https://cdn.jsdelivr.net/gh/andersenbel/near-carrd-donate/carrd/carrd-donate-1.css" /> <script type="application/javascript" src="https://cdn.jsdelivr.net/gh/andersenbel/near-carrd-donate/carrd/carrd-donate-1.js"></script> <script> new add_near({ networkId: "testnet", keyStore: false, nodeUrl: "https://rpc.testnet.near.org", walletUrl: "https://wallet.testnet.near.org", helperUrl: "https://helper.testnet.near.org", explorerUrl: "https://explorer.testnet.near.org", }, { con_name: "your-contract-name.testnet", app_name: "Example App", success_url: "https://your-site.com.carrd.co/#success", failure_url: "https://your-site.com.carrd.co/#failure", }, { "btn_signin": "near_protocol_signin", "btn_signout": "near_protocol_signout", "btn_donate": "buttons02", "input_amount": "form01-name", "input_sender_name": "near_protocol_input_your_name", "input_message_text": "near_protocol_input_message_text", "text_username": "near_protocol_username", "text_number_messages": "text10", "text_balance": "text06", "html_top_messages": "near_protocol_html_top_messages", "html_last_messages": "near_protocol_html_last_messages", }) </script> Near Quick Start =========== Based on near guest-book repsitory To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`) 2. Run the local development server: `yarn && yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app. Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html](/src/index.html) is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli -------------------------- You need near-cli installed globally. Here's how: npm install --global near-cli This will give you the `near` [CLI] tool. Ensure that it's installed with: near --version Step 1: Create an account for the contract ------------------------------------------ Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account. Now authorize NEAR CLI for this new account, and follow the instructions it gives you: near login Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!' Step 3: change remote URL if you cloned this repo ------------------------- Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to GitHub Pages from the command line. 1) go to GitHub and create a new repository for this project 2) open your terminal and in the root of this project enter the following: $ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git` Step 4: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contracts to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. [NEAR]: https://near.org/ [yarn]: https://yarnpkg.com/ [AssemblyScript]: https://www.assemblyscript.org/introduction.html [React]: https://reactjs.org [smart contract docs]: https://docs.near.org/docs/develop/contracts/overview [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.near.org [near-cli]: https://github.com/near/near-cli [CLI]: https://www.w3schools.com/whatis/whatis_cli.asp [create-near-app]: https://github.com/near/create-near-app [carrd.co]: https://carrd.co/
mohammed-arham_BlockchainVotingSystem
blockvote .gitpod.yml README.md babel.config.js contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js node_modules .bin acorn.cmd acorn.ps1 asb.cmd asb.ps1 asbuild.cmd asbuild.ps1 asc.cmd asc.ps1 asinit.cmd asinit.ps1 asp.cmd asp.ps1 aspect.cmd aspect.ps1 assemblyscript-build.cmd assemblyscript-build.ps1 eslint.cmd eslint.ps1 esparse.cmd esparse.ps1 esvalidate.cmd esvalidate.ps1 js-yaml.cmd js-yaml.ps1 mkdirp.cmd mkdirp.ps1 near-vm-as.cmd near-vm-as.ps1 near-vm.cmd near-vm.ps1 nearley-railroad.cmd nearley-railroad.ps1 nearley-test.cmd nearley-test.ps1 nearley-unparse.cmd nearley-unparse.ps1 nearleyc.cmd nearleyc.ps1 node-which.cmd node-which.ps1 resolve.cmd resolve.ps1 rimraf.cmd rimraf.ps1 semver.cmd semver.ps1 shjs.cmd shjs.ps1 wasm-opt.cmd wasm-opt.ps1 .package-lock.json @as-covers assembly CONTRIBUTING.md README.md index.ts package.json tsconfig.json core CONTRIBUTING.md README.md package.json glue README.md lib index.d.ts index.js package.json transform README.md lib index.d.ts index.js util.d.ts util.js node_modules visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js toString.d.ts toString.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformRange.d.ts transformRange.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json package.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @eslint eslintrc CHANGELOG.md README.md conf config-schema.js environments.js eslint-all.js eslint-recommended.js lib cascading-config-array-factory.js config-array-factory.js config-array config-array.js config-dependency.js extracted-config.js ignore-pattern.js index.js override-tester.js flat-compat.js index.js shared ajv.js config-ops.js config-validator.js deprecation-warnings.js naming.js relative-module-resolver.js types.js package.json @humanwhocodes config-array README.md api.js package.json object-schema .eslintrc.js .github workflows nodejs-test.yml release-please.yml CHANGELOG.md README.md package.json src index.js merge-strategy.js object-schema.js validation-strategy.js tests merge-strategy.js object-schema.js validation-strategy.js acorn-jsx README.md index.d.ts index.js package.json xhtml.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json as-bignum README.md assembly __tests__ as-pect.d.ts i128.spec.as.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts package.json asbuild README.md dist cli.d.ts cli.js commands build.d.ts build.js fmt.d.ts fmt.js index.d.ts index.js init cmd.d.ts cmd.js files asconfigJson.d.ts asconfigJson.js aspecConfig.d.ts aspecConfig.js assembly_files.d.ts assembly_files.js eslintConfig.d.ts eslintConfig.js gitignores.d.ts gitignores.js index.d.ts index.js indexJs.d.ts indexJs.js packageJson.d.ts packageJson.js test_files.d.ts test_files.js index.d.ts index.js interfaces.d.ts interfaces.js run.d.ts run.js test.d.ts test.js index.d.ts index.js main.d.ts main.js utils.d.ts utils.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json assemblyscript-json .eslintrc.js .travis.yml README.md assembly JSON.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json temp-docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md assemblyscript-regex .eslintrc.js .github workflows benchmark.yml release.yml test.yml README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __spec_tests__ generated.spec.ts __tests__ alterations.spec.ts as-pect.d.ts boundary-assertions.spec.ts capture-group.spec.ts character-classes.spec.ts character-sets.spec.ts characters.ts empty.ts quantifiers.spec.ts range-quantifiers.spec.ts regex.spec.ts utils.ts char.ts env.ts index.ts nfa matcher.ts nfa.ts types.ts walker.ts parser node.ts parser.ts string-iterator.ts walker.ts regexp.ts tsconfig.json util.ts benchmark benchmark.js package.json spec test-generator.js ts index.ts tsconfig.json assemblyscript-temporal .github workflows node.js.yml release.yml .vscode launch.json README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __tests__ README.md as-pect.d.ts date.spec.ts duration.spec.ts empty.ts plaindate.spec.ts plaindatetime.spec.ts plainmonthday.spec.ts plaintime.spec.ts plainyearmonth.spec.ts timezone.spec.ts zoneddatetime.spec.ts constants.ts date.ts duration.ts enums.ts env.ts index.ts instant.ts now.ts plaindate.ts plaindatetime.ts plainmonthday.ts plaintime.ts plainyearmonth.ts timezone.ts tsconfig.json tz __tests__ index.spec.ts rule.spec.ts zone.spec.ts iana.ts index.ts rule.ts zone.ts utils.ts zoneddatetime.ts development.md package.json tzdb README.md iana theory.html zoneinfo2tdf.pl assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md bin rtplot.js index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json astral-regex index.d.ts index.js package.json readme.md axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js CHANGELOG.md README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json csv-stringify README.md lib browser index.js sync.js es5 index.d.ts index.js sync.d.ts sync.js index.d.ts index.js sync.d.ts sync.js package.json debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js diff CONTRIBUTING.md README.md dist diff.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js doctrine CHANGELOG.md README.md lib doctrine.js typed.js utility.js package.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js enquirer CHANGELOG.md README.md index.d.ts index.js lib ansi.js combos.js completer.js interpolate.js keypress.js placeholder.js prompt.js prompts autocomplete.js basicauth.js confirm.js editable.js form.js index.js input.js invisible.js list.js multiselect.js numeral.js password.js quiz.js scale.js select.js snippet.js sort.js survey.js text.js toggle.js render.js roles.js state.js styles.js symbols.js theme.js timer.js types array.js auth.js boolean.js index.js number.js string.js utils.js package.json env-paths index.d.ts index.js package.json readme.md escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js package.json eslint-utils README.md index.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json eslint CHANGELOG.md README.md bin eslint.js conf category-list.json config-schema.js default-cli-options.js eslint-all.js eslint-recommended.js replacements.json lib api.js cli-engine cli-engine.js file-enumerator.js formatters checkstyle.js codeframe.js compact.js html.js jslint-xml.js json-with-metadata.js json.js junit.js stylish.js table.js tap.js unix.js visualstudio.js hash.js index.js lint-result-cache.js load-rules.js xml-escape.js cli.js config default-config.js flat-config-array.js flat-config-schema.js rule-validator.js eslint eslint.js index.js init autoconfig.js config-file.js config-initializer.js config-rule.js npm-utils.js source-code-utils.js linter apply-disable-directives.js code-path-analysis code-path-analyzer.js code-path-segment.js code-path-state.js code-path.js debug-helpers.js fork-context.js id-generator.js config-comment-parser.js index.js interpolate.js linter.js node-event-generator.js report-translator.js rule-fixer.js rules.js safe-emitter.js source-code-fixer.js timing.js options.js rule-tester index.js rule-tester.js rules accessor-pairs.js array-bracket-newline.js array-bracket-spacing.js array-callback-return.js array-element-newline.js arrow-body-style.js arrow-parens.js arrow-spacing.js block-scoped-var.js block-spacing.js brace-style.js callback-return.js camelcase.js capitalized-comments.js class-methods-use-this.js comma-dangle.js comma-spacing.js comma-style.js complexity.js computed-property-spacing.js consistent-return.js consistent-this.js constructor-super.js curly.js default-case-last.js default-case.js default-param-last.js dot-location.js dot-notation.js eol-last.js eqeqeq.js for-direction.js func-call-spacing.js func-name-matching.js func-names.js func-style.js function-call-argument-newline.js function-paren-newline.js generator-star-spacing.js getter-return.js global-require.js grouped-accessor-pairs.js guard-for-in.js handle-callback-err.js id-blacklist.js id-denylist.js id-length.js id-match.js implicit-arrow-linebreak.js indent-legacy.js indent.js index.js init-declarations.js jsx-quotes.js key-spacing.js keyword-spacing.js line-comment-position.js linebreak-style.js lines-around-comment.js lines-around-directive.js lines-between-class-members.js max-classes-per-file.js max-depth.js max-len.js max-lines-per-function.js max-lines.js max-nested-callbacks.js max-params.js max-statements-per-line.js max-statements.js multiline-comment-style.js multiline-ternary.js new-cap.js new-parens.js newline-after-var.js newline-before-return.js newline-per-chained-call.js no-alert.js no-array-constructor.js no-async-promise-executor.js no-await-in-loop.js no-bitwise.js no-buffer-constructor.js no-caller.js no-case-declarations.js no-catch-shadow.js no-class-assign.js no-compare-neg-zero.js no-cond-assign.js no-confusing-arrow.js no-console.js no-const-assign.js no-constant-condition.js no-constructor-return.js no-continue.js no-control-regex.js no-debugger.js no-delete-var.js no-div-regex.js no-dupe-args.js no-dupe-class-members.js no-dupe-else-if.js no-dupe-keys.js no-duplicate-case.js no-duplicate-imports.js no-else-return.js no-empty-character-class.js no-empty-function.js no-empty-pattern.js no-empty.js no-eq-null.js no-eval.js no-ex-assign.js no-extend-native.js no-extra-bind.js no-extra-boolean-cast.js no-extra-label.js no-extra-parens.js no-extra-semi.js no-fallthrough.js no-floating-decimal.js no-func-assign.js no-global-assign.js no-implicit-coercion.js no-implicit-globals.js no-implied-eval.js no-import-assign.js no-inline-comments.js no-inner-declarations.js no-invalid-regexp.js no-invalid-this.js no-irregular-whitespace.js no-iterator.js no-label-var.js no-labels.js no-lone-blocks.js no-lonely-if.js no-loop-func.js no-loss-of-precision.js no-magic-numbers.js no-misleading-character-class.js no-mixed-operators.js no-mixed-requires.js no-mixed-spaces-and-tabs.js no-multi-assign.js no-multi-spaces.js no-multi-str.js no-multiple-empty-lines.js no-native-reassign.js no-negated-condition.js no-negated-in-lhs.js no-nested-ternary.js no-new-func.js no-new-object.js no-new-require.js no-new-symbol.js no-new-wrappers.js no-new.js no-nonoctal-decimal-escape.js no-obj-calls.js no-octal-escape.js no-octal.js no-param-reassign.js no-path-concat.js no-plusplus.js no-process-env.js no-process-exit.js no-promise-executor-return.js no-proto.js no-prototype-builtins.js no-redeclare.js no-regex-spaces.js no-restricted-exports.js no-restricted-globals.js no-restricted-imports.js no-restricted-modules.js no-restricted-properties.js no-restricted-syntax.js no-return-assign.js no-return-await.js no-script-url.js no-self-assign.js no-self-compare.js no-sequences.js no-setter-return.js no-shadow-restricted-names.js no-shadow.js no-spaced-func.js no-sparse-arrays.js no-sync.js no-tabs.js no-template-curly-in-string.js no-ternary.js no-this-before-super.js no-throw-literal.js no-trailing-spaces.js no-undef-init.js no-undef.js no-undefined.js no-underscore-dangle.js no-unexpected-multiline.js no-unmodified-loop-condition.js no-unneeded-ternary.js no-unreachable-loop.js no-unreachable.js no-unsafe-finally.js no-unsafe-negation.js no-unsafe-optional-chaining.js no-unused-expressions.js no-unused-labels.js no-unused-vars.js no-use-before-define.js no-useless-backreference.js no-useless-call.js no-useless-catch.js no-useless-computed-key.js no-useless-concat.js no-useless-constructor.js no-useless-escape.js no-useless-rename.js no-useless-return.js no-var.js no-void.js no-warning-comments.js no-whitespace-before-property.js no-with.js nonblock-statement-body-position.js object-curly-newline.js object-curly-spacing.js object-property-newline.js object-shorthand.js one-var-declaration-per-line.js one-var.js operator-assignment.js operator-linebreak.js padded-blocks.js padding-line-between-statements.js prefer-arrow-callback.js prefer-const.js prefer-destructuring.js prefer-exponentiation-operator.js prefer-named-capture-group.js prefer-numeric-literals.js prefer-object-spread.js prefer-promise-reject-errors.js prefer-reflect.js prefer-regex-literals.js prefer-rest-params.js prefer-spread.js prefer-template.js quote-props.js quotes.js radix.js require-atomic-updates.js require-await.js require-jsdoc.js require-unicode-regexp.js require-yield.js rest-spread-spacing.js semi-spacing.js semi-style.js semi.js sort-imports.js sort-keys.js sort-vars.js space-before-blocks.js space-before-function-paren.js space-in-parens.js space-infix-ops.js space-unary-ops.js spaced-comment.js strict.js switch-colon-spacing.js symbol-description.js template-curly-spacing.js template-tag-spacing.js unicode-bom.js use-isnan.js utils ast-utils.js fix-tracker.js keywords.js lazy-loading-rule-map.js patterns letters.js unicode index.js is-combining-character.js is-emoji-modifier.js is-regional-indicator-symbol.js is-surrogate-pair.js valid-jsdoc.js valid-typeof.js vars-on-top.js wrap-iife.js wrap-regex.js yield-star-spacing.js yoda.js shared ajv.js ast-utils.js config-validator.js deprecation-warnings.js logging.js relative-module-resolver.js runtime-info.js string-utils.js traverser.js types.js source-code index.js source-code.js token-store backward-token-comment-cursor.js backward-token-cursor.js cursor.js cursors.js decorative-cursor.js filter-cursor.js forward-token-comment-cursor.js forward-token-cursor.js index.js limit-cursor.js padded-token-cursor.js skip-cursor.js utils.js messages all-files-ignored.js extend-config-missing.js failed-to-read-json.js file-not-found.js no-config-found.js plugin-conflict.js plugin-invalid.js plugin-missing.js print-config-with-directory-path.js whitespace-found.js package.json espree CHANGELOG.md README.md espree.js lib ast-node-types.js espree.js features.js options.js token-translator.js visitor-keys.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esquery README.md dist esquery.esm.js esquery.esm.min.js esquery.js esquery.lite.js esquery.lite.min.js esquery.min.js license.txt node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json parser.js esrecurse README.md esrecurse.js gulpfile.babel.js node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json estraverse README.md estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-deep-equal README.md es6 index.d.ts index.js react.d.ts react.js index.d.ts index.js package.json react.d.ts react.js fast-json-stable-stringify .eslintrc.yml .github FUNDING.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.d.ts index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json file-entry-cache README.md cache.js changelog.md package.json find-up index.d.ts index.js package.json readme.md flat-cache README.md changelog.md package.json src cache.js del.js utils.js flatted .github FUNDING.yml workflows node.js.yml README.md SPECS.md cjs index.js package.json es.js esm index.js index.js min.js package.json php flatted.php types.d.ts follow-redirects README.md http.js https.js index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js ms index.js license.md package.json readme.md package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js functional-red-black-tree README.md bench test.js package.json rbtree.js test test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globals globals.json index.d.ts index.js package.json readme.md has-flag index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hasurl README.md index.js package.json ignore CHANGELOG.md README.md index.d.ts index.js legacy.js package.json import-fresh index.d.ts index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json interpret README.md index.js mjs-stub.js package.json is-core-module CHANGELOG.md README.md core.json index.js package.json test index.js is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.js package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json js-tokens CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-stable-stringify-without-jsonify .travis.yml example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js replacer.js space.js str.js to-json.js levn README.md lib cast.js index.js parse-string.js package.json line-column README.md lib line-column.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.merge README.md index.js package.json lodash.sortby README.md index.js package.json lodash.truncate README.md index.js package.json long README.md dist long.js index.js package.json src long.js lru-cache README.md index.js package.json minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md natural-compare README.md index.js package.json near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt empty.ts generic.ts includeBytes.spec.ts main.ts max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts json.lib.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts maxHeap.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts datetime.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ empty.ts exportAs.ts model.ts sentences.ts singleton copy.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md parent-module index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-key index.d.ts index.js package.json readme.md path-parse README.md index.js package.json prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json rechoir .travis.yml README.md index.js lib extension.js normalize.js register.js package.json regexpp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json require-from-string index.js package.json readme.md require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve-from index.js package.json readme.md resolve .github FUNDING.yml SECURITY.md appveyor.yml async.js example async.js sync.js index.js lib async.js caller.js core.js core.json homedir.js is-core.js node-modules-paths.js normalize-options.js sync.js package.json sync.js test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js home_paths.js home_paths_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json malformed_package_json index.js package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json semver README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md shelljs CHANGELOG.md README.md commands.js global.js make.js package.json plugin.js shell.js src cat.js cd.js chmod.js common.js cp.js dirs.js echo.js error.js exec-child.js exec.js find.js grep.js head.js ln.js ls.js mkdir.js mv.js popd.js pushd.js pwd.js rm.js sed.js set.js sort.js tail.js tempdir.js test.js to.js toEnd.js touch.js uniq.js which.js slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md supports-preserve-symlinks-flag .github FUNDING.yml CHANGELOG.md README.md browser.js index.js package.json test index.js table README.md dist src alignSpanningCell.d.ts alignSpanningCell.js alignString.d.ts alignString.js alignTableData.d.ts alignTableData.js calculateCellHeight.d.ts calculateCellHeight.js calculateMaximumColumnWidths.d.ts calculateMaximumColumnWidths.js calculateOutputColumnWidths.d.ts calculateOutputColumnWidths.js calculateRowHeights.d.ts calculateRowHeights.js calculateSpanningCellWidth.d.ts calculateSpanningCellWidth.js createStream.d.ts createStream.js drawBorder.d.ts drawBorder.js drawContent.d.ts drawContent.js drawRow.d.ts drawRow.js drawTable.d.ts drawTable.js generated validators.d.ts validators.js getBorderCharacters.d.ts getBorderCharacters.js index.d.ts index.js injectHeaderConfig.d.ts injectHeaderConfig.js makeRangeConfig.d.ts makeRangeConfig.js makeStreamConfig.d.ts makeStreamConfig.js makeTableConfig.d.ts makeTableConfig.js mapDataUsingRowHeights.d.ts mapDataUsingRowHeights.js padTableData.d.ts padTableData.js schemas config.json shared.json streamConfig.json spanningCellManager.d.ts spanningCellManager.js stringifyTableData.d.ts stringifyTableData.js table.d.ts table.js truncateTableData.d.ts truncateTableData.js types api.d.ts api.js internal.d.ts internal.js utils.d.ts utils.js validateConfig.d.ts validateConfig.js validateSpanningCellConfig.d.ts validateSpanningCellConfig.js validateTableData.d.ts validateTableData.js wrapCell.d.ts wrapCell.js wrapString.d.ts wrapString.js wrapWord.d.ts wrapWord.js node_modules ajv .runkit_example.js README.md dist 2019.d.ts 2019.js 2020.d.ts 2020.js ajv.d.ts ajv.js compile codegen code.d.ts code.js index.d.ts index.js scope.d.ts scope.js errors.d.ts errors.js index.d.ts index.js jtd parse.d.ts parse.js serialize.d.ts serialize.js types.d.ts types.js names.d.ts names.js ref_error.d.ts ref_error.js resolve.d.ts resolve.js rules.d.ts rules.js util.d.ts util.js validate applicability.d.ts applicability.js boolSchema.d.ts boolSchema.js dataType.d.ts dataType.js defaults.d.ts defaults.js index.d.ts index.js keyword.d.ts keyword.js subschema.d.ts subschema.js core.d.ts core.js jtd.d.ts jtd.js refs data.json json-schema-2019-09 index.d.ts index.js meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.d.ts index.js meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.d.ts jtd-schema.js runtime equal.d.ts equal.js parseJson.d.ts parseJson.js quote.d.ts quote.js re2.d.ts re2.js timestamp.d.ts timestamp.js ucs2length.d.ts ucs2length.js uri.d.ts uri.js validation_error.d.ts validation_error.js standalone index.d.ts index.js instance.d.ts instance.js types index.d.ts index.js json-schema.d.ts json-schema.js jtd-schema.d.ts jtd-schema.js vocabularies applicator additionalItems.d.ts additionalItems.js additionalProperties.d.ts additionalProperties.js allOf.d.ts allOf.js anyOf.d.ts anyOf.js contains.d.ts contains.js dependencies.d.ts dependencies.js dependentSchemas.d.ts dependentSchemas.js if.d.ts if.js index.d.ts index.js items.d.ts items.js items2020.d.ts items2020.js not.d.ts not.js oneOf.d.ts oneOf.js patternProperties.d.ts patternProperties.js prefixItems.d.ts prefixItems.js properties.d.ts properties.js propertyNames.d.ts propertyNames.js thenElse.d.ts thenElse.js code.d.ts code.js core id.d.ts id.js index.d.ts index.js ref.d.ts ref.js discriminator index.d.ts index.js types.d.ts types.js draft2020.d.ts draft2020.js draft7.d.ts draft7.js dynamic dynamicAnchor.d.ts dynamicAnchor.js dynamicRef.d.ts dynamicRef.js index.d.ts index.js recursiveAnchor.d.ts recursiveAnchor.js recursiveRef.d.ts recursiveRef.js errors.d.ts errors.js format format.d.ts format.js index.d.ts index.js jtd discriminator.d.ts discriminator.js elements.d.ts elements.js enum.d.ts enum.js error.d.ts error.js index.d.ts index.js metadata.d.ts metadata.js nullable.d.ts nullable.js optionalProperties.d.ts optionalProperties.js properties.d.ts properties.js ref.d.ts ref.js type.d.ts type.js union.d.ts union.js values.d.ts values.js metadata.d.ts metadata.js next.d.ts next.js unevaluated index.d.ts index.js unevaluatedItems.d.ts unevaluatedItems.js unevaluatedProperties.d.ts unevaluatedProperties.js validation const.d.ts const.js dependentRequired.d.ts dependentRequired.js enum.d.ts enum.js index.d.ts index.js limitContains.d.ts limitContains.js limitItems.d.ts limitItems.js limitLength.d.ts limitLength.js limitNumber.d.ts limitNumber.js limitProperties.d.ts limitProperties.js multipleOf.d.ts multipleOf.js pattern.d.ts pattern.js required.d.ts required.js uniqueItems.d.ts uniqueItems.js lib 2019.ts 2020.ts ajv.ts compile codegen code.ts index.ts scope.ts errors.ts index.ts jtd parse.ts serialize.ts types.ts names.ts ref_error.ts resolve.ts rules.ts util.ts validate applicability.ts boolSchema.ts dataType.ts defaults.ts index.ts keyword.ts subschema.ts core.ts jtd.ts refs data.json json-schema-2019-09 index.ts meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.ts meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.ts runtime equal.ts parseJson.ts quote.ts re2.ts timestamp.ts ucs2length.ts uri.ts validation_error.ts standalone index.ts instance.ts types index.ts json-schema.ts jtd-schema.ts vocabularies applicator additionalItems.ts additionalProperties.ts allOf.ts anyOf.ts contains.ts dependencies.ts dependentSchemas.ts if.ts index.ts items.ts items2020.ts not.ts oneOf.ts patternProperties.ts prefixItems.ts properties.ts propertyNames.ts thenElse.ts code.ts core id.ts index.ts ref.ts discriminator index.ts types.ts draft2020.ts draft7.ts dynamic dynamicAnchor.ts dynamicRef.ts index.ts recursiveAnchor.ts recursiveRef.ts errors.ts format format.ts index.ts jtd discriminator.ts elements.ts enum.ts error.ts index.ts metadata.ts nullable.ts optionalProperties.ts properties.ts ref.ts type.ts union.ts values.ts metadata.ts next.ts unevaluated index.ts unevaluatedItems.ts unevaluatedProperties.ts validation const.ts dependentRequired.ts enum.ts index.ts limitContains.ts limitItems.ts limitLength.ts limitNumber.ts limitProperties.ts multipleOf.ts pattern.ts required.ts uniqueItems.ts package.json json-schema-traverse .eslintrc.yml .github FUNDING.yml workflows build.yml publish.yml README.md index.d.ts index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json text-table .travis.yml example align.js center.js dotalign.js doubledot.js table.js index.js package.json test align.js ansi-colors.js center.js dotalign.js doubledot.js table.js tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json type-check README.md lib check.js index.js parse-type.js package.json type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts universal-url README.md browser.js index.js package.json uri-js README.md dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js ws.d.ts ws.js wss.d.ts wss.js uri.d.ts uri.js util.d.ts util.js package.json v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js word-wrap README.md index.d.ts index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json package-lock.json package.json package.json src App.js Components Home.js NewPoll.js PollingStation.js __mocks__ fileMock.js assets blockvotelogo.svg loadingcircles.svg logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html | features not yet implemented issues with the tests differences between PCRE and JS regex | | |
# once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) <a name="type-check" /> `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). npm install type-check ## Quick Examples ```js // Basic types: var typeCheck = require('type-check').typeCheck; typeCheck('Number', 1); // true typeCheck('Number', 'str'); // false typeCheck('Error', new Error); // true typeCheck('Undefined', undefined); // true // Comment typeCheck('count::Number', 1); // true // One type OR another type: typeCheck('Number | String', 2); // true typeCheck('Number | String', 'str'); // true // Wildcard, matches all types: typeCheck('*', 2) // true // Array, all elements of a single type: typeCheck('[Number]', [1, 2, 3]); // true typeCheck('[Number]', [1, 'str', 3]); // false // Tuples, or fixed length arrays with elements of different types: typeCheck('(String, Number)', ['str', 2]); // true typeCheck('(String, Number)', ['str']); // false typeCheck('(String, Number)', ['str', 2, 5]); // false // Object properties: typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true typeCheck('{x: Number, y: Boolean}', {x: 2}); // false typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true // A particular type AND object properties: typeCheck('RegExp{source: String, ...}', /re/i); // true typeCheck('RegExp{source: String, ...}', {source: 're'}); // false // Custom types: var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; typeCheck('Even', 2, opt); // true // Nested: var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true ``` Check out the [type syntax format](#syntax) and [guide](#guide). ## Usage `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. ```js // typeCheck(type, input, options); typeCheck('Number', 2); // true // parseType(type); var parsedType = parseType('Number'); // object // parsedTypeCheck(parsedType, input, options); parsedTypeCheck(parsedType, 2); // true ``` ### typeCheck(type, input, options) `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js typeCheck('Number', 2); // true ``` ### parseType(type) `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to parse ##### returns `Object` - an object in the parsed type format representing the parsed type ##### example ```js parseType('Number'); // [{type: 'Number'}] ``` ### parsedTypeCheck(parsedType, input, options) `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js parsedTypeCheck([{type: 'Number'}], 2); // true var parsedType = parseType('String'); parsedTypeCheck(parsedType, 'str'); // true ``` <a name="type-format" /> ## Type Format ### Syntax White space is ignored. The root node is a __Types__. * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` ### Guide `type-check` uses `Object.toString` to find out the basic type of a value. Specifically, ```js {}.toString.call(VALUE).slice(8, -1) {}.toString.call(true).slice(8, -1) // 'Boolean' ``` A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. The wildcard `*` matches all types. There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. ## Options Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. <a name="custom-types" /> ### Custom Types __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; } } } }; typeCheck('Even', 2, options); // true typeCheck('Even', 3, options); // false ``` `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. ## Technical About `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) # Optionator <a name="optionator" /> Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). [About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format) ## Why? The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. $ cmd --halp Invalid option '--halp' - perhaps you meant '--help'? $ cmd --count str Invalid value for option 'count' - expected type Int, received value: str. Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. ## About Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. MIT license. Version 0.9.1 npm install optionator For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. ## Usage `require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. ```js var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` ### parse(input, parseOptions) `parse` processes the `input` according to your settings, and returns an object with the results. ##### arguments * input - `[String] | Object | String` - the input you wish to parse * parseOptions - `{slice: Int}` - all options optional - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) ##### returns `Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. ##### example ```js parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} parse('--count 2 positional'); // {count: 2, _: ['positional']} parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} ``` ### parseArgv(input) `parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. ##### arguments * input - `[String]` - the input you wish to parse ##### returns See "returns" section in "parse" ##### example ```js parseArgv(process.argv); ``` ### generateHelp(helpOptions) `generateHelp` produces help text based on your settings. ##### arguments * helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` ##### returns `String` - the generated help text ##### example ```js generateHelp(); /* "Usage: cmd [options] positional -h, --help displays help -c, --count Int number of things Version 1.0.0 "*/ ``` ### generateHelpForOption(optionName) `generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. ##### arguments * optionName - `String` - the name of the option to display ##### returns `String` - the generated help text for the option ##### example ```js generateHelpForOption('count'); /* "-c, --count Int description: number of things example: cmd --count 2 "*/ ``` ## Settings Format When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: { prepend: String, append: String, options: [{heading: String} | { option: String, alias: [String] | String, type: String, enum: [String], default: String, restPositional: Boolean, required: Boolean, overrideRequired: Boolean, dependsOn: [String] | String, concatRepeatedArrays: Boolean | (Boolean, Object), mergeRepeatedObjects: Boolean, description: String, longDescription: String, example: [String] | String }], helpStyle: { aliasSeparator: String, typeSeparator: String, descriptionSeparator: String, initialIndent: Int, secondaryIndent: Int, maxPadFactor: Number }, mutuallyExclusive: [[String | [String]]], concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object mergeRepeatedObjects: Boolean, // deprecated, set in defaults object positionalAnywhere: Boolean, typeAliases: Object, defaults: Object } All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. ### Top Level Properties * `prepend` is an optional string to be placed before the options in the help text * `append` is an optional string to be placed after the options in the help text * `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified * `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text * `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present * `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` * `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` * `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property #### Heading Properties * `heading` a required string, the name of the heading #### Option Properties * `option` the required name of the option - use dash-case, without the leading dashes * `alias` is an optional string or array of strings which specify any aliases for the option * `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it * `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` * `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` * `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument * `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined * `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags * `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. * `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` * `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set * `description` is an optional string, which will be displayed next to the option in the help text * `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used * `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used #### Help Style Properties * `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' * `typeSeparator` is an optional string, separates the type from the names - default: ' ' * `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' * `initialIndent` is an optional int - the amount of indent for options - default: 2 * `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 * `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 ## Argument Format At the highest level there are two types of arguments: named, and positional. Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. Everything after an `--` is positional, even if it looks like a named argument. You may optionally use `=` to separate option names from values, for example: `--count=2`. If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. If duplicate named arguments are present, the last one will be taken. ## Technical About `optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # `asbuild` [![Stars](https://img.shields.io/github/stars/AssemblyScript/asbuild.svg?style=social&maxAge=3600&label=Star)](https://github.com/AssemblyScript/asbuild/stargazers) *A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.* ## 🚩 Table of Contents - [Installing](#-installing) - [Usage](#-usage) - [`asb init`](#asb-init---create-an-empty-project) - [`asb test`](#asb-test---run-as-pect-tests) - [`asb fmt`](#asb-fmt---format-as-files-using-eslint) - [`asb run`](#asb-run---run-a-wasi-binary) - [`asb build`](#asb-build---compile-the-project-using-asc) - [Background](#-background) ## 🔧 Installing Install it globally ``` npm install -g asbuild ``` Or, locally as dev dependencies ``` npm install --save-dev asbuild ``` ## 💡 Usage ``` Build tool for AssemblyScript projects. Usage: asb [command] [options] Commands: asb Alias of build command, to maintain back-ward compatibility [default] asb build Compile a local package and all of its dependencies [aliases: compile, make] asb init [baseDir] Create a new AS package in an given directory asb test Run as-pect tests asb fmt [paths..] This utility formats current module using eslint. [aliases: format, lint] Options: --version Show version number [boolean] --help Show help [boolean] ``` ### `asb init` - Create an empty project ``` asb init [baseDir] Create a new AS package in an given directory Positionals: baseDir Create a sample AS project in this directory [string] [default: "."] Options: --version Show version number [boolean] --help Show help [boolean] --yes Skip the interactive prompt [boolean] [default: false] ``` ### `asb test` - Run as-pect tests ``` asb test Run as-pect tests USAGE: asb test [options] -- [aspect_options] Options: --version Show version number [boolean] --help Show help [boolean] --verbose, --vv Print out arguments passed to as-pect [boolean] [default: false] ``` ### `asb fmt` - Format AS files using ESlint ``` asb fmt [paths..] This utility formats current module using eslint. Positionals: paths Paths to format [array] [default: ["."]] Initialisation: --init Generates recommended eslint config for AS Projects [boolean] Miscellaneous --lint, --dry-run Tries to fix problems without saving the changes to the file system [boolean] [default: false] Options: --version Show version number [boolean] --help Show help ``` ### `asb run` - Run a WASI binary ``` asb run Run a WASI binary USAGE: asb run [options] [binary path] -- [binary options] Positionals: binary path to Wasm binary [string] [required] Options: --version Show version number [boolean] --help Show help [boolean] --preopen, -p comma separated list of directories to open. [default: "."] ``` ### `asb build` - Compile the project using asc ``` asb build Compile a local package and all of its dependencies USAGE: asb build [entry_file] [options] -- [asc_options] Options: --version Show version number [boolean] --help Show help [boolean] --baseDir, -d Base directory of project. [string] [default: "."] --config, -c Path to asconfig file [string] [default: "./asconfig.json"] --wat Output wat file to outDir [boolean] [default: false] --outDir Directory to place built binaries. Default "./build/<target>/" [string] --target Target for compilation [string] [default: "release"] --verbose Print out arguments passed to asc [boolean] [default: false] Examples: asb build Build release of 'assembly/index.ts to build/release/packageName.wasm asb build --target release Build a release binary asb build -- --measure Pass argument to 'asc' ``` #### Defaults ##### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ##### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./tests/build_test) ## 📖 Background Asbuild started as wrapper around `asc` to provide an easier CLI interface and now has been extened to support other commands like `init`, `test` and `fmt` just like `cargo` to become a one stop build tool for AS Projects. ## 📜 License This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/). # AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation Node.js version 8 and up: `$ npm install cross-spawn` Node.js version 7 and under: `$ npm install cross-spawn@6` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # line-column [![Build Status](https://travis-ci.org/io-monad/line-column.svg?branch=master)](https://travis-ci.org/io-monad/line-column) [![Coverage Status](https://coveralls.io/repos/github/io-monad/line-column/badge.svg?branch=master)](https://coveralls.io/github/io-monad/line-column?branch=master) [![npm version](https://badge.fury.io/js/line-column.svg)](https://badge.fury.io/js/line-column) Node module to convert efficiently index to/from line-column in a string. ## Install npm install line-column ## Usage ### lineColumn(str, options = {}) Returns a `LineColumnFinder` instance for given string `str`. #### Options | Key | Description | Default | | ------- | ----------- | ------- | | `origin` | The origin value of line number and column number | `1` | ### lineColumn(str, index) This is just a shorthand for `lineColumn(str).fromIndex(index)`. ### LineColumnFinder#fromIndex(index) Find line and column from index in the string. Parameters: - `index` - `number` Index in the string. (0-origin) Returns: - `{ line: x, col: y }` Found line number and column number. - `null` if the given index is out of range. ### LineColumnFinder#toIndex(line, column) Find index from line and column in the string. Parameters: - `line` - `number` Line number in the string. - `column` - `number` Column number in the string. or - `{ line: x, col: y }` - `Object` line and column numbers in the string.<br>A key name `column` can be used instead of `col`. or - `[ line, col ]` - `Array` line and column numbers in the string. Returns: - `number` Found index in the string. - `-1` if the given line or column is out of range. ## Example ```js var lineColumn = require("line-column"); var testString = [ "ABCDEFG\n", // line:0, index:0 "HIJKLMNOPQRSTU\n", // line:1, index:8 "VWXYZ\n", // line:2, index:23 "日本語の文字\n", // line:3, index:29 "English words" // line:4, index:36 ].join(""); // length:49 lineColumn(testString).fromIndex(3) // { line: 1, col: 4 } lineColumn(testString).fromIndex(33) // { line: 4, col: 5 } lineColumn(testString).toIndex(1, 4) // 3 lineColumn(testString).toIndex(4, 5) // 33 // Shorthand of .fromIndex (compatible with find-line-column) lineColumn(testString, 33) // { line:4, col: 5 } // Object or Array is also acceptable lineColumn(testString).toIndex({ line: 4, col: 5 }) // 33 lineColumn(testString).toIndex({ line: 4, column: 5 }) // 33 lineColumn(testString).toIndex([4, 5]) // 33 // You can cache it for the same string. It is so efficient. (See benchmark) var finder = lineColumn(testString); finder.fromIndex(33) // { line: 4, column: 5 } finder.toIndex(4, 5) // 33 // For 0-origin line and column numbers var oneOrigin = lineColumn(testString, { origin: 0 }); oneOrigin.fromIndex(33) // { line: 3, column: 4 } oneOrigin.toIndex(3, 4) // 33 ``` ## Testing npm test ## Benchmark The popular package [find-line-column](https://www.npmjs.com/package/find-line-column) provides the same "index to line-column" feature. Here is some benchmarking on `line-column` vs `find-line-column`. You can run this benchmark by `npm run benchmark`. See [benchmark/](benchmark/) for the source code. ``` long text + line-column (not cached) x 72,989 ops/sec ±0.83% (89 runs sampled) long text + line-column (cached) x 13,074,242 ops/sec ±0.32% (89 runs sampled) long text + find-line-column x 33,887 ops/sec ±0.54% (84 runs sampled) short text + line-column (not cached) x 1,636,766 ops/sec ±0.77% (82 runs sampled) short text + line-column (cached) x 21,699,686 ops/sec ±1.04% (82 runs sampled) short text + find-line-column x 382,145 ops/sec ±1.04% (85 runs sampled) ``` As you might have noticed, even not cached version of `line-column` is 2x - 4x faster than `find-line-column`, and cached version of `line-column` is remarkable 50x - 380x faster. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT (See LICENSE) # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers # node-supports-preserve-symlinks-flag <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] Determine if the current node version supports the `--preserve-symlinks` flag. ## Example ```js var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); var assert = require('assert'); assert.equal(supportsPreserveSymlinks, null); // in a browser assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag [npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag [dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg [dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies [npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg [downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag [codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag [actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` # lodash.truncate v4.4.2 The [lodash](https://lodash.com/) method `_.truncate` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.truncate ``` In Node.js: ```js var truncate = require('lodash.truncate'); ``` See the [documentation](https://lodash.com/docs#truncate) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.truncate) for more details. # prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>. See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. You can install via npm `npm install prelude-ls` ### Development `make test` to test `make build` to build `lib` from `src` `make build-browser` to build browser versions assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) Like `chown -R`. Takes the same arguments as `fs.chown()` blockvote ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `blockvote.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `blockvote.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account blockvote.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'blockvote.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # flatted [![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) ![snow flake](./flatted.jpg) <sup>**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**</sup> ## Announcement 📣 There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general. The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax. However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍 - - - A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). Now available also for **[PHP](./php/flatted.php)**. ```js npm i flatted ``` Usable via [CDN](https://unpkg.com/flatted) or as regular module. ```js // ESM import {parse, stringify, toJSON, fromJSON} from 'flatted'; // CJS const {parse, stringify, toJSON, fromJSON} = require('flatted'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}] ``` ## toJSON and fromJSON If you'd like to implicitly survive JSON serialization, these two helpers helps: ```js import {toJSON, fromJSON} from 'flatted'; class RecursiveMap extends Map { static fromJSON(any) { return new this(fromJSON(any)); } toJSON() { return toJSON([...this.entries()]); } } const recursive = new RecursiveMap; const same = {}; same.same = same; recursive.set('same', same); const asString = JSON.stringify(recursive); const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); asMap.get('same') === asMap.get('same').same; // true ``` ## Flatted VS JSON As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. ### New in V1: Exact same JSON API * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. ### Compatibility All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. ### How does it work ? While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` Once parsed, all indexes will be replaced through the flattened collection. <sup><sub>`*` represented as string to avoid conflicts with numbers</sub></sup> ```js // logic example var a = [{one: 1}, {two: '2'}]; a[0].a = a; // a is the main object, will be at index '0' // {one: 1} is the second object, index '1' // {two: '2'} the third, in '2', and it has a string // which will be found at index '3' Flatted.stringify(a); // [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] // a[one,two] {one: 1, a} {two: '2'} '2' ``` # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.mjs': '/absolute/path/to/interpret/mjs-stub.js', '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', 'sucrase/register/ts', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', 'sucrase/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). ## Test Strategy - tests are copied from the [polyfill implementation](https://github.com/tc39/proposal-temporal/tree/main/polyfill/test) - tests should be removed if they relate to features that do not make sense for TS/AS, i.e. tests that validate the shape of an object do not make sense in a language with compile-time type checking - tests that fail because a feature has not been implemented yet should be left as failures. # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. [![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) [![Build Status](https://travis-ci.org/eslint/espree.svg?branch=master)](https://travis-ci.org/eslint/espree) [![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) # Espree Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. ## Usage Install: ``` npm i espree ``` And in your Node.js code: ```javascript const espree = require("espree"); const ast = espree.parse(code); ``` ## API ### `parse()` `parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). ```javascript const espree = require("espree"); const ast = espree.parse(code, options); ``` **Example :** ```js const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); console.log(ast); ``` <details><summary>Output</summary> <p> ``` Node { type: 'Program', start: 0, end: 15, body: [ Node { type: 'VariableDeclaration', start: 0, end: 15, declarations: [Array], kind: 'let' } ], sourceType: 'script' } ``` </p> </details> ### `tokenize()` `tokenize` returns the tokens of a given code. It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array **Example :** ```js const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); console.log(tokens); ``` <details><summary>Output</summary> <p> ``` Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, Token { type: 'String', value: '"bar"', start: 10, end: 15 } ``` </p> </details> ### `version` Returns the current `espree` version ### `VisitorKeys` Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) ### `latestEcmaVersion` Returns the latest ECMAScript supported by `espree` ### `supportedEcmaVersions` Returns an array of all supported ECMAScript versions ## Options ```js const options = { // attach range information to each node range: false, // attach line/column location information to each node loc: false, // create a top-level comments array containing all comments comment: false, // create a top-level tokens array containing all tokens tokens: false, // Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming. ecmaVersion: 5, // specify which type of script you're parsing ("script" or "module") sourceType: "script", // specify additional language features ecmaFeatures: { // enable JSX parsing jsx: false, // enable return in global scope globalReturn: false, // enable implied strict mode (if ecmaVersion >= 5) impliedStrict: false } } ``` ## Esprima Compatibility Going Forward The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. Espree may also deviate from Esprima in the interface it exposes. ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). Espree is licensed under a permissive BSD 2-clause license. ## Security Policy We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting * `npm run browserify` - creates a version of Espree that is usable in a browser ## Differences from Espree 2.x * The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. * Trailing whitespace no longer is counted as part of a node. * `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. * The `esparse` and `esvalidate` binary scripts have been removed. * There is no `tolerant` option. We will investigate adding this back in the future. ## Known Incompatibilities In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. ### Esprima 1.2.2 * Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. * Espree does not parse `let` and `const` declarations by default. * Error messages returned for parsing errors are different. * There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. ### Esprima 2.x * Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. ## Frequently Asked Questions ### Why another parser [ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. ### Have you tried working with Esprima? Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. ### Why don't you just use Acorn? Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. ### What ECMAScript features do you support? Espree supports all ECMAScript 2020 features and partially supports ECMAScript 2021 features. Because ECMAScript 2021 is still under development, we are implementing features as they are finalized. Currently, Espree supports: * [Logical Assignment Operators](https://github.com/tc39/proposal-logical-assignment) * [Numeric Separators](https://github.com/tc39/proposal-numeric-separator) See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. ### How do you determine which experimental features to support? In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. [![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) [![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) [![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) <br /> [![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) [![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) [![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) # ESLint [Website](https://eslint.org) | [Configuring](https://eslint.org/docs/user-guide/configuring) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | [Code of Conduct](https://eslint.org/conduct) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://eslint.org/chat) ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. ## Table of Contents 1. [Installation and Usage](#installation-and-usage) 2. [Configuration](#configuration) 3. [Code of Conduct](#code-of-conduct) 4. [Filing Issues](#filing-issues) 5. [Frequently Asked Questions](#faq) 6. [Releases](#releases) 7. [Security Policy](#security-policy) 8. [Semantic Versioning Policy](#semantic-versioning-policy) 9. [Stylistic Rule Updates](#stylistic-rule-updates) 10. [License](#license) 11. [Team](#team) 12. [Sponsors](#sponsors) 13. [Technology Sponsors](#technology-sponsors) ## <a name="installation-and-usage"></a>Installation and Usage Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install ESLint using npm: ``` $ npm install eslint --save-dev ``` You should then set up a configuration file: ``` $ ./node_modules/.bin/eslint --init ``` After that, you can run ESLint on any file or directory like this: ``` $ ./node_modules/.bin/eslint yourfile.js ``` ## <a name="configuration"></a>Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: ```json { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). ## <a name="code-of-conduct"></a>Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://eslint.org/conduct). ## <a name="filing-issues"></a>Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: * [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) * [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) ## <a name="faq"></a>Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. ### Why can't ESLint find my plugins? * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. * Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. ### What ECMAScript versions does ESLint support? ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). ### What about experimental features? ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). ### Why doesn't ESLint lock dependency versions? Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. ## <a name="releases"></a>Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. ## <a name="security-policy"></a>Security Policy ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## <a name="semantic-versioning-policy"></a>Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: * Patch release (intended to not break your lint build) * A bug fix in a rule that results in ESLint reporting fewer linting errors. * A bug fix to the CLI or core (including formatters). * Improvements to documentation. * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). * Minor release (might break your lint build) * A bug fix in a rule that results in ESLint reporting more linting errors. * A new rule is created. * A new option to an existing rule that does not result in ESLint reporting more linting errors by default. * A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. * An existing rule is deprecated. * A new CLI capability is created. * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). * A new formatter is created. * `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). * Major release (likely to break your lint build) * `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). * A new option to an existing rule that results in ESLint reporting more linting errors by default. * An existing formatter is removed. * Part of the public API is removed or changed in an incompatible way. The public API includes: * Rule schemas * Configuration schema * Command-line options * Node.js API * Rule, formatter, parser, plugin APIs According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. ## <a name="stylistic-rule-updates"></a>Stylistic Rule Updates Stylistic rules are frozen according to [our policy](https://eslint.org/blog/2020/05/changes-to-rules-policies) on how we evaluate new rules and rule changes. This means: * **Bug fixes**: We will still fix bugs in stylistic rules. * **New ECMAScript features**: We will also make sure stylistic rules are compatible with new ECMAScript features. * **New options**: We will **not** add any new options to stylistic rules unless an option is the only way to fix a bug or support a newly-added ECMAScript feature. ## <a name="license"></a>License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) ## <a name="team"></a>Team These folks keep the project moving and are resources for help. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--teamstart--> ### Technical Steering Committee (TSC) The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/nzakas"> <img src="https://github.com/nzakas.png?s=75" width="75" height="75"><br /> Nicholas C. Zakas </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/btmills"> <img src="https://github.com/btmills.png?s=75" width="75" height="75"><br /> Brandon Mills </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/mdjermanovic"> <img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br /> Milos Djermanovic </a> </td></tr></tbody></table> ### Reviewers The people who review and implement new features. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/mysticatea"> <img src="https://github.com/mysticatea.png?s=75" width="75" height="75"><br /> Toru Nagashima </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/aladdin-add"> <img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br /> 薛定谔的猫 </a> </td></tr></tbody></table> ### Committers The people who review and fix bugs and help triage issues. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/brettz9"> <img src="https://github.com/brettz9.png?s=75" width="75" height="75"><br /> Brett Zamir </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/bmish"> <img src="https://github.com/bmish.png?s=75" width="75" height="75"><br /> Bryan Mishkin </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/g-plane"> <img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br /> Pig Fang </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/anikethsaha"> <img src="https://github.com/anikethsaha.png?s=75" width="75" height="75"><br /> Anix </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/yeonjuan"> <img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br /> YeonJuan </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/snitin315"> <img src="https://github.com/snitin315.png?s=75" width="75" height="75"><br /> Nitin Kumar </a> </td></tr></tbody></table> <!--teamend--> ## <a name="sponsors"></a>Sponsors The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--sponsorsstart--> <h3>Platinum Sponsors</h3> <p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3> <p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p> <!--sponsorsend--> ## <a name="technology-sponsors"></a>Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) * Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) * Password management is sponsored by [1Password](https://www.1password.com) ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ShellJS - Unix shell commands for Node.js [![Travis](https://img.shields.io/travis/shelljs/shelljs/master.svg?style=flat-square&label=unix)](https://travis-ci.org/shelljs/shelljs) [![AppVeyor](https://img.shields.io/appveyor/ci/shelljs/shelljs/master.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/shelljs/shelljs/branch/master) [![Codecov](https://img.shields.io/codecov/c/github/shelljs/shelljs/master.svg?style=flat-square&label=coverage)](https://codecov.io/gh/shelljs/shelljs) [![npm version](https://img.shields.io/npm/v/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) [![npm downloads](https://img.shields.io/npm/dm/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! ShellJS is proudly tested on every node release since `v4`! The project is [unit-tested](http://travis-ci.org/shelljs/shelljs) and battle-tested in projects like: + [Firebug](http://getfirebug.com/) - Firefox's infamous debugger + [JSHint](http://jshint.com) & [ESLint](http://eslint.org/) - popular JavaScript linters + [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers + [Yeoman](http://yeoman.io/) - Web application stack and development tool + [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + And [many more](https://npmjs.org/browse/depended/shelljs). If you have feedback, suggestions, or need help, feel free to post in our [issue tracker](https://github.com/shelljs/shelljs/issues). Think ShellJS is cool? Check out some related projects in our [Wiki page](https://github.com/shelljs/shelljs/wiki)! Upgrading from an older version? Check out our [breaking changes](https://github.com/shelljs/shelljs/wiki/Breaking-Changes) page to see what changes to watch out for while upgrading. ## Command line use If you just want cross platform UNIX commands, checkout our new project [shelljs/shx](https://github.com/shelljs/shx), a utility to expose `shelljs` to the command line. For example: ``` $ shx mkdir -p foo $ shx touch foo/bar.txt $ shx rm -rf foo ``` ## Plugin API ShellJS now supports third-party plugins! You can learn more about using plugins and writing your own ShellJS commands in [the wiki](https://github.com/shelljs/shelljs/wiki/Using-ShellJS-Plugins). ## A quick note about the docs For documentation on all the latest features, check out our [README](https://github.com/shelljs/shelljs). To read docs that are consistent with the latest release, check out [the npm page](https://www.npmjs.com/package/shelljs) or [shelljs.org](http://documentup.com/shelljs/shelljs). ## Installing Via npm: ```bash $ npm install [-g] shelljs ``` ## Examples ```javascript var shell = require('shelljs'); if (!shell.which('git')) { shell.echo('Sorry, this script requires git'); shell.exit(1); } // Copy files to release dir shell.rm('-rf', 'out/Release'); shell.cp('-R', 'stuff/', 'out/Release'); // Replace macros in each .js file shell.cd('lib'); shell.ls('*.js').forEach(function (file) { shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file); shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); shell.cd('..'); // Run external tool synchronously if (shell.exec('git commit -am "Auto-commit"').code !== 0) { shell.echo('Error: Git commit failed'); shell.exit(1); } ``` ## Exclude options If you need to pass a parameter that looks like an option, you can do so like: ```js shell.grep('--', '-v', 'path/to/file'); // Search for "-v", no grep options shell.cp('-R', '-dir', 'outdir'); // If already using an option, you're done ``` ## Global vs. Local We no longer recommend using a global-import for ShellJS (i.e. `require('shelljs/global')`). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution. Instead, we recommend a local import (standard for npm packages): ```javascript var shell = require('shelljs'); shell.echo('hello world'); ``` <!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED --> ## Command reference All commands run synchronously, unless otherwise stated. All commands accept standard bash globbing characters (`*`, `?`, etc.), compatible with the [node `glob` module](https://github.com/isaacs/node-glob). For less-commonly used commands and features, please check out our [wiki page](https://github.com/shelljs/shelljs/wiki). ### cat([options,] file [, file ...]) ### cat([options,] file_array) Available options: + `-n`: number all output lines Examples: ```javascript var str = cat('file*.txt'); var str = cat('file1', 'file2'); var str = cat(['file1', 'file2']); // same as above ``` Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). ### cd([dir]) Changes to directory `dir` for the duration of the script. Changes to home directory if no argument is supplied. ### chmod([options,] octal_mode || octal_string, file) ### chmod([options,] symbolic_mode, file) Available options: + `-v`: output a diagnostic for every file processed + `-c`: like verbose, but report only when a change is made + `-R`: change files and directories recursively Examples: ```javascript chmod(755, '/Users/brandon'); chmod('755', '/Users/brandon'); // same as above chmod('u+x', '/Users/brandon'); chmod('-R', 'a-w', '/Users/brandon'); ``` Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + In symbolic modes, `a-r` and `-r` are identical. No consideration is given to the `umask`. + There is no "quiet" option, since default behavior is to run silent. ### cp([options,] source [, source ...], dest) ### cp([options,] source_array, dest) Available options: + `-f`: force (default behavior) + `-n`: no-clobber + `-u`: only copy if `source` is newer than `dest` + `-r`, `-R`: recursive + `-L`: follow symlinks + `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` Copies files. ### pushd([options,] [dir | '-N' | '+N']) Available options: + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. Examples: ```javascript // process.cwd() === '/usr' pushd('/etc'); // Returns /etc /usr pushd('+1'); // Returns /usr /etc ``` Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. ### popd([options,] ['-N' | '+N']) Available options: + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. Examples: ```javascript echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(); // '/usr' echo(process.cwd()); // '/usr' ``` When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. ### dirs([options | '+N' | '-N']) Available options: + `-c`: Clears the directory stack by deleting all of the elements. + `-q`: Supresses output to the console. Arguments: + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. See also: `pushd`, `popd` ### echo([options,] string [, string ...]) Available options: + `-e`: interpret backslash escapes (default) + `-n`: remove trailing newline from output Examples: ```javascript echo('hello world'); var str = echo('hello world'); echo('-n', 'no newline at end'); ``` Prints `string` to stdout, and returns string with additional utility methods like `.to()`. ### exec(command [, options] [, callback]) Available options: + `async`: Asynchronous execution. If a callback is provided, it will be set to `true`, regardless of the passed value (default: `false`). + `silent`: Do not echo program output to console (default: `false`). + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and what is written to stdout and stderr when not in silent mode (default: `'utf8'`). + and any option available to Node.js's [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) Examples: ```javascript var version = exec('node --version', {silent:true}).stdout; var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... do something with data ... */ }); exec('some_long_running_process', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); }); ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process object, and the `callback` receives the arguments `(code, stdout, stderr)`. Not seeing the behavior you want? `exec()` runs everything through `sh` by default (or `cmd.exe` on Windows), which differs from `bash`. If you need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. ### find(path [, path ...]) ### find(path_array) Examples: ```javascript find('src', 'lib'); find(['src', 'lib']); // same as above find('.').filter(function(file) { return file.match(/\.js$/); }); ``` Returns array of all files (however deep) in the given paths. The main difference from `ls('-R', path)` is that the resulting file names include the base directories (e.g., `lib/resources/file1` instead of just `file1`). ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Invert `regex_filter` (only print non-matching lines). + `-l`: Print only filenames of matching files. + `-i`: Ignore case. Examples: ```javascript grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the file that match the given `regex_filter`. ### head([{'-n': \<num\>},] file [, file ...]) ### head([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the first `<num>` lines of the files Examples: ```javascript var str = head({'-n': 1}, 'file*.txt'); var str = head('file1', 'file2'); var str = head(['file1', 'file2']); // same as above ``` Read the start of a file. ### ln([options,] source, dest) Available options: + `-s`: symlink + `-f`: force Examples: ```javascript ln('file', 'newlink'); ln('-sf', 'file', 'existing'); ``` Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. ### ls([options,] [path, ...]) ### ls([options,] path_array) Available options: + `-R`: recursive + `-A`: all files (include files beginning with `.`, except for `.` and `..`) + `-L`: follow symlinks + `-d`: list directories themselves, not their contents + `-l`: list objects representing each file, each with fields containing `ls -l` output fields. See [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) for more info Examples: ```javascript ls('projs/*.js'); ls('-R', '/users/me', '/tmp'); ls('-R', ['/users/me', '/tmp']); // same as above ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} ``` Returns array of files in the given `path`, or files in the current directory if no `path` is provided. ### mkdir([options,] dir [, dir ...]) ### mkdir([options,] dir_array) Available options: + `-p`: full path (and create intermediate directories, if necessary) Examples: ```javascript mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above ``` Creates directories. ### mv([options ,] source [, source ...], dest') ### mv([options ,] source_array, dest') Available options: + `-f`: force (default behavior) + `-n`: no-clobber Examples: ```javascript mv('-n', 'file', 'dir/'); mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` Moves `source` file(s) to `dest`. ### pwd() Returns the current directory. ### rm([options,] file [, file ...]) ### rm([options,] file_array) Available options: + `-f`: force + `-r, -R`: recursive Examples: ```javascript rm('-rf', '/tmp/*'); rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` Removes files. ### sed([options,] search_regex, replacement, file [, file ...]) ### sed([options,] search_regex, replacement, file_array) Available options: + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ Examples: ```javascript sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); ``` Reads an input string from `file`s, and performs a JavaScript `replace()` on the input using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. Note: Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified using the `$n` syntax: ```javascript sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); ``` ### set(options) Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) + `+/-f`: disable filename expansion (globbing) Examples: ```javascript set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" ``` Sets global configuration variables. ### sort([options,] file [, file ...]) ### sort([options,] file_array) Available options: + `-r`: Reverse the results + `-n`: Compare according to numerical value Examples: ```javascript sort('foo.txt', 'bar.txt'); sort('-r', 'foo.txt'); ``` Return the contents of the `file`s, sorted line-by-line. Sorting multiple files mixes their content (just as unix `sort` does). ### tail([{'-n': \<num\>},] file [, file ...]) ### tail([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the last `<num>` lines of `file`s Examples: ```javascript var str = tail({'-n': 1}, 'file*.txt'); var str = tail('file1', 'file2'); var str = tail(['file1', 'file2']); // same as above ``` Read the end of a `file`. ### tempdir() Examples: ```javascript var tmp = tempdir(); // "/tmp" for most *nix platforms ``` Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). ### test(expression) Available expression primaries: + `'-b', 'path'`: true if path is a block device + `'-c', 'path'`: true if path is a character device + `'-d', 'path'`: true if path is a directory + `'-e', 'path'`: true if path exists + `'-f', 'path'`: true if path is a regular file + `'-L', 'path'`: true if path is a symbolic link + `'-p', 'path'`: true if path is a pipe (FIFO) + `'-S', 'path'`: true if path is a socket Examples: ```javascript if (test('-d', path)) { /* do something with dir */ }; if (!test('-f', path)) continue; // skip if it's a regular file ``` Evaluates `expression` using the available primaries and returns corresponding value. ### ShellString.prototype.to(file) Examples: ```javascript cat('input.txt').to('output.txt'); ``` Analogous to the redirection operator `>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix redirections, `to()` will overwrite any existing file!_ ### ShellString.prototype.toEnd(file) Examples: ```javascript cat('input.txt').toEnd('output.txt'); ``` Analogous to the redirect-and-append operator `>>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). ### touch([options,] file [, file ...]) ### touch([options,] file_array) Available options: + `-a`: Change only the access time + `-c`: Do not create any files + `-m`: Change only the modification time + `-d DATE`: Parse `DATE` and use it instead of current time + `-r FILE`: Use `FILE`'s times instead of current time Examples: ```javascript touch('source.js'); touch('-c', '/path/to/some/dir/source.js'); touch({ '-r': FILE }, '/path/to/some/dir/source.js'); ``` Update the access and modification times of each `FILE` to the current time. A `FILE` argument that does not exist is created empty, unless `-c` is supplied. This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). ### uniq([options,] [input, [output]]) Available options: + `-i`: Ignore case while comparing + `-c`: Prefix lines by the number of occurrences + `-d`: Only print duplicate lines, one for each group of identical lines Examples: ```javascript uniq('foo.txt'); uniq('-i', 'foo.txt'); uniq('-cd', 'foo.txt', 'bar.txt'); ``` Filter adjacent matching lines from `input`. ### which(command) Examples: ```javascript var nodeExec = which('node'); ``` Searches for `command` in the system's `PATH`. On Windows, this uses the `PATHEXT` variable to append the extension if it's not already executable. Returns string containing the absolute path to `command`. ### exit(code) Exits the current process with the given exit `code`. ### error() Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise. **Note**: do not rely on the return value to be an error message. If you need the last error message, use the `.stderr` attribute from the last command's return value instead. ### ShellString(str) Examples: ```javascript var foo = ShellString('hello world'); ``` Turns a regular string into a string-like object similar to what each command returns. This has special methods, like `.to()` and `.toEnd()`. ### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to `process.env`. ### Pipes Examples: ```javascript grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); echo('files with o\'s in the name:\n' + ls().grep('o')); cat('test.js').exec('node'); // pipe to exec() call ``` Commands can send their output to another command in a pipe-like fashion. `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand side of a pipe. Pipes can be chained. ## Configuration ### config.silent Example: ```javascript var sh = require('shelljs'); var silentState = sh.config.silent; // save old silent state sh.config.silent = true; /* ... */ sh.config.silent = silentState; // restore old silent state ``` Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` If `true`, the script will throw a Javascript error when any shell.js command encounters an error. Default is `false`. This is analogous to Bash's `set -e`. ### config.verbose Example: ```javascript config.verbose = true; // or set('-v'); cd('dir/'); rm('-rf', 'foo.txt', 'bar.txt'); exec('echo hello'); ``` Will print each command as follows: ``` cd dir/ rm -rf foo.txt bar.txt exec echo hello ``` ### config.globOptions Example: ```javascript config.globOptions = {nodir: true}; ``` Use this value for calls to `glob.sync()` instead of the default options. ### config.reset() Example: ```javascript var shell = require('shelljs'); // Make changes to shell.config, and do stuff... /* ... */ shell.config.reset(); // reset to original state // Do more stuff, but with original settings /* ... */ ``` Reset `shell.config` to the defaults: ```javascript { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, } ``` ## Team | [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Brandon Freitag](https://avatars1.githubusercontent.com/u/5988055?v=3&s=130)](http://github.com/freitagbr) | |:---:|:---:| | [Nate Fischer](https://github.com/nfischer) | [Brandon Freitag](http://github.com/freitagbr) | [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png [1]: https://travis-ci.org/litejs/natural-compare-lite [2]: https://coveralls.io/r/litejs/natural-compare-lite [npm package]: https://npmjs.org/package/natural-compare-lite [GitHub repo]: https://github.com/litejs/natural-compare-lite @version 1.4.0 @date 2015-10-26 @stability 3 - Stable Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2] =============== Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering". ```text Standard sorting: Natural order sorting: img1.png img1.png img10.png img2.png img12.png img10.png img2.png img12.png ``` String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function. ### Installation - In browser ```html <script src=min.natural-compare.js></script> ``` - In node.js: `npm install natural-compare-lite` ```javascript require("natural-compare-lite") ``` ### Usage ```javascript // Simple case sensitive example var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; a.sort(String.naturalCompare); // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] // Use wrapper function for case insensitivity a.sort(function(a, b){ return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); }) // In most cases we want to sort an array of objects var a = [ {"street":"350 5th Ave", "room":"A-1021"} , {"street":"350 5th Ave", "room":"A-21046-b"} ]; // sort by street, then by room a.sort(function(a, b){ return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); }) // When text transformation is needed (eg toLowerCase()), // it is best for performance to keep // transformed key in that object. // There are no need to do text transformation // on each comparision when sorting. var a = [ {"make":"Audi", "model":"A6"} , {"make":"Kia", "model":"Rio"} ]; // sort by make, then by model a.map(function(car){ car.sort_key = (car.make + " " + car.model).toLowerCase(); }) a.sort(function(a, b){ return String.naturalCompare(a.sort_key, b.sort_key); }) ``` - Works well with dates in ISO format eg "Rev 2012-07-26.doc". ### Custom alphabet It is possible to configure a custom alphabet to achieve a desired order. ```javascript // Estonian alphabet String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" ["t", "z", "x", "õ"].sort(String.naturalCompare) // ["z", "t", "õ", "x"] // Russian alphabet String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" ["Ё", "А", "Б"].sort(String.naturalCompare) // ["А", "Б", "Ё"] ``` External links -------------- - [GitHub repo][https://github.com/litejs/natural-compare-lite] - [jsperf test](http://jsperf.com/natural-sort-2/12) Licence ------- Copyright (c) 2012-2015 Lauri Rooden &lt;[email protected]&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) [![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) This package is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy to use and powerful. It was first released in 2010 and is tested against big data sets by a large community. ## Documentation * [Project homepage](http://csv.js.org/stringify/) * [API](http://csv.js.org/stringify/api/) * [Options](http://csv.js.org/stringify/options/) * [Examples](http://csv.js.org/stringify/examples/) ## Main features * Follow the Node.js streaming API * Simplicity with the optional callback API * Support for custom formatters, delimiters, quotes, escape characters and header * Support big datasets * Complete test coverage and samples for inspiration * Only 1 external dependency * to be used conjointly with `csv-generate`, `csv-parse` and `stream-transform` * MIT License ## Usage The module is built on the Node.js Stream API. For the sake of simplicity, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: ```javascript const stringify = require('csv-stringify') const assert = require('assert') // import stringify from 'csv-stringify' // import assert from 'assert/strict' const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] stringify(input, function(err, output) { const expected = '1,2,3,4\na,b,c,d\n' assert.strictEqual(output, expected, `output.should.eql ${expected}`) console.log("Passed.", output) }) ``` ## Development Tests are executed with mocha. To install it, run `npm install` followed by `npm test`. It will install mocha and its dependencies in your project "node_modules" directory and run the test suite. The tests run against the CoffeeScript source files. To generate the JavaScript files, run `npm run build`. The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node-csv-stringify). See the [Travis definition file](https://github.com/adaltas/node-csv-stringify/blob/master/.travis.yml) to view the tested Node.js version. ## Contributors * David Worms: <https://github.com/wdavidw> [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform [examples]: http://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # is-core-module <sup>[![Version Badge][2]][1]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module [codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module [actions-url]: https://github.com/inspect-js/is-core-module/actions # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 (2020, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 10. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. <h1 align="center">Enquirer</h1> <p align="center"> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version"> </a> <a href="https://travis-ci.org/enquirer/enquirer"> <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis"> </a> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br> <sub>>_ Prompts should be more like conversations than inquisitions▌</sub> </p> <br> <p align="center"> <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br> <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br> <a href="#built-in-prompts"><strong>See more prompt examples</strong></a> </p> <br> <br> Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases. * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_) * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb). * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement. * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos. * **Intuitive** - Keypress combos are available to simplify usage. * **Flexible** - All prompts can be used standalone or chained together. * **Stylish** - Easily override semantic styles and symbols for any part of the prompt. * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts). * **Pluggable** - Add advanced features to Enquirer using plugins. * **Validation** - Optionally validate user input with any prompt. * **Well tested** - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values. * **Examples** - There are numerous [examples](examples) available to help you get started. If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks! <br> <p align="center"> <b>>_ Ready to start making prompts your users will love? ▌</b><br> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750"> </p> <br> <br> ## ❯ Getting started Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts. * [Install](#-install) * [Usage](#-usage) * [Enquirer](#-enquirer) * [Prompts](#-prompts) - [Built-in Prompts](#-prompts) - [Custom Prompts](#-custom-prompts) * [Key Bindings](#-key-bindings) * [Options](#-options) * [Release History](#-release-history) * [Performance](#-performance) * [About](#-about) <br> ## ❯ Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install enquirer --save ``` Install with [yarn](https://yarnpkg.com/en/): ```sh $ yarn add enquirer ``` <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750"> </p> _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_ <br> ## ❯ Usage ### Single prompt The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method. ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); // { username: 'jonschlinkert' } ``` _(Examples with `await` need to be run inside an `async` function)_ ### Multiple prompts Pass an array of ["question" objects](#prompt-options) to run a series of prompts. ```js const response = await prompt([ { type: 'input', name: 'name', message: 'What is your name?' }, { type: 'input', name: 'username', message: 'What is your username?' } ]); console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' } ``` ### Different ways to run enquirer #### 1. By importing the specific `built-in prompt` ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Did you like enquirer?' }); prompt.run() .then(answer => console.log('Answer:', answer)); ``` #### 2. By passing the options to `prompt` ```js const { prompt } = require('enquirer'); prompt({ type: 'confirm', name: 'question', message: 'Did you like enquirer?' }) .then(answer => console.log('Answer:', answer)); ``` **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings) <br> ## ❯ Enquirer **Enquirer is a prompt runner** Add Enquirer to your JavaScript project with following line of code. ```js const Enquirer = require('enquirer'); ``` The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts. ```js const { prompt } = require('enquirer'); const question = [ { type: 'input', name: 'username', message: 'What is your username?' }, { type: 'password', name: 'password', message: 'What is your password?' } ]; let answers = await prompt(question); console.log(answers); ``` **Prompts control how values are rendered and returned** Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application. **How can I customize prompts?** Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt. All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`. Use this approach if you need to modify a prompt instance, or listen for events on the prompt. **Example** ```js const { Input } = require('enquirer'); const prompt = new Input({ name: 'username', message: 'What is your username?' }); prompt.run() .then(answer => console.log('Username:', answer)) .catch(console.error); ``` ### [Enquirer](index.js#L20) Create an instance of `Enquirer`. **Params** * `options` **{Object}**: (optional) Options to use with all prompts. * `answers` **{Object}**: (optional) Answers object to initialize with. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` ### [register()](index.js#L42) Register a custom prompt type. **Params** * `type` **{String}** * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class. * `returns` **{Object}**: Returns the Enquirer instance **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); enquirer.register('customType', require('./custom-prompt')); ``` ### [prompt()](index.js#L78) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const response = await enquirer.prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` ### [use()](index.js#L160) Use an enquirer plugin. **Params** * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer. * `returns` **{Object}**: Returns the Enquirer instance. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const plugin = enquirer => { // do stuff to enquire instance }; enquirer.use(plugin); ``` ### [Enquirer#prompt](index.js#L210) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` <br> ## ❯ Prompts This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept. **Getting started with Enquirer's prompts** * [Prompt](#prompt) - The base `Prompt` class used by other prompts - [Prompt Options](#prompt-options) * [Built-in prompts](#built-in-prompts) * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts * [Custom prompts](#%E2%9D%AF-custom-prompts) - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use. ### Prompt The base `Prompt` class is used to create all other prompts. ```js const { Prompt } = require('enquirer'); class MyCustomPrompt extends Prompt {} ``` See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works. #### Prompt Options Each prompt takes an options object (aka "question" object), that implements the following interface: ```js { // required type: string | function, name: string | function, message: string | function | async function, // optional skip: boolean | function | async function, initial: string | function | async function, format: function | async function, result: function | async function, validate: function | async function, } ``` Each property of the options object is described below: | **Property** | **Required?** | **Type** | **Description** | | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. | | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. | | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. | | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. | | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. | | `format` | no | `function` | Function to format user input in the terminal. | | `result` | no | `function` | Function to format the final submitted value before it's returned. | | `validate` | no | `function` | Function to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message. | **Example usage** ```js const { prompt } = require('enquirer'); const question = { type: 'input', name: 'username', message: 'What is your username?' }; prompt(question) .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` <br> ### Built-in prompts * [AutoComplete Prompt](#autocomplete-prompt) * [BasicAuth Prompt](#basicauth-prompt) * [Confirm Prompt](#confirm-prompt) * [Form Prompt](#form-prompt) * [Input Prompt](#input-prompt) * [Invisible Prompt](#invisible-prompt) * [List Prompt](#list-prompt) * [MultiSelect Prompt](#multiselect-prompt) * [Numeral Prompt](#numeral-prompt) * [Password Prompt](#password-prompt) * [Quiz Prompt](#quiz-prompt) * [Survey Prompt](#survey-prompt) * [Scale Prompt](#scale-prompt) * [Select Prompt](#select-prompt) * [Sort Prompt](#sort-prompt) * [Snippet Prompt](#snippet-prompt) * [Toggle Prompt](#toggle-prompt) ### AutoComplete Prompt Prompt that auto-completes as the user types, and returns the selected value as a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750"> </p> **Example Usage** ```js const { AutoComplete } = require('enquirer'); const prompt = new AutoComplete({ name: 'flavor', message: 'Pick your favorite flavor', limit: 10, initial: 2, choices: [ 'Almond', 'Apple', 'Banana', 'Blackberry', 'Blueberry', 'Cherry', 'Chocolate', 'Cinnamon', 'Coconut', 'Cranberry', 'Grape', 'Nougat', 'Orange', 'Pear', 'Pineapple', 'Raspberry', 'Strawberry', 'Vanilla', 'Watermelon', 'Wintergreen' ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **AutoComplete Options** | Option | Type | Default | Description | | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. | | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. | | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. | | `initial` | `number` | 0 | Preselected item in the list of choices. | | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) | **Related prompts** * [Select](#select-prompt) * [MultiSelect](#multiselect-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### BasicAuth Prompt Prompt that asks for username and password to authenticate the user. The default implementation of `authenticate` function in `BasicAuth` prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the `authenticate` function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750"> </p> **Example Usage** ```js const { BasicAuth } = require('enquirer'); const prompt = new BasicAuth({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '123', showPassword: true }); prompt .run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Confirm Prompt Prompt that returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750"> </p> **Example Usage** ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Want to answer?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Form Prompt Prompt that allows the user to enter and submit multiple values on a single terminal screen. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750"> </p> **Example Usage** ```js const { Form } = require('enquirer'); const prompt = new Form({ name: 'user', message: 'Please provide the following information:', choices: [ { name: 'firstname', message: 'First Name', initial: 'Jon' }, { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' }, { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' } ] }); prompt.run() .then(value => console.log('Answer:', value)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Input Prompt Prompt that takes user input and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750"> </p> **Example Usage** ```js const { Input } = require('enquirer'); const prompt = new Input({ message: 'What is your username?', initial: 'jonschlinkert' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.log); ``` You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)). **Related prompts** * [Confirm](#confirm-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Invisible Prompt Prompt that takes user input, hides it from the terminal, and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750"> </p> **Example Usage** ```js const { Invisible } = require('enquirer'); const prompt = new Invisible({ name: 'secret', message: 'What is your secret?' }); prompt.run() .then(answer => console.log('Answer:', { secret: answer })) .catch(console.error); ``` **Related prompts** * [Password](#password-prompt) * [Input](#input-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### List Prompt Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750"> </p> **Example Usage** ```js const { List } = require('enquirer'); const prompt = new List({ name: 'keywords', message: 'Type comma-separated keywords' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Sort](#sort-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### MultiSelect Prompt Prompt that allows the user to select multiple items from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750"> </p> **Example Usage** ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: ['aqua', 'blue', 'fuchsia'] ``` **Example key-value pairs** Optionally, pass a `result` function and use the `.map` method to return an object of key-value pairs of the selected names and values: [example](./examples/multiselect/option-result.js) ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ], result(names) { return this.map(names); } }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' } ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Numeral Prompt Prompt that takes a number as input. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750"> </p> **Example Usage** ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ name: 'number', message: 'Please enter a number' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Confirm](#confirm-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Password Prompt Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt) <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750"> </p> **Example Usage** ```js const { Password } = require('enquirer'); const prompt = new Password({ name: 'password', message: 'What is your password?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Invisible](#invisible-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Quiz Prompt Prompt that allows the user to play multiple-choice quiz questions. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750"> </p> **Example Usage** ```js const { Quiz } = require('enquirer'); const prompt = new Quiz({ name: 'countries', message: 'How many countries are there in the world?', choices: ['165', '175', '185', '195', '205'], correctChoice: 3 }); prompt .run() .then(answer => { if (answer.correct) { console.log('Correct!'); } else { console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); } }) .catch(console.error); ``` **Quiz Options** | Option | Type | Required | Description | | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | | `choices` | `array` | Yes | The list of possible answers to the quiz question. | | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. | **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Survey Prompt Prompt that allows the user to provide feedback for a list of questions. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"> </p> **Example Usage** ```js const { Survey } = require('enquirer'); const prompt = new Survey({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.' }, { name: 'navigation', message: 'The website is easy to navigate.' }, { name: 'images', message: 'The website usually has good images.' }, { name: 'upload', message: 'The website makes it easy to upload images.' }, { name: 'colors', message: 'The website has a pleasing color palette.' } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [Scale](#scale-prompt) * [Snippet](#snippet-prompt) * [Select](#select-prompt) *** ### Scale Prompt A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale). <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750"> </p> **Example Usage** ```js const { Scale } = require('enquirer'); const prompt = new Scale({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.', initial: 2 }, { name: 'navigation', message: 'The website is easy to navigate.', initial: 2 }, { name: 'images', message: 'The website usually has good images.', initial: 2 }, { name: 'upload', message: 'The website makes it easy to upload images.', initial: 2 }, { name: 'colors', message: 'The website has a pleasing color palette.', initial: 2 } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Select Prompt Prompt that allows the user to select from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750"> </p> **Example Usage** ```js const { Select } = require('enquirer'); const prompt = new Select({ name: 'color', message: 'Pick a flavor', choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [MultiSelect](#multiselect-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Sort Prompt Prompt that allows the user to sort items in a list. **Example** In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750"> </p> **Example Usage** ```js const colors = require('ansi-colors'); const { Sort } = require('enquirer'); const prompt = new Sort({ name: 'colors', message: 'Sort the colors in order of preference', hint: 'Top is best, bottom is worst', numbered: true, choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ name: n, message: colors[n](n) })) }); prompt.run() .then(function(answer = []) { console.log(answer); console.log('Your preferred order of colors is:'); console.log(answer.map(key => colors[key](key)).join('\n')); }) .catch(console.error); ``` **Related prompts** * [List](#list-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Snippet Prompt Prompt that allows the user to replace placeholders in a snippet of code or text. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750"> </p> **Example Usage** ```js const semver = require('semver'); const { Snippet } = require('enquirer'); const prompt = new Snippet({ name: 'username', message: 'Fill out the fields in package.json', required: true, fields: [ { name: 'author_name', message: 'Author Name' }, { name: 'version', validate(value, state, item, index) { if (item && item.name === 'version' && !semver.valid(value)) { return prompt.styles.danger('version should be a valid semver value'); } return true; } } ], template: `{ "name": "\${name}", "description": "\${description}", "version": "\${version}", "homepage": "https://github.com/\${username}/\${name}", "author": "\${author_name} (https://github.com/\${username})", "repository": "\${username}/\${name}", "license": "\${license:ISC}" } ` }); prompt.run() .then(answer => console.log('Answer:', answer.result)) .catch(console.error); ``` **Related prompts** * [Survey](#survey-prompt) * [AutoComplete](#autocomplete-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Toggle Prompt Prompt that allows the user to toggle between two values then returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750"> </p> **Example Usage** ```js const { Toggle } = require('enquirer'); const prompt = new Toggle({ message: 'Want to answer?', enabled: 'Yep', disabled: 'Nope' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Confirm](#confirm-prompt) * [Input](#input-prompt) * [Sort](#sort-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Prompt Types There are 5 (soon to be 6!) type classes: * [ArrayPrompt](#arrayprompt) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [Choices](#choices) - [Defining choices](#defining-choices) - [Choice properties](#choice-properties) - [Related prompts](#related-prompts) * [AuthPrompt](#authprompt) * [BooleanPrompt](#booleanprompt) * DatePrompt (Coming Soon!) * [NumberPrompt](#numberprompt) * [StringPrompt](#stringprompt) Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how. ### ArrayPrompt The `ArrayPrompt` class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the [Select](#select) and [Survey](#survey) prompts. #### Options In addition to the [options](#options) available to all prompts, Array prompts also support the following options. | **Option** | **Required?** | **Type** | **Description** | | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | | | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. | | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. | | | #### Properties Array prompts have the following instance properties and getters. | **Property name** | **Type** | **Description** | | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. | | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. | | `enabled` | `array` | Returns an array of enabled choices. | | `focused` | `array` | Returns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is _focused_, the list will scroll to the focused choice and re-render. | | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. | | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. | | `limit` | `number` | The number of choices to display on-screen. | | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. | | `visible` | `string` | | #### Methods | **Method** | **Description** | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pointer()` | Returns the visual symbol to use to identify the choice that currently has focus. The `❯` symbol is often used for this. The pointer is not always visible, as with the `autocomplete` prompt. | | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. | | `focus()` | Sets focus on a choice, if it can be focused. | #### Choices Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal. **Type**: `string|object` **Example** ```js const { prompt } = require('enquirer'); const questions = [{ type: 'select', name: 'color', message: 'Favorite color?', initial: 1, choices: [ { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object ] }]; let answers = await prompt(questions); console.log('Answer:', answers.color); ``` #### Defining choices Whether defined as a string or object, choices are normalized to the following interface: ```js { name: string; message: string | undefined; value: string | undefined; hint: string | undefined; disabled: boolean | string | undefined; } ``` **Example** ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: ['Apple', 'Orange', 'Raspberry'] }; ``` Normalizes to the following when the prompt is run: ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: [ { name: 'Apple', message: 'Apple', value: 'Apple' }, { name: 'Orange', message: 'Orange', value: 'Orange' }, { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } ] }; ``` #### Choice properties The following properties are supported on `choice` objects. | **Option** | **Type** | **Description** | | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The unique key to identify a choice | | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. | | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. | | `choices` | `array` | Array of "child" choices. | | `hint` | `string` | Help message to display next to a choice. | | `role` | `string` | Determines how the choice will be displayed. Currently the only role supported is `separator`. Additional roles may be added in the future (like `heading`, etc). Please create a [feature request] | | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). | | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. | | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). | #### Related prompts * [AutoComplete](#autocomplete-prompt) * [Form](#form-prompt) * [MultiSelect](#multiselect-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) *** ### AuthPrompt The `AuthPrompt` is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the [BasicAuth Prompt](#basicauth-prompt). You can also find prompt examples in `examples/auth/` folder that utilizes `AuthPrompt` to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others. `AuthPrompt` has a factory function that creates an instance of `AuthPrompt` class and it expects an `authenticate` function, as an argument, which overrides the `authenticate` function of the `AuthPrompt` class. #### Methods | **Method** | **Description** | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticate()` | Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default `authenticate` function throws an error if no other function is provided. | #### Choices Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt). **Example** ```js const { AuthPrompt } = require('enquirer'); function authenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } const CustomAuthPrompt = AuthPrompt.create(authenticate); const prompt = new CustomAuthPrompt({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '1234567', choices: [ { name: 'username', message: 'username' }, { name: 'password', message: 'password' } ] }); prompt .run() .then(answer => console.log('Authenticated?', answer)) .catch(console.error); ``` #### Related prompts * [BasicAuth Prompt](#basicauth-prompt) *** ### BooleanPrompt The `BooleanPrompt` class is used for creating prompts that display and return a boolean value. ```js const { BooleanPrompt } = require('enquirer'); const prompt = new BooleanPrompt({ header: '========================', message: 'Do you love enquirer?', footer: '========================', }); prompt.run() .then(answer => console.log('Selected:', answer)) .catch(console.error); ``` **Returns**: `boolean` *** ### NumberPrompt The `NumberPrompt` class is used for creating prompts that display and return a numerical value. ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ header: '************************', message: 'Input the Numbers:', footer: '************************', }); prompt.run() .then(answer => console.log('Numbers are:', answer)) .catch(console.error); ``` **Returns**: `string|number` (number, or number formatted as a string) *** ### StringPrompt The `StringPrompt` class is used for creating prompts that display and return a string value. ```js const { StringPrompt } = require('enquirer'); const prompt = new StringPrompt({ header: '************************', message: 'Input the String:', footer: '************************' }); prompt.run() .then(answer => console.log('String is:', answer)) .catch(console.error); ``` **Returns**: `string` <br> ## ❯ Custom prompts With Enquirer 2.0, custom prompts are easier than ever to create and use. **How do I create a custom prompt?** Custom prompts are created by extending either: * Enquirer's `Prompt` class * one of the built-in [prompts](#-prompts), or * low-level [types](#-types). <!-- Example: HaiKarate Custom Prompt --> ```js const { Prompt } = require('enquirer'); class HaiKarate extends Prompt { constructor(options = {}) { super(options); this.value = options.initial || 0; this.cursorHide(); } up() { this.value++; this.render(); } down() { this.value--; this.render(); } render() { this.clear(); // clear previously rendered prompt from the terminal this.write(`${this.state.message}: ${this.value}`); } } // Use the prompt by creating an instance of your custom prompt class. const prompt = new HaiKarate({ message: 'How many sprays do you want?', initial: 10 }); prompt.run() .then(answer => console.log('Sprays:', answer)) .catch(console.error); ``` If you want to be able to specify your prompt by `type` so that it may be used alongside other prompts, you will need to first create an instance of `Enquirer`. ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` Then use the `.register()` method to add your custom prompt. ```js enquirer.register('haikarate', HaiKarate); ``` Now you can do the following when defining "questions". ```js let spritzer = require('cologne-drone'); let answers = await enquirer.prompt([ { type: 'haikarate', name: 'cologne', message: 'How many sprays do you need?', initial: 10, async onSubmit(name, value) { await spritzer.activate(value); //<= activate drone return value; } } ]); ``` <br> ## ❯ Key Bindings ### All prompts These key combinations may be used with all prompts. | **command** | **description** | | -------------------------------- | -------------------------------------- | | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. | | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. | <br> ### Move cursor These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>left</kbd> | Move the cursor back one character. | | <kbd>right</kbd> | Move the cursor forward one character. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> ### Edit Input These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> | **command (Mac)** | **command (Windows)** | **description** | | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. | | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. | | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | ### Select choices These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true. | **command** | **description** | | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. | | <kbd>i</kbd> | Invert the current selection of choices. | | <kbd>g</kbd> | Toggle the current choice group. | <br> ### Hide/show choices | **command** | **description** | | ------------------------------- | ---------------------------------------------- | | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. | | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. | <br> ### Move/lock Pointer | **command** | **description** | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>up</kbd> | Move the pointer up. | | <kbd>down</kbd> | Move the pointer down. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. | | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). | | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). | <br> | **command (Mac)** | **command (Windows)** | **description** | | -------------------------------- | --------------------- | ---------------------------------------------------------- | | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. | | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. | <br> ## ❯ Release History Please see [CHANGELOG.md](CHANGELOG.md). ## ❯ Performance ### System specs MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB. ### Load time Time it takes for the module to load the first time (average of 3 runs): ``` enquirer: 4.013ms inquirer: 286.717ms ``` <br> ## ❯ About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Todo We're currently working on documentation for the following items. Please star and watch the repository for updates! * [ ] Customizing symbols * [ ] Customizing styles (palette) * [ ] Customizing rendered input * [ ] Customizing returned values * [ ] Customizing key bindings * [ ] Question validation * [ ] Choice validation * [ ] Skipping questions * [ ] Async choices * [ ] Async timers: loaders, spinners and other animations * [ ] Links to examples </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ```sh $ yarn && yarn test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> #### Contributors | **Commits** | **Contributor** | | --- | --- | | 283 | [jonschlinkert](https://github.com/jonschlinkert) | | 82 | [doowb](https://github.com/doowb) | | 32 | [rajat-sr](https://github.com/rajat-sr) | | 20 | [318097](https://github.com/318097) | | 15 | [g-plane](https://github.com/g-plane) | | 12 | [pixelass](https://github.com/pixelass) | | 5 | [adityavyas611](https://github.com/adityavyas611) | | 5 | [satotake](https://github.com/satotake) | | 3 | [tunnckoCore](https://github.com/tunnckoCore) | | 3 | [Ovyerus](https://github.com/Ovyerus) | | 3 | [sw-yx](https://github.com/sw-yx) | | 2 | [DanielRuf](https://github.com/DanielRuf) | | 2 | [GabeL7r](https://github.com/GabeL7r) | | 1 | [AlCalzone](https://github.com/AlCalzone) | | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) | | 1 | [danieldelcore](https://github.com/danieldelcore) | | 1 | [ImgBotApp](https://github.com/ImgBotApp) | | 1 | [jsonkao](https://github.com/jsonkao) | | 1 | [knpwrs](https://github.com/knpwrs) | | 1 | [yeskunall](https://github.com/yeskunall) | | 1 | [mischah](https://github.com/mischah) | | 1 | [renarsvilnis](https://github.com/renarsvilnis) | | 1 | [sbugert](https://github.com/sbugert) | | 1 | [stephencweiss](https://github.com/stephencweiss) | | 1 | [skellock](https://github.com/skellock) | | 1 | [whxaxes](https://github.com/whxaxes) | #### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) #### Credit Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts. #### License Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # regexpp [![npm version](https://img.shields.io/npm/v/regexpp.svg)](https://www.npmjs.com/package/regexpp) [![Downloads/month](https://img.shields.io/npm/dm/regexpp.svg)](http://www.npmtrends.com/regexpp) [![Build Status](https://github.com/mysticatea/regexpp/workflows/CI/badge.svg)](https://github.com/mysticatea/regexpp/actions) [![codecov](https://codecov.io/gh/mysticatea/regexpp/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/regexpp) [![Dependency Status](https://david-dm.org/mysticatea/regexpp.svg)](https://david-dm.org/mysticatea/regexpp) A regular expression parser for ECMAScript. ## 💿 Installation ```bash $ npm install regexpp ``` - require Node.js 8 or newer. ## 📖 Usage ```ts import { AST, RegExpParser, RegExpValidator, RegExpVisitor, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST } from "regexpp" ``` ### parseRegExpLiteral(source, options?) Parse a given regular expression literal then make AST object. This is equivalent to `new RegExpParser(options).parseLiteral(source)`. - **Parameters:** - `source` (`string | RegExp`) The source code to parse. - `options?` ([`RegExpParser.Options`]) The options to parse. - **Return:** - The AST of the regular expression. ### validateRegExpLiteral(source, options?) Validate a given regular expression literal. This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. - **Parameters:** - `source` (`string`) The source code to validate. - `options?` ([`RegExpValidator.Options`]) The options to validate. ### visitRegExpAST(ast, handlers) Visit each node of a given AST. This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. ### RegExpParser #### new RegExpParser(options?) - **Parameters:** - `options?` ([`RegExpParser.Options`]) The options to parse. #### parser.parseLiteral(source, start?, end?) Parse a regular expression literal. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression. #### parser.parsePattern(source, start?, end?, uFlag?) Parse a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"abc"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. - **Return:** - The AST of the regular expression pattern. #### parser.parseFlags(source, start?, end?) Parse a regular expression flags. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"gim"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression flags. ### RegExpValidator #### new RegExpValidator(options) - **Parameters:** - `options` ([`RegExpValidator.Options`]) The options to validate. #### validator.validateLiteral(source, start, end) Validate a regular expression literal. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. #### validator.validatePattern(source, start, end, uFlag) Validate a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. #### validator.validateFlags(source, start, end) Validate a regular expression flags. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. ### RegExpVisitor #### new RegExpVisitor(handlers) - **Parameters:** - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. #### visitor.visit(ast) Validate a regular expression literal. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. ## 📰 Changelog - [GitHub Releases](https://github.com/mysticatea/regexpp/releases) ## 🍻 Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. - `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. - `npm run lint` runs ESLint. - `npm run update:test` updates test fixtures. - `npm run update:ids` updates `src/unicode/ids.ts`. - `npm run watch` runs tests with `--watch` option. [`AST.Node`]: src/ast.ts#L4 [`RegExpParser.Options`]: src/parser.ts#L539 [`RegExpValidator.Options`]: src/validator.ts#L127 [`RegExpVisitor.Handlers`]: src/visitor.ts#L204 # flat-cache > A stupidly simple key/value storage using files to persist the data [![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) [![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache) ## install ```bash npm i --save flat-cache ``` ## Usage ```js var flatCache = require('flat-cache') // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var cache = flatCache.load('cacheId'); // sets a key on the cache cache.setKey('key', { foo: 'var' }); // get a key from the cache cache.getKey('key') // { foo: 'var' } // fetch the entire persisted object cache.all() // { 'key': { foo: 'var' } } // remove a key cache.removeKey('key'); // removes a key from the cache // save it to disk cache.save(); // very important, if you don't save no changes will be persisted. // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys // loads the cache from a given directory, if one does // not exists for the given Id a new one will be prepared to be created var cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); // The following methods are useful to clear the cache // delete a given cache flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists. // delete all cache flatCache.clearAll(); // remove the cache directory ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` storage was needed and Bam! this module was born. ## Important notes - If no directory is especified when the `load` method is called, a folder named `.cache` will be created inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you might want to ignore the default `.cache` folder, or specify a custom directory. - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references - All the changes to the cache state are done to memory - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module intentionally dumb and simple - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call like: `cache.save( true /* noPrune */ )`. ## License MIT ## Changelog [changelog](./changelog.md) ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) Shims used when bundling asc for browser usage. # eslint-utils [![npm version](https://img.shields.io/npm/v/eslint-utils.svg)](https://www.npmjs.com/package/eslint-utils) [![Downloads/month](https://img.shields.io/npm/dm/eslint-utils.svg)](http://www.npmtrends.com/eslint-utils) [![Build Status](https://github.com/mysticatea/eslint-utils/workflows/CI/badge.svg)](https://github.com/mysticatea/eslint-utils/actions) [![Coverage Status](https://codecov.io/gh/mysticatea/eslint-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-utils) [![Dependency Status](https://david-dm.org/mysticatea/eslint-utils.svg)](https://david-dm.org/mysticatea/eslint-utils) ## 🏁 Goal This package provides utility functions and classes for make ESLint custom rules. For examples: - [getStaticValue](https://eslint-utils.mysticatea.dev/api/ast-utils.html#getstaticvalue) evaluates static value on AST. - [ReferenceTracker](https://eslint-utils.mysticatea.dev/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. ## 📖 Usage See [documentation](https://eslint-utils.mysticatea.dev/). ## 📰 Changelog See [releases](https://github.com/mysticatea/eslint-utils/releases). ## ❤️ Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run clean` removes the coverage result of `npm test` command. - `npm run coverage` shows the coverage result of the last `npm test` command. - `npm run lint` runs ESLint. - `npm run watch` runs tests on each file change. # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg"> &nbsp; # Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). [![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-%2307b4b9)](https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2Fap4lMFzfXF8Hzmh-Vz0WNxp_1jKiOa-h%23MCowBQYDK2VuAyEAcdefddRvDfI8iAuBpztm_J3qFucj8MDZoVs_2EcMTzU%3D) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv sponsors [<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv) ## Contributing More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). ## Documentation All documentation is available on the [Ajv website](https://ajv.js.org). Some useful site links: - [Getting started](https://ajv.js.org/guide/getting-started.html) - [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) - [API reference](https://ajv.js.org/api.html) - [Strict mode](https://ajv.js.org/strict-mode.html) - [Standalone validation code](https://ajv.js.org/standalone.html) - [Security considerations](https://ajv.js.org/security.html) - [Command line interface](https://ajv.js.org/packages/ajv-cli.html) - [Frequently Asked Questions](https://ajv.js.org/faq.html) ## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a> ## Performance Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus&#x2F;schemasafe|is-my-json-valid|djv|@cfworker&#x2F;json-schema|jsonschema&chd=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) - support of recursive references between schemas - correct string lengths for strings with unicode pairs - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) - NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) - meta-schema for JTD schemas - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) - supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current - [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) - [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) - [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items - [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords - [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) - additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords ## Install To install version 8: ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://runkit.com/npm/ajv In JavaScript: ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false, } const data = { foo: 1, bar: "abc" } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) ## Changes history See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) **Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) [Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](./LICENSE) <a name="table"></a> # Table > Produces a string that represents array data in a text table. [![Github action status](https://github.com/gajus/table/actions/workflows/main.yml/badge.svg)](https://github.com/gajus/table/actions) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) [![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical) [![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas) * [Table](#table) * [Features](#table-features) * [Install](#table-install) * [Usage](#table-usage) * [API](#table-api) * [table](#table-api-table-1) * [createStream](#table-api-createstream) * [getBorderCharacters](#table-api-getbordercharacters) ![Demo of table displaying a list of missions to the Moon.](./.README/demo.png) <a name="table-features"></a> ## Features * Works with strings containing [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) characters. * Works with strings containing [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). * Configurable border characters. * Configurable content alignment per column. * Configurable content padding per column. * Configurable column width. * Text wrapping. <a name="table-install"></a> ## Install ```bash npm install table ``` [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) [![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) <a name="table-usage"></a> ## Usage ```js import { table } from 'table'; // Using commonjs? // const { table } = require('table'); const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; console.log(table(data)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ ``` <a name="table-api"></a> ## API <a name="table-api-table-1"></a> ### table Returns the string in the table format **Parameters:** - **_data_:** The data to display - Type: `any[][]` - Required: `true` - **_config_:** Table configuration - Type: `object` - Required: `false` <a name="table-api-table-1-config-border"></a> ##### config.border Type: `{ [type: string]: string }`\ Default: `honeywell` [template](#getbordercharacters) Custom borders. The keys are any of: - `topLeft`, `topRight`, `topBody`,`topJoin` - `bottomLeft`, `bottomRight`, `bottomBody`, `bottomJoin` - `joinLeft`, `joinRight`, `joinBody`, `joinJoin` - `bodyLeft`, `bodyRight`, `bodyJoin` - `headerJoin` ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: { topBody: `─`, topJoin: `┬`, topLeft: `┌`, topRight: `┐`, bottomBody: `─`, bottomJoin: `┴`, bottomLeft: `└`, bottomRight: `┘`, bodyLeft: `│`, bodyRight: `│`, bodyJoin: `│`, joinBody: `─`, joinLeft: `├`, joinRight: `┤`, joinJoin: `┼` } }; console.log(table(data, config)); ``` ``` ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ ``` <a name="table-api-table-1-config-drawverticalline"></a> ##### config.drawVerticalLine Type: `(lineIndex: number, columnCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a vertical line. This callback is called for each vertical border of the table. If the table has `n` columns, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawVerticalLine: (lineIndex, columnCount) => { return lineIndex === 0 || lineIndex === columnCount; } }; console.log(table(data, config)); ``` ``` ╔════════════╗ ║ 0A 0B 0C ║ ╟────────────╢ ║ 1A 1B 1C ║ ╟────────────╢ ║ 2A 2B 2C ║ ╟────────────╢ ║ 3A 3B 3C ║ ╟────────────╢ ║ 4A 4B 4C ║ ╚════════════╝ ``` <a name="table-api-table-1-config-drawhorizontalline"></a> ##### config.drawHorizontalLine Type: `(lineIndex: number, rowCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a horizontal line. This callback is called for each horizontal border of the table. If the table has `n` rows, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. If the table has `n` rows and contains the header, then the range will be `[0, n+1]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawHorizontalLine: (lineIndex, rowCount) => { return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount - 1 || lineIndex === rowCount; } }; console.log(table(data, config)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ║ 2A │ 2B │ 2C ║ ║ 3A │ 3B │ 3C ║ ╟────┼────┼────╢ ║ 4A │ 4B │ 4C ║ ╚════╧════╧════╝ ``` <a name="table-api-table-1-config-singleline"></a> ##### config.singleLine Type: `boolean`\ Default: `false` If `true`, horizontal lines inside the table are not drawn. This option also overrides the `config.drawHorizontalLine` if specified. ```js const data = [ ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], ]; const config = { singleLine: true }; console.log(table(data, config)); ``` ``` ╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ ║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ ║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ ║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ ║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ ║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ ║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ ╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ ``` <a name="table-api-table-1-config-columns"></a> ##### config.columns Type: `Column[] | { [columnIndex: number]: Column }` Column specific configurations. <a name="table-api-table-1-config-columns-config-columns-width"></a> ###### config.columns[*].width Type: `number`\ Default: the maximum cell widths of the column Column width (excluding the paddings). ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: { 1: { width: 10 } } }; console.log(table(data, config)); ``` ``` ╔════╤════════════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────────────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────────────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════════════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-alignment"></a> ###### config.columns[*].alignment Type: `'center' | 'justify' | 'left' | 'right'`\ Default: `'left'` Cell content horizontal alignment ```js const data = [ ['0A', '0B', '0C', '0D 0E 0F'], ['1A', '1B', '1C', '1D 1E 1F'], ['2A', '2B', '2C', '2D 2E 2F'], ]; const config = { columnDefault: { width: 10, }, columns: [ { alignment: 'left' }, { alignment: 'center' }, { alignment: 'right' }, { alignment: 'justify' } ], }; console.log(table(data, config)); ``` ``` ╔════════════╤════════════╤════════════╤════════════╗ ║ 0A │ 0B │ 0C │ 0D 0E 0F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C │ 1D 1E 1F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C │ 2D 2E 2F ║ ╚════════════╧════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-verticalalignment"></a> ###### config.columns[*].verticalAlignment Type: `'top' | 'middle' | 'bottom'`\ Default: `'top'` Cell content vertical alignment ```js const data = [ ['A', 'B', 'C', 'DEF'], ]; const config = { columnDefault: { width: 1, }, columns: [ { verticalAlignment: 'top' }, { verticalAlignment: 'middle' }, { verticalAlignment: 'bottom' }, ], }; console.log(table(data, config)); ``` ``` ╔═══╤═══╤═══╤═══╗ ║ A │ │ │ D ║ ║ │ B │ │ E ║ ║ │ │ C │ F ║ ╚═══╧═══╧═══╧═══╝ ``` <a name="table-api-table-1-config-columns-config-columns-paddingleft"></a> ###### config.columns[*].paddingLeft Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the left. <a name="table-api-table-1-config-columns-config-columns-paddingright"></a> ###### config.columns[*].paddingRight Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the right. The `paddingLeft` and `paddingRight` options do not count on the column width. So the column has `width = 5`, `paddingLeft = 2` and `paddingRight = 2` will have the total width is `9`. ```js const data = [ ['0A', 'AABBCC', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: [ { paddingLeft: 3 }, { width: 2, paddingRight: 3 } ] }; console.log(table(data, config)); ``` ``` ╔══════╤══════╤════╗ ║ 0A │ AA │ 0C ║ ║ │ BB │ ║ ║ │ CC │ ║ ╟──────┼──────┼────╢ ║ 1A │ 1B │ 1C ║ ╟──────┼──────┼────╢ ║ 2A │ 2B │ 2C ║ ╚══════╧══════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-truncate"></a> ###### config.columns[*].truncate Type: `number`\ Default: `Infinity` The number of characters is which the content will be truncated. To handle a content that overflows the container width, `table` package implements [text wrapping](#config.columns[*].wrapWord). However, sometimes you may want to truncate content that is too long to be displayed in the table. ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20, truncate: 100 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convall… ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-wrapword"></a> ###### config.columns[*].wrapWord Type: `boolean`\ Default: `false` The `table` package implements auto text wrapping, i.e., text that has the width greater than the container width will be separated into multiple lines at the nearest space or one of the special characters: `\|/_.,;-`. When `wrapWord` is `false`: ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convallis ║ ║ dapibus. Nunc venena ║ ║ tis tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` When `wrapWord` is `true`: ``` ╔══════════════════════╗ ║ Lorem ipsum dolor ║ ║ sit amet, ║ ║ consectetur ║ ║ adipiscing elit. ║ ║ Phasellus pulvinar ║ ║ nibh sed mauris ║ ║ convallis dapibus. ║ ║ Nunc venenatis ║ ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columndefault"></a> ##### config.columnDefault Type: `Column`\ Default: `{}` The default configuration for all columns. Column-specific settings will overwrite the default values. <a name="table-api-table-1-config-header"></a> ##### config.header Type: `object` Header configuration. *Deprecated in favor of the new spanning cells API.* The header configuration inherits the most of the column's, except: - `content` **{string}**: the header content. - `width:` calculate based on the content width automatically. - `alignment:` `center` be default. - `verticalAlignment:` is not supported. - `config.border.topJoin` will be `config.border.topBody` for prettier. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ]; const config = { columnDefault: { width: 10, }, header: { alignment: 'center', content: 'THE HEADER\nThis is the table about something', }, } console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════╗ ║ THE HEADER ║ ║ This is the table about something ║ ╟────────────┬────────────┬────────────╢ ║ 0A │ 0B │ 0C ║ ╟────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C ║ ╟────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C ║ ╚════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-spanningcells"></a> ##### config.spanningCells Type: `SpanningCellConfig[]` Spanning cells configuration. The configuration should be straightforward: just specify an array of minimal cell configurations including the position of top-left cell and the number of columns and/or rows will be expanded from it. The content of overlap cells will be ignored to make the `data` shape be consistent. By default, the configuration of column that the top-left cell belongs to will be applied to the whole spanning cell, except: * The `width` will be summed up of all spanning columns. * The `paddingRight` will be received from the right-most column intentionally. Advances customized column-like styles can be configurable to each spanning cell to overwrite the default behavior. ```js const data = [ ['Test Coverage Report', '', '', '', '', ''], ['Module', 'Component', 'Test Cases', 'Failures', 'Durations', 'Success Rate'], ['Services', 'User', '50', '30', '3m 7s', '60.0%'], ['', 'Payment', '100', '80', '7m 15s', '80.0%'], ['Subtotal', '', '150', '110', '10m 22s', '73.3%'], ['Controllers', 'User', '24', '18', '1m 30s', '75.0%'], ['', 'Payment', '30', '24', '50s', '80.0%'], ['Subtotal', '', '54', '42', '2m 20s', '77.8%'], ['Total', '', '204', '152', '12m 42s', '74.5%'], ]; const config = { columns: [ { alignment: 'center', width: 12 }, { alignment: 'center', width: 10 }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' } ], spanningCells: [ { col: 0, row: 0, colSpan: 6 }, { col: 0, row: 2, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 4, colSpan: 2, alignment: 'right'}, { col: 0, row: 5, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 7, colSpan: 2, alignment: 'right' }, { col: 0, row: 8, colSpan: 2, alignment: 'right' } ], }; console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Test Coverage Report ║ ╟──────────────┬────────────┬────────────┬──────────┬───────────┬──────────────╢ ║ Module │ Component │ Test Cases │ Failures │ Durations │ Success Rate ║ ╟──────────────┼────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 50 │ 30 │ 3m 7s │ 60.0% ║ ║ Services ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 100 │ 80 │ 7m 15s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 150 │ 110 │ 10m 22s │ 73.3% ║ ╟──────────────┬────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 24 │ 18 │ 1m 30s │ 75.0% ║ ║ Controllers ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 30 │ 24 │ 50s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 54 │ 42 │ 2m 20s │ 77.8% ║ ╟───────────────────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Total │ 204 │ 152 │ 12m 42s │ 74.5% ║ ╚═══════════════════════════╧════════════╧══════════╧═══════════╧══════════════╝ ``` <a name="table-api-createstream"></a> ### createStream `table` package exports `createStream` function used to draw a table and append rows. **Parameter:** - _**config:**_ the same as `table`'s, except `config.columnDefault.width` and `config.columnCount` must be provided. ```js import { createStream } from 'table'; const config = { columnDefault: { width: 50 }, columnCount: 1 }; const stream = createStream(config); setInterval(() => { stream.write([new Date()]); }, 500); ``` ![Streaming current date.](./.README/api/stream/streaming.gif) `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { createStream } from 'table'; import _ from 'lodash'; const config = { columnDefault: { width: 50 }, columnCount: 3, columns: [ { width: 10, alignment: 'right' }, { alignment: 'center' }, { width: 10 } ] }; const stream = createStream(config); let i = 0; setInterval(() => { let random; random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/api/stream/streaming-random.gif) <a name="table-api-getbordercharacters"></a> ### getBorderCharacters **Parameter:** - **_template_** - Type: `'honeywell' | 'norc' | 'ramac' | 'void'` - Required: `true` You can load one of the predefined border templates using `getBorderCharacters` function. ```js import { table, getBorderCharacters } from 'table'; const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: getBorderCharacters(`name of the template`) }; console.log(table(data, config)); ``` ``` # honeywell ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ # norc ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ # ramac (ASCII; for use in terminals that do not support Unicode characters) +----+----+----+ | 0A | 0B | 0C | |----|----|----| | 1A | 1B | 1C | |----|----|----| | 2A | 2B | 2C | +----+----+----+ # void (no borders; see "borderless table" section of the documentation) 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` Raise [an issue](https://github.com/gajus/table/issues) if you'd like to contribute a new border template. <a name="table-api-getbordercharacters-borderless-table"></a> #### Borderless Table Simply using `void` border character template creates a table with a lot of unnecessary spacing. To create a more pleasant to the eye table, reset the padding and remove the joining rows, e.g. ```js const output = table(data, { border: getBorderCharacters('void'), columnDefault: { paddingLeft: 0, paddingRight: 1 }, drawHorizontalLine: () => false } ); console.log(output); ``` ``` 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js const rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. [![build status](https://app.travis-ci.com/dankogai/js-base64.svg)](https://app.travis-ci.com/github/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.encode(latin, true)); // ZGFua29nYWk skips padding Base64.encodeURI(latin)); // ZGFua29nYWk Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.decode( 'ZGFua29nYWk'); // dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend Uint8Array.prototype Base64.extendUint8Array(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IEs before 11. Do the following in your shell. ```shell $ make base64.es5.js ``` ## Brief History * Since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. * Since version 3.7 `base64.js` is ES5-compatible again (hence IE11-compabile). * Since 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above) # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) [![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## Enterprise support json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv v7 beta is released [Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: - to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. - to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. - to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. - schemas are compiled to ES6 code (ES5 code generation is supported with an option). - to improve reliability and maintainability the code is migrated to TypeScript. **Please note**: - the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). - all formats are separated to ajv-formats package - they have to be explicitely added if you use them. See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. To install the new version: ```bash npm install ajv@beta ``` See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. ## Mozilla MOSS grant and OpenJS Foundation [<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) # Acorn-JSX [![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) [![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. ## Transpiler Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. ## Usage Requiring this module provides you with an Acorn plugin that you can use like this: ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');"); ``` Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `[email protected]`. If you still want to opt-in to support of such constructions, you can pass the following option: ```javascript acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) ``` Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: ```javascript acorn.Parser.extend(jsx({ allowNamespaces: false })) ``` Note that by default `allowNamespaces` is enabled for spec compliancy. ## License This plugin is issued under the [MIT license](./LICENSE). JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` ## Enterprise support fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 10.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) ### Status: Work in progress Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> # file-entry-cache > Super simple cache for file metadata, useful for process that work o a given series of files > and that only need to repeat the job on the changed ones since the previous run of the process — Edit [![NPM Version](http://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) [![Build Status](http://img.shields.io/travis/royriojas/file-entry-cache.svg?style=flat)](https://travis-ci.org/royriojas/file-entry-cache) ## install ```bash npm i --save file-entry-cache ``` ## Usage The module exposes two functions `create` and `createFromFile`. ## `create(cacheName, [directory, useCheckSum])` - **cacheName**: the name of the cache to be created - **directory**: Optional the directory to load the cache from - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ## `createFromFile(pathToCache, [useCheckSum])` - **pathToCache**: the path to the cache file (this combines the cache name and directory) - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ```js // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var fileEntryCache = require('file-entry-cache'); var cache = fileEntryCache.create('testCache'); var files = expand('../fixtures/*.txt'); // the first time this method is called, will return all the files var oFiles = cache.getUpdatedFiles(files); // this will persist this to disk checking each file stats and // updating the meta attributes `size` and `mtime`. // custom fields could also be added to the meta object and will be persisted // in order to retrieve them later cache.reconcile(); // use this if you want the non visited file entries to be kept in the cache // for more than one execution // // cache.reconcile( true /* noPrune */) // on a second run var cache2 = fileEntryCache.create('testCache'); // will return now only the files that were modified or none // if no files were modified previous to the execution of this function var oFiles = cache.getUpdatedFiles(files); // if you want to prevent a file from being considered non modified // something useful if a file failed some sort of validation // you can then remove the entry from the cache doing cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` // that will effectively make the file to appear again as modified until the validation is passed. In that // case you should not remove it from the cache // if you need all the files, so you can determine what to do with the changed ones // you can call var oFiles = cache.normalizeEntries(files); // oFiles will be an array of objects like the following entry = { key: 'some/name/file', the path to the file changed: true, // if the file was changed since previous run meta: { size: 3242, // the size of the file mtime: 231231231, // the modification time of the file data: {} // some extra field stored for this file (useful to save the result of a transformation on the file } } ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with optional file persistance. The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, then store the new state of the files. The next time this module request for `getChangedFiles` will return only the files that were modified. Making the process to end faster. This module could also be used by processes that modify the files applying a transform, in that case the result of the transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed the transformed stored data could be used instead of actually applying the transformation, saving time in case of only a few files changed. In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. ## Important notes - The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values - All the changes to the cache state are done to memory first and only persisted after reconcile. ## License MIT # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value = <JSON.Value>valueOrNull; // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let innerString = (<JSON.Str>value).valueOf(); let jsonString = (<JSON.Str>value).stringify(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: string = encoder.stringify(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i64): void { // Handle field } setFloat(name: string, value: f64): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP/HTTPS Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true ### WS/WSS Support URI.parse("wss://example.com/foo?bar=baz"); //returns: //{ // scheme : "wss", // host: "example.com", // resourceName: "/foo?bar=baz", // secure: true, //} URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "uuid", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: npm install uri-js # OR yarn add uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(low: `number`, high: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. ## Timezone support In order to provide support for timezones, without relying on the JavaScript host or any other time-zone aware environment, this library makes use of teh IANA Timezone Database directly: https://www.iana.org/time-zones The database files are parsed by the scripts in this folder, which emit AssemblyScript code which is used to process the various rules at runtime. # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ blockvote Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli ## assemblyscript-temporal An implementation of temporal within AssemblyScript, with an initial focus on non-timezone-aware classes and functionality. ### Why? AssemblyScript has minimal `Date` support, however, the JS Date API itself is terrible and people tend not to use it that often. As a result libraries like moment / luxon have become staple replacements. However, there is now a [relatively mature TC39 proposal](https://github.com/tc39/proposal-temporal) that adds greatly improved date support to JS. The goal of this project is to implement Temporal for AssemblyScript. ### Usage This library currently supports the following types: #### `PlainDateTime` A `PlainDateTime` represents a calendar date and wall-clock time that does not carry time zone information, e.g. December 7th, 1995 at 3:00 PM (in the Gregorian calendar). For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindatetime.html), this implementation follows the specification as closely as possible. You can create a `PlainDateTime` from individual components, a string or an object literal: ```javascript datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.year; // 2019; datetime.month; // 11; // ... datetime.nanosecond; // 789; datetime = PlainDateTime.from("1976-11-18T12:34:56"); datetime.toString(); // "1976-11-18T12:34:56" datetime = PlainDateTime.from({ year: 1966, month: 3, day: 3 }); datetime.toString(); // "1966-03-03T00:00:00" ``` There are various ways you can manipulate a date: ```javascript // use 'with' to copy a date but with various property values overriden datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.with({ year: 2019 }).toString(); // "2019-11-18T15:23:30.123456789" // use 'add' or 'substract' to add / subtract a duration datetime = PlainDateTime.from("2020-01-12T15:00"); datetime.add({ months: 1 }).toString(); // "2020-02-12T15:00:00"); // add / subtract support Duration objects or object literals datetime.add(new Duration(1)).toString(); // "2021-01-12T15:00:00"); ``` You can compare dates and check for equality ```javascript dt1 = PlainDateTime.from("1976-11-18"); dt2 = PlainDateTime.from("2019-10-29"); PlainDateTime.compare(dt1, dt1); // 0 PlainDateTime.compare(dt1, dt2); // -1 dt1.equals(dt1); // true ``` Currently `PlainDateTime` only supports the ISO 8601 (Gregorian) calendar. #### `PlainDate` A `PlainDate` object represents a calendar date that is not associated with a particular time or time zone, e.g. August 24th, 2006. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindate.html), this implementation follows the specification as closely as possible. The `PlainDate` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainTime` A `PlainTime` object represents a wall-clock time that is not associated with a particular date or time zone, e.g. 7:39 PM. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaintime.html), this implementation follows the specification as closely as possible. The `PlainTime` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainMonthDay` A date without a year component. This is useful to express things like "Bastille Day is on the 14th of July". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainmonthday.html) , this implementation follows the specification as closely as possible. ```javascript const monthDay = PlainMonthDay.from({ month: 7, day: 14 }); // => 07-14 const date = monthDay.toPlainDate({ year: 2030 }); // => 2030-07-14 date.dayOfWeek; // => 7 ``` The `PlainMonthDay` API is almost identical to `PlainDateTime`, so see above for more API usage examples. #### `PlainYearMonth` A date without a day component. This is useful to express things like "the October 2020 meeting". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainyearmonth.html) , this implementation follows the specification as closely as possible. The `PlainYearMonth` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `now` The `now` object has several methods which give information about the current time and date. ```javascript dateTime = now.plainDateTimeISO(); dateTime.toString(); // 2021-04-01T12:05:47.357 ``` ## Contributing This project is open source, MIT licensed and your contributions are very much welcomed. There is a [brief document that outlines implementation progress and priorities](./development.md). # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # assemblyscript-regex A regex engine for AssemblyScript. [AssemblyScript](https://www.assemblyscript.org/) is a new language, based on TypeScript, that runs on WebAssembly. AssemblyScript has a lightweight standard library, but lacks support for Regular Expression. The project fills that gap! This project exposes an API that mirrors the JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class: ```javascript const regex = new RegExp("fo*", "g"); const str = "table football, foul"; let match: Match | null = regex.exec(str); while (match != null) { // first iteration // match.index = 6 // match.matches[0] = "foo" // second iteration // match.index = 16 // match.matches[0] = "fo" match = regex.exec(str); } ``` ## Project status The initial focus of this implementation has been feature support and functionality over performance. It currently supports a sufficient number of regex features to be considered useful, including most character classes, common assertions, groups, alternations, capturing groups and quantifiers. The next phase of development will focussed on more extensive testing and performance. The project currently has reasonable unit test coverage, focussed on positive and negative test cases on a per-feature basis. It also includes a more exhaustive test suite with test cases borrowed from another regex library. ### Feature support Based on the classfication within the [MDN cheatsheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) **Character sets** - [x] . - [x] \d - [x] \D - [x] \w - [x] \W - [x] \s - [x] \S - [x] \t - [x] \r - [x] \n - [x] \v - [x] \f - [ ] [\b] - [ ] \0 - [ ] \cX - [x] \xhh - [x] \uhhhh - [ ] \u{hhhh} or \u{hhhhh} - [x] \ **Assertions** - [x] ^ - [x] $ - [ ] \b - [ ] \B **Other assertions** - [ ] x(?=y) Lookahead assertion - [ ] x(?!y) Negative lookahead assertion - [ ] (?<=y)x Lookbehind assertion - [ ] (?<!y)x Negative lookbehind assertion **Groups and ranges** - [x] x|y - [x] [xyz][a-c] - [x] [^xyz][^a-c] - [x] (x) capturing group - [ ] \n back reference - [ ] (?<Name>x) named capturing group - [x] (?:x) Non-capturing group **Quantifiers** - [x] x\* - [x] x+ - [x] x? - [x] x{n} - [x] x{n,} - [x] x{n,m} - [ ] x\*? / x+? / ... **RegExp** - [x] global - [ ] sticky - [x] case insensitive - [x] multiline - [x] dotAll - [ ] unicode ### Development This project is open source, MIT licenced and your contributions are very much welcomed. To get started, check out the repository and install dependencies: ``` $ npm install ``` A few general points about the tools and processes this project uses: - This project uses prettier for code formatting and eslint to provide additional syntactic checks. These are both run on `npm test` and as part of the CI build. - The unit tests are executed using [as-pect](https://github.com/jtenner/as-pect) - a native AssemblyScript test runner - The specification tests are within the `spec` folder. The `npm run test:generate` target transforms these tests into as-pect tests which execute as part of the standard build / test cycle - In order to support improved debugging you can execute this library as TypeScript (rather than WebAssembly), via the `npm run tsrun` target. # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" /> __Light ECMAScript (JavaScript) Value Notation__ Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. __How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. npm install levn For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). ## Quick Examples ```js var parse = require('levn').parse; parse('Number', '2'); // 2 parse('String', '2'); // '2' parse('String', 'levn'); // 'levn' parse('String', 'a b'); // 'a b' parse('Boolean', 'true'); // true parse('Date', '#2011-11-11#'); // (Date object) parse('Date', '2011-11-11'); // (Date object) parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi parse('RegExp', 're'); // /re/ parse('Int', '2'); // 2 parse('Number | String', 'str'); // 'str' parse('Number | String', '2'); // 2 parse('[Number]', '[1,2,3]'); // [1,2,3] parse('(String, Boolean)', '(hi, false)'); // ['hi', false] parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} // at the top level, you can ommit surrounding delimiters parse('[Number]', '1,2,3'); // [1,2,3] parse('(String, Boolean)', 'hi, false'); // ['hi', false] parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} // wildcard - auto choose type parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] ``` ## Usage `require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. ```js // parse(type, input, options); parse('[Number]', '1,2,3'); // [1, 2, 3] // parsedTypeParse(parsedType, input, options); var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ### parse(type, input, options) `parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. ##### arguments * type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js parse('[Number]', '1,2,3'); // [1, 2, 3] ``` ### parsedTypeParse(parsedType, input, options) `parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ## Levn Format Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). * `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` * `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` * `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` * `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents * `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. * `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). * `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. * Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: * If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. * If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. * If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. * If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. * If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). * If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. Whitespace between special characters and elements is inconsequential. ## Options Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. ### Explicit A `Boolean`. By default it is `false`. __Example:__ ```js parse('RegExp', 're', {explicit: false}); // /re/ parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... parse('RegExp | String', 're', {explicit: true}); // 're' ``` `explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. ### customTypes An `Object`. Empty `{}` by default. __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function (x) { return x % 2 === 0; }, cast: function (x) { return {type: 'Just', value: parseInt(x)}; } } } } parse('Even', '2', options); // 2 parse('Even', '3', options); // Error: Value: "3" does not type check... ``` __Another Example:__ ```js function Person(name, age){ this.name = name; this.age = age; } var options = { customTypes: { Person: { typeOf: 'Object', validate: function (x) { x instanceof Person; }, cast: function (value, options, typesCast) { var name, age; if ({}.toString.call(value).slice(8, -1) !== 'Object') { return {type: 'Nothing'}; } name = typesCast(value.name, [{type: 'String'}], options); age = typesCast(value.age, [{type: 'Numger'}], options); return {type: 'Just', value: new Person(name, age)}; } } } parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} ``` `customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. `cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. ## Technical About `levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Aliases Create custom aliases for styles. ```js const colors = require('ansi-colors'); colors.alias('primary', colors.yellow); colors.alias('secondary', colors.bold); console.log(colors.primary.secondary('Foo')); ``` ## Themes A theme is an object of custom aliases. ```js const colors = require('ansi-colors'); colors.theme({ danger: colors.red, dark: colors.dim.gray, disabled: colors.gray, em: colors.italic, heading: colors.bold.underline, info: colors.cyan, muted: colors.dim, primary: colors.blue, strong: colors.bold, success: colors.green, underline: colors.underline, warning: colors.yellow }); // Now, we can use our custom styles alongside the built-in styles! console.log(colors.danger.strong.em('Error!')); console.log(colors.warning('Heads up!')); console.log(colors.info('Did you know...')); console.log(colors.success.bold('It worked!')); ``` ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 48 | [jonschlinkert](https://github.com/jonschlinkert) | | 42 | [doowb](https://github.com/doowb) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._ <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore). Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module. ##### Tested on - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - [Guide for 2.x -> 3.x](#upgrade-2x---3x) - [Guide for 3.x -> 4.x](#upgrade-3x---4x) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array<Pathname>): Array<Pathname> ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory. ```js // WRONG ig.ignores('./abc') // WRONG, for it will never happen. // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js ig.add('config/') // `ig` does NOT know if 'config' is a normal file, directory or something ig.ignores('config') // And it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` **** # Upgrade Guide ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0,4.1,4.2?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: [demo](https://estools.github.io/esquery/) The following selectors are supported: * AST node type: `ForStatement` * [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` * [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` * [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` * attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` * attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` * nested attribute: `[attr.level2="foo"]` * field: `FunctionDeclaration > Identifier.id` * [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` * [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` * [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` * [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` * [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` * [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` * [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` * [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` * [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)` * [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` * [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` * class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` [![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. <img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png"> ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. functional-red-black-tree ========================= A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. # Install npm install functional-red-black-tree # Example Here is an example of some basic usage: ```javascript //Load the library var createTree = require("functional-red-black-tree") //Create a tree var t1 = createTree() //Insert some items into the tree var t2 = t1.insert(1, "foo") var t3 = t2.insert(2, "bar") //Remove something var t4 = t3.remove(1) ``` # API ```javascript var createTree = require("functional-red-black-tree") ``` ## Overview - [Tree methods](#tree-methods) - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) - [`tree.keys`](#treekeys) - [`tree.values`](#treevalues) - [`tree.length`](#treelength) - [`tree.get(key)`](#treegetkey) - [`tree.insert(key, value)`](#treeinsertkey-value) - [`tree.remove(key)`](#treeremovekey) - [`tree.find(key)`](#treefindkey) - [`tree.ge(key)`](#treegekey) - [`tree.gt(key)`](#treegtkey) - [`tree.lt(key)`](#treeltkey) - [`tree.le(key)`](#treelekey) - [`tree.at(position)`](#treeatposition) - [`tree.begin`](#treebegin) - [`tree.end`](#treeend) - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) - [`tree.root`](#treeroot) - [Node properties](#node-properties) - [`node.key`](#nodekey) - [`node.value`](#nodevalue) - [`node.left`](#nodeleft) - [`node.right`](#noderight) - [Iterator methods](#iterator-methods) - [`iter.key`](#iterkey) - [`iter.value`](#itervalue) - [`iter.node`](#iternode) - [`iter.tree`](#itertree) - [`iter.index`](#iterindex) - [`iter.valid`](#itervalid) - [`iter.clone()`](#iterclone) - [`iter.remove()`](#iterremove) - [`iter.update(value)`](#iterupdatevalue) - [`iter.next()`](#iternext) - [`iter.prev()`](#iterprev) - [`iter.hasNext`](#iterhasnext) - [`iter.hasPrev`](#iterhasprev) ## Tree methods ### `var tree = createTree([compare])` Creates an empty functional tree * `compare` is an optional comparison function, same semantics as array.sort() **Returns** An empty tree ordered by `compare` ### `tree.keys` A sorted array of all the keys in the tree ### `tree.values` An array array of all the values in the tree ### `tree.length` The number of items in the tree ### `tree.get(key)` Retrieves the value associated to the given key * `key` is the key of the item to look up **Returns** The value of the first node associated to `key` ### `tree.insert(key, value)` Creates a new tree with the new pair inserted. * `key` is the key of the item to insert * `value` is the value of the item to insert **Returns** A new tree with `key` and `value` inserted ### `tree.remove(key)` Removes the first item with `key` in the tree * `key` is the key of the item to remove **Returns** A new tree with the given item removed if it exists ### `tree.find(key)` Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. ### `tree.ge(key)` Find the first item in the tree whose key is `>= key` * `key` is the key to search for **Returns** An iterator at the given element. ### `tree.gt(key)` Finds the first item in the tree whose key is `> key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.lt(key)` Finds the last item in the tree whose key is `< key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.le(key)` Finds the last item in the tree whose key is `<= key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.at(position)` Finds an iterator starting at the given element * `position` is the index at which the iterator gets created **Returns** An iterator starting at position ### `tree.begin` An iterator pointing to the first element in the tree ### `tree.end` An iterator pointing to the last element in the tree ### `tree.forEach(visitor(key,value)[, lo[, hi]])` Walks a visitor function over the nodes of the tree in order. * `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. * `lo` is an optional start of the range to visit (inclusive) * `hi` is an optional end of the range to visit (non-inclusive) **Returns** The last value returned by the callback ### `tree.root` Returns the root node of the tree ## Node properties Each node of the tree has the following properties: ### `node.key` The key associated to the node ### `node.value` The value associated to the node ### `node.left` The left subtree of the node ### `node.right` The right subtree of the node ## Iterator methods ### `iter.key` The key of the item referenced by the iterator ### `iter.value` The value of the item referenced by the iterator ### `iter.node` The value of the node at the iterator's current position. `null` is iterator is node valid. ### `iter.tree` The tree associated to the iterator ### `iter.index` Returns the position of this iterator in the sequence. ### `iter.valid` Checks if the iterator is valid ### `iter.clone()` Makes a copy of the iterator ### `iter.remove()` Removes the item at the position of the iterator **Returns** A new binary search tree with `iter`'s item removed ### `iter.update(value)` Updates the value of the node in the tree at this iterator **Returns** A new binary search tree with the corresponding node updated ### `iter.next()` Advances the iterator to the next position ### `iter.prev()` Moves the iterator backward one element ### `iter.hasNext` If true, then the iterator is not at the end of the sequence ### `iter.hasPrev` If true, then the iterator is not at the beginning of the sequence # Credits (c) 2013 Mikola Lysenko. MIT License ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` # lodash.merge v4.6.2 The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.merge ``` In Node.js: ```js var merge = require('lodash.merge'); ``` See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/eslint/doctrine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/doctrine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Doctrine Doctrine is a [JSDoc](http://usejsdoc.org) parser that parses documentation comments from JavaScript (you need to pass in the comment, not a whole JavaScript file). ## Installation You can install Doctrine using [npm](https://npmjs.com): ``` $ npm install doctrine --save-dev ``` Doctrine can also be used in web browsers using [Browserify](http://browserify.org). ## Usage Require doctrine inside of your JavaScript: ```js var doctrine = require("doctrine"); ``` ### parse() The primary method is `parse()`, which accepts two arguments: the JSDoc comment to parse and an optional options object. The available options are: * `unwrap` - set to `true` to delete the leading `/**`, any `*` that begins a line, and the trailing `*/` from the source text. Default: `false`. * `tags` - an array of tags to return. When specified, Doctrine returns only tags in this array. For example, if `tags` is `["param"]`, then only `@param` tags will be returned. Default: `null`. * `recoverable` - set to `true` to keep parsing even when syntax errors occur. Default: `false`. * `sloppy` - set to `true` to allow optional parameters to be specified in brackets (`@param {string} [foo]`). Default: `false`. * `lineNumbers` - set to `true` to add `lineNumber` to each node, specifying the line on which the node is found in the source. Default: `false`. * `range` - set to `true` to add `range` to each node, specifying the start and end index of the node in the original comment. Default: `false`. Here's a simple example: ```js var ast = doctrine.parse( [ "/**", " * This function comment is parsed by doctrine", " * @param {{ok:String}} userName", "*/" ].join('\n'), { unwrap: true }); ``` This example returns the following AST: { "description": "This function comment is parsed by doctrine", "tags": [ { "title": "param", "description": null, "type": { "type": "RecordType", "fields": [ { "type": "FieldType", "key": "ok", "value": { "type": "NameExpression", "name": "String" } } ] }, "name": "userName" } ] } See the [demo page](http://eslint.org/doctrine/demo/) more detail. ## Team These folks keep the project moving and are resources for help: * Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) - project lead * Yusuke Suzuki ([@constellation](https://github.com/constellation)) - reviewer ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/doctrine/issues). ## Frequently Asked Questions ### Can I pass a whole JavaScript file to Doctrine? No. Doctrine can only parse JSDoc comments, so you'll need to pass just the JSDoc comment to Doctrine in order to work. ### License #### doctrine Copyright JS Foundation and other contributors, https://js.foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #### esprima some of functions is derived from esprima Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #### closure-compiler some of extensions is derived from closure-compiler Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ ### Where to ask for help? Join our [Chatroom](https://gitter.im/eslint/doctrine) [npm-image]: https://img.shields.io/npm/v/doctrine.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/doctrine [travis-image]: https://img.shields.io/travis/eslint/doctrine/master.svg?style=flat-square [travis-url]: https://travis-ci.org/eslint/doctrine [coveralls-image]: https://img.shields.io/coveralls/eslint/doctrine/master.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/eslint/doctrine?branch=master [downloads-image]: http://img.shields.io/npm/dm/doctrine.svg?style=flat-square [downloads-url]: https://www.npmjs.com/package/doctrine ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. # fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) # rechoir [![Build Status](https://secure.travis-ci.org/tkellen/js-rechoir.png)](http://travis-ci.org/tkellen/js-rechoir) > Require any supported file as a node module. [![NPM](https://nodei.co/npm/rechoir.png)](https://nodei.co/npm/rechoir/) ## What is it? This module, in conjunction with [interpret]-like objects can register any file type the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. ## API ### prepare(config, filepath, requireFrom) Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). `config` An [interpret]-like configuration object. `filepath` A file whose type you'd like to register a module loader for. `requireFrom` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. If calling this method is successful (aka: it doesn't throw), you can now require files of the type you requested natively. An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. If a loader is already registered, this will simply return `true`. **Note:** While rechoir will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. #### Usage ```js const config = require('interpret').extensions; const rechoir = require('rechoir'); rechoir.prepare(config, './test/fixtures/test.coffee'); rechoir.prepare(config, './test/fixtures/test.csv'); rechoir.prepare(config, './test/fixtures/test.toml'); console.log(require('./test/fixtures/test.coffee')); console.log(require('./test/fixtures/test.csv')); console.log(require('./test/fixtures/test.toml')); ``` [interpret]: http://github.com/tkellen/js-interpret [Liftoff]: http://github.com/tkellen/js-liftoff These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ```
kenobijon_registry-near
README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs target .rustc_info.json debug .fingerprint Inflector-e80133f0d873a89e lib-inflector.json ahash-0ea456d44955ceb2 build-script-build-script-build.json ahash-6fc733b0afe6113c lib-ahash.json ahash-75de2a8567409b0a run-build-script-build-script-build.json arrayref-c13f4daf9141ff10 lib-arrayref.json arrayvec-4b25329b5c477333 lib-arrayvec.json arrayvec-5ed8e9a0f838a07f lib-arrayvec.json autocfg-3936825b0293837c lib-autocfg.json base64-0c3f16fadc1da635 lib-base64.json base64-7f77bc7365859151 lib-base64.json bitvec-83ca9af5df3aa113 lib-bitvec.json blake2-1c863c75d1d6b31a lib-blake2.json block-buffer-38700f825239f7bd lib-block-buffer.json block-buffer-a954f756e3b1bcb7 lib-block-buffer.json borsh-986eacda82679337 lib-borsh.json borsh-derive-ff5a595a34d09f30 lib-borsh-derive.json borsh-derive-internal-c2c3bd476929baca lib-borsh-derive-internal.json borsh-schema-derive-internal-3774f5dc58be8529 lib-borsh-schema-derive-internal.json bs58-a1ee981bf5fa2a05 lib-bs58.json byte-slice-cast-e98726a35bb6c61f lib-byte-slice-cast.json byteorder-8a63190df9e3bb15 lib-byteorder.json bytesize-8ae2f8246e0e0087 lib-bytesize.json c2-chacha-316740eec1a0bf3e lib-c2-chacha.json cc-97578d6be55bc3a5 lib-cc.json cfg-if-1cc4882d2e315207 lib-cfg-if.json cfg-if-30d7f2d28beeeb1b lib-cfg-if.json cfg-if-7372481e614c58dd lib-cfg-if.json chrono-39eb6a4c1e498307 lib-chrono.json cipher-79514ce09dd00f63 lib-cipher.json convert_case-5edeb42cc79bfdbf lib-convert_case.json core-foundation-sys-0ae7d9beeb7d3b58 lib-core-foundation-sys.json cpufeatures-0b5950d59b19d08f lib-cpufeatures.json crunchy-0322e332b3ec8289 lib-crunchy.json crunchy-1e4810b237e7579b build-script-build-script-build.json crunchy-6050ff8e1cd01d84 run-build-script-build-script-build.json crypto-common-d3ec57cea1af8de9 lib-crypto-common.json crypto-mac-cc774e3e358255a3 lib-crypto-mac.json curve25519-dalek-e9aa2a6179d49fa6 lib-curve25519-dalek.json derive_more-366fade5ce64d792 lib-derive_more.json digest-aeee431478f452ff lib-digest.json digest-f0cd7cfc841481f7 lib-digest.json dyn-clone-51a073597038c7ce lib-dyn-clone.json easy-ext-7a928631cacd1e93 lib-easy-ext.json ed25519-961d1528f0b9cbc5 lib-ed25519.json ed25519-dalek-58d7a436ab1d6459 lib-ed25519-dalek.json equivalent-6e3def3d9eaeb21e lib-equivalent.json fixed-hash-9f98eda83ed8bb41 lib-fixed-hash.json funty-5c293ef059cd9097 lib-funty.json generic-array-14d371e49e7d702d build-script-build-script-build.json generic-array-46aa735c1d9d8d90 run-build-script-build-script-build.json generic-array-5442b79b9255e92d lib-generic_array.json getrandom-55e1f9759a8ab4b4 lib-getrandom.json getrandom-6a73bb18c9683d61 build-script-build-script-build.json getrandom-8b136a9a485914e1 lib-getrandom.json getrandom-a020d3a53d85421e run-build-script-build-script-build.json hashbrown-5dfac44f6603aecd lib-hashbrown.json hashbrown-f042b77d7b931423 lib-hashbrown.json heck-f53c7857da10975a lib-heck.json hello_near-af336120a3473314 test-lib-hello_near.json hello_near-b32386bdc5efb65e lib-hello_near.json hex-fb12a001e1673ece lib-hex.json iana-time-zone-b0919317c75cf72a lib-iana-time-zone.json impl-codec-446bbf1f44a51baa lib-impl-codec.json impl-trait-for-tuples-bcbfc7c552d4fd88 lib-impl-trait-for-tuples.json indexmap-8142eca295408c05 lib-indexmap.json itoa-ab3c6c4fe96382ee lib-itoa.json keccak-24ff826cafa9499b lib-keccak.json lazy_static-f922ee928b4d529a lib-lazy_static.json libc-1eddc621494ab531 run-build-script-build-script-build.json libc-26eea7aab874018d build-script-build-script-build.json libc-a76246da1ddda7e5 lib-libc.json libc-d568baaf99c503fe build-script-build-script-build.json libc-f8a2f81183a6efe9 run-build-script-build-script-build.json libc-fe3cff9cb64c5b73 lib-libc.json memory_units-65568a0325aa157f lib-memory_units.json near-abi-789f02415127b639 lib-near-abi.json near-account-id-d52375c84163c27a lib-near-account-id.json near-crypto-0d2d2a109ed779be lib-near-crypto.json near-primitives-ace64c6bb40e4baf lib-near-primitives.json near-primitives-core-d856d1e6c33f3646 lib-near-primitives-core.json near-rpc-error-core-faac573db5513450 lib-near-rpc-error-core.json near-rpc-error-macro-6c28ef9898c192f0 lib-near-rpc-error-macro.json near-sdk-048b443888a1a8ce lib-near-sdk.json near-sdk-macros-bc9c2f90641b3e4d lib-near-sdk-macros.json near-sys-fe41686c1c2c82f0 lib-near-sys.json near-vm-errors-fc8ad961408fedb3 lib-near-vm-errors.json near-vm-logic-b0a4c7e30ebcd1fe lib-near-vm-logic.json num-bigint-10cada73a2856123 run-build-script-build-script-build.json num-bigint-ae8b62e375a643e5 lib-num-bigint.json num-bigint-ba46fa44fc1222cd build-script-build-script-build.json num-integer-51afd3190b5476b7 build-script-build-script-build.json num-integer-bc3d41f9e551238c run-build-script-build-script-build.json num-integer-e809a327ef51a2dc lib-num-integer.json num-rational-47ca0984fed0294d build-script-build-script-build.json num-rational-62e125b49c275883 run-build-script-build-script-build.json num-rational-d7b557ef72664e77 lib-num-rational.json num-traits-2f2611516571c0b1 run-build-script-build-script-build.json num-traits-552a91a53cf31010 build-script-build-script-build.json num-traits-dbef2fc3fc372886 lib-num-traits.json once_cell-43a9c7b59790676b lib-once_cell.json once_cell-6c76acca5e158921 lib-once_cell.json opaque-debug-a3337a4b35c8c00e lib-opaque-debug.json parity-scale-codec-8d93a72b8848e743 lib-parity-scale-codec.json parity-scale-codec-derive-3ae7ef36e3076002 lib-parity-scale-codec-derive.json parity-secp256k1-5f5429d8dc31af35 lib-secp256k1.json parity-secp256k1-9c01b2fdc4119051 run-build-script-build-script-build.json parity-secp256k1-df52a0fbbb1147e8 build-script-build-script-build.json ppv-lite86-acd224a756fd208c lib-ppv-lite86.json primitive-types-a7725a944624ab34 lib-primitive-types.json proc-macro-crate-c2d88499128afdb4 lib-proc-macro-crate.json proc-macro-crate-ea3ffa476fa5aec4 lib-proc-macro-crate.json proc-macro2-3c015a460b278a16 lib-proc-macro2.json proc-macro2-90dc97af59964299 build-script-build-script-build.json proc-macro2-fd49a5163e1f2f25 run-build-script-build-script-build.json quote-1add6fd47e9598b5 lib-quote.json radium-6dd089b3862f651e run-build-script-build-script-build.json radium-83d04fdd0665788c lib-radium.json radium-f89e6679aacd06d2 build-script-build-script-build.json rand-9f2e0dd08e49176a lib-rand.json rand-e80bde2727479ac6 lib-rand.json rand_chacha-09939ecc3dca32d0 lib-rand_chacha.json rand_chacha-8cc45feb85a457b3 lib-rand_chacha.json rand_core-4d6a337cea168578 lib-rand_core.json rand_core-a889f9877caa0188 lib-rand_core.json reed-solomon-erasure-88fcd5d11b5cbe2b run-build-script-build-script-build.json reed-solomon-erasure-dd499b2dcc27b68b lib-reed-solomon-erasure.json reed-solomon-erasure-efe9a6831b061980 build-script-build-script-build.json ripemd-e646318a063c8cfe lib-ripemd.json rustc-hex-7cde8fc5dbf5ad74 lib-rustc-hex.json rustversion-33cbd60acc479c1d lib-rustversion.json rustversion-6cde50f3c25402bc run-build-script-build-script-build.json rustversion-d979a190c4096a5f build-script-build-script-build.json ryu-1c1077400d7c556d lib-ryu.json schemars-5c96bb93e1f74f1e build-script-build-script-build.json schemars-69f6519f03f8aaf0 lib-schemars.json schemars-f15a7d493fe677aa run-build-script-build-script-build.json schemars_derive-261f0ce1c668f8ca lib-schemars_derive.json semver-0279b01ae992d068 lib-semver.json semver-18f315fe44c2c281 run-build-script-build-script-build.json semver-a57201e8d0261815 build-script-build-script-build.json serde-02a88de12388d108 run-build-script-build-script-build.json serde-92b092b389162a2f build-script-build-script-build.json serde-b3afd0e9aa9ac879 build-script-build-script-build.json serde-f6ad5173cae16b67 lib-serde.json serde-fbda797e15a9ea67 lib-serde.json serde-fcb012c177d3aa3e run-build-script-build-script-build.json serde_derive-ac1774ae39dae6e5 lib-serde_derive.json serde_derive_internals-832f7e51b9294ed7 lib-serde_derive_internals.json serde_json-29f4b1b4a55019a2 lib-serde_json.json serde_json-46c51fd1ed27e751 build-script-build-script-build.json serde_json-5bf2e87ab678d336 run-build-script-build-script-build.json sha2-106a9250d751237b lib-sha2.json sha2-15c92c16b67c4d0e lib-sha2.json sha3-059caa5150937dc5 lib-sha3.json signature-3b44bc0765318baf lib-signature.json smallvec-0faa8f879102b9bd lib-smallvec.json smart-default-3045d748c3bac74d lib-smart-default.json spin-1eada6c21182491e lib-spin.json static_assertions-a6e951094df62b70 lib-static_assertions.json strum-22910cd43501794c lib-strum.json strum_macros-b271fa7ff7e8072e lib-strum_macros.json subtle-705566a687a5fcaa lib-subtle.json syn-239286cdeabdb889 run-build-script-build-script-build.json syn-3f2b717136c72e7b lib-syn.json syn-7a8dc973d4ce2cb6 build-script-build-script-build.json syn-dcb010de73dd4767 lib-syn.json tap-eaedd486a44964e7 lib-tap.json thiserror-7acf72f94fd8f821 lib-thiserror.json thiserror-832f68b2f0d58241 build-script-build-script-build.json thiserror-f8d51ff79ff81f61 run-build-script-build-script-build.json thiserror-impl-7bb08c953867cdc6 lib-thiserror-impl.json toml-afcd3c1444b02fce lib-toml.json toml_datetime-4a5291c26fbeb8a6 lib-toml_datetime.json toml_edit-be40e56c21b9a462 lib-toml_edit.json typenum-065ba6fa960be3e8 run-build-script-build-script-main.json typenum-3bd5fb5d75e4b054 build-script-build-script-main.json typenum-8517bb9e3d571ddc lib-typenum.json uint-74b740755d5305c5 lib-uint.json unicode-ident-30bffaffa70cce66 lib-unicode-ident.json version_check-9f5b1902f3f8fdcd lib-version_check.json wee_alloc-18c4de30419d0a16 lib-wee_alloc.json wee_alloc-8edfc0e4af906ee2 build-script-build-script-build.json wee_alloc-b939c7b00afe81d3 run-build-script-build-script-build.json winnow-b15b0096472a783e lib-winnow.json wyz-65fe601d21da6e6a lib-wyz.json zeroize-300fff1fd0abe47f lib-zeroize.json zeroize_derive-03bc83de2f553c80 lib-zeroize_derive.json zeropool-bn-d770c8ff38dcb3ac lib-zeropool-bn.json build crunchy-6050ff8e1cd01d84 out lib.rs num-bigint-10cada73a2856123 out radix_bases.rs parity-secp256k1-9c01b2fdc4119051 out flag_check.c reed-solomon-erasure-88fcd5d11b5cbe2b out table.rs thiserror-f8d51ff79ff81f61 out probe.rs typenum-065ba6fa960be3e8 out consts.rs op.rs tests.rs wee_alloc-b939c7b00afe81d3 out wee_alloc_static_array_backend_size_bytes.txt integration-tests Cargo.toml src tests.rs target .rustc_info.json debug .fingerprint addr2line-09d209f8a0c7116f lib-addr2line.json addr2line-1b09017effc27084 lib-addr2line.json adler-66193f2f1cc48360 lib-adler.json adler-98adad4089b45387 lib-adler.json ahash-0ea456d44955ceb2 build-script-build-script-build.json ahash-7297727f0d17d16d lib-ahash.json ahash-75de2a8567409b0a run-build-script-build-script-build.json aho-corasick-27a6c2f321448fc4 lib-aho_corasick.json aho-corasick-2a22e770ebd97f6e lib-aho_corasick.json anyhow-171893a834e5f157 run-build-script-build-script-build.json anyhow-7affaa3019f2b1e7 lib-anyhow.json anyhow-8ae77d3afe84f020 lib-anyhow.json anyhow-b4e6b36fa7b33f22 build-script-build-script-build.json arrayref-c13f4daf9141ff10 lib-arrayref.json arrayvec-a0363d7a81f7012e lib-arrayvec.json arrayvec-f7311df6d8c0337d lib-arrayvec.json async-io-3f47d426c2d4ec1f run-build-script-build-script-build.json async-io-b4eda6772a9edf1a lib-async-io.json async-io-cb7ca3dda8b4ef63 lib-async-io.json async-io-d7932282d5f87a7d build-script-build-script-build.json async-lock-1aff2ee639fac99e lib-async-lock.json async-lock-9986ff35c1233ec1 lib-async-lock.json async-process-5e8cc0c62db5df96 lib-async-process.json async-process-928265985cf32129 lib-async-process.json async-signal-95f737823711f296 lib-async-signal.json async-signal-ed0799f1d5ecbd07 lib-async-signal.json async-trait-3c54476b46102437 lib-async-trait.json async-trait-73f7f51b23ae6040 run-build-script-build-script-build.json async-trait-fc0901c57f3c3a31 build-script-build-script-build.json autocfg-3936825b0293837c lib-autocfg.json backtrace-4c22dc8fbacb9dac build-script-build-script-build.json backtrace-570caee693ce1ba5 lib-backtrace.json backtrace-c0086959cce66653 lib-backtrace.json backtrace-ccb49c2d03b68a74 run-build-script-build-script-build.json base64-3cb722f0485897cb lib-base64.json base64-7f77bc7365859151 lib-base64.json binary-install-0a8838d7be0ad6d5 lib-binary-install.json binary-install-93f6690bfc39d2d8 lib-binary-install.json bitflags-2c23485922337403 lib-bitflags.json bitflags-3f65ee119fe7acb9 lib-bitflags.json bitflags-3fe1f0658207a730 lib-bitflags.json bitflags-a542dd06e64d0ed9 lib-bitflags.json blake2-1c863c75d1d6b31a lib-blake2.json block-buffer-38700f825239f7bd lib-block-buffer.json block-buffer-a954f756e3b1bcb7 lib-block-buffer.json borsh-5deb667d6bb5ebda lib-borsh.json borsh-derive-7a823b099c9ca447 lib-borsh-derive.json borsh-derive-internal-c2c3bd476929baca lib-borsh-derive-internal.json borsh-schema-derive-internal-3774f5dc58be8529 lib-borsh-schema-derive-internal.json bs58-a1ee981bf5fa2a05 lib-bs58.json byteorder-4785c6f785ea5a3f lib-byteorder.json byteorder-8a63190df9e3bb15 lib-byteorder.json bytes-6c1a28f0b45e0573 lib-bytes.json bytesize-8ae2f8246e0e0087 lib-bytesize.json bzip2-51f3d36ace8ce18e lib-bzip2.json bzip2-dba8d6c6263fc71f lib-bzip2.json bzip2-sys-2436a89baf5444a6 lib-bzip2_sys.json bzip2-sys-3dd6514d9b76c746 lib-bzip2_sys.json bzip2-sys-524dbc2548a66b75 build-script-build-script-build.json bzip2-sys-87e77b0f99dd6d89 run-build-script-build-script-build.json c2-chacha-316740eec1a0bf3e lib-c2-chacha.json cc-5cc549118009f3b2 lib-cc.json cfg-if-30d7f2d28beeeb1b lib-cfg-if.json cfg-if-6efb9ad8354586a5 lib-cfg-if.json chrono-490157e8264d68cd lib-chrono.json chrono-b6df2f72a86c0062 lib-chrono.json cipher-79514ce09dd00f63 lib-cipher.json concurrent-queue-b075fafd5e44e77e lib-concurrent-queue.json concurrent-queue-cf53546bac5f1606 lib-concurrent-queue.json convert_case-5edeb42cc79bfdbf lib-convert_case.json core-foundation-f5a25eed7eace731 lib-core-foundation.json core-foundation-sys-0ae7d9beeb7d3b58 lib-core-foundation-sys.json core-foundation-sys-f959c7bc0fbd4cb9 lib-core-foundation-sys.json cpufeatures-5181c62d2d3f6151 lib-cpufeatures.json crc32fast-10a03ee41073431b lib-crc32fast.json crc32fast-17338316b03ecb72 build-script-build-script-build.json crc32fast-782cfa6aad633efc run-build-script-build-script-build.json crc32fast-83d6232eb7aa42a6 lib-crc32fast.json crossbeam-utils-30de5deac3c84127 lib-crossbeam-utils.json crossbeam-utils-3970aafdfe9806f6 run-build-script-build-script-build.json crossbeam-utils-48d4a31a151648f4 build-script-build-script-build.json crossbeam-utils-c42e9f24b2273838 lib-crossbeam-utils.json crunchy-03d172c79f89a522 build-script-build-script-build.json crunchy-8dbbd6b9b02b7472 run-build-script-build-script-build.json crunchy-db16729146e29a71 lib-crunchy.json crypto-common-d3ec57cea1af8de9 lib-crypto-common.json crypto-mac-cc774e3e358255a3 lib-crypto-mac.json curl-40ba13b0ca6126fa run-build-script-build-script-build.json curl-56c57e781911d953 build-script-build-script-build.json curl-b2a723e250c4b0b6 lib-curl.json curl-bb2fa7be3799c9d1 lib-curl.json curl-sys-3e255ae363f9b49d run-build-script-build-script-build.json curl-sys-57f33555b90f36eb build-script-build-script-build.json curl-sys-f1666e88af90730f lib-curl_sys.json curl-sys-f433dc1e1bfd65dc lib-curl_sys.json curve25519-dalek-78dc099d046ce4f0 lib-curve25519-dalek.json derive_more-366fade5ce64d792 lib-derive_more.json digest-aeee431478f452ff lib-digest.json digest-f0cd7cfc841481f7 lib-digest.json dirs-0de53cc529230fbe lib-dirs.json dirs-bca7c4addda5f84c lib-dirs.json dirs-dd884d3cf51d101c lib-dirs.json dirs-sys-ae5a472a87a376ed lib-dirs-sys.json easy-ext-7a928631cacd1e93 lib-easy-ext.json ed25519-961d1528f0b9cbc5 lib-ed25519.json ed25519-dalek-beb28a6eeb34c458 lib-ed25519-dalek.json encoding_rs-07808bd98abcd80f lib-encoding_rs.json errno-d2bfd1ed6e45f8f3 lib-errno.json errno-d307c34a196c877b lib-errno.json event-listener-0c1c94db81dc1475 lib-event-listener.json event-listener-3e834e082d699603 lib-event-listener.json event-listener-8c65207f9da2c717 lib-event-listener.json event-listener-d2cc4070f21411f0 lib-event-listener.json failure-48d9c042690e7d48 lib-failure.json failure-a93645ada495264e lib-failure.json failure_derive-27162696ce339a0a lib-failure_derive.json failure_derive-2dfd370069013b86 build-script-build-script-build.json failure_derive-ed2cc0fe8815306d run-build-script-build-script-build.json fastrand-21945042000b8614 lib-fastrand.json fastrand-61a884ea707936bd lib-fastrand.json fastrand-bb40daf71127f943 lib-fastrand.json filetime-41811d1d14d8249c lib-filetime.json filetime-bd15203fe5698f25 lib-filetime.json fixed-hash-a1bc7c00d0777795 lib-fixed-hash.json flate2-e0d0a492ca16a1d0 lib-flate2.json flate2-f48007ac91c19087 lib-flate2.json fnv-61f369bd67026d2b lib-fnv.json form_urlencoded-a65b8a68e2f826cd lib-form_urlencoded.json fs2-1ea127f5b92d5e25 lib-fs2.json fs2-a1d38e953b75b103 lib-fs2.json futures-channel-70457b04096087ed lib-futures-channel.json futures-channel-8161ece3bff88309 build-script-build-script-build.json futures-channel-b5e74c9a2a8882f4 run-build-script-build-script-build.json futures-core-4880069ce6d7d4fe lib-futures-core.json futures-core-637c51fa7738753a lib-futures-core.json futures-core-7c62d1d43bacbe45 build-script-build-script-build.json futures-core-81425588a6104a34 run-build-script-build-script-build.json futures-io-0fdc36943930b64b lib-futures-io.json futures-io-56451cde08e0ccff lib-futures-io.json futures-lite-10a9a56eca877996 lib-futures-lite.json futures-lite-e458de233cfbd494 lib-futures-lite.json futures-sink-cd7d3aba91022df2 lib-futures-sink.json futures-task-aae8e209a725c401 run-build-script-build-script-build.json futures-task-bcfae45115869535 lib-futures-task.json futures-task-f0f27193821c3471 build-script-build-script-build.json futures-util-05e45ae54b89b7e3 run-build-script-build-script-build.json futures-util-78b02eb4ecd78266 lib-futures-util.json futures-util-af8690ab43e2415f build-script-build-script-build.json generic-array-14d371e49e7d702d build-script-build-script-build.json generic-array-46aa735c1d9d8d90 run-build-script-build-script-build.json generic-array-5442b79b9255e92d lib-generic_array.json getrandom-13040f32b614f666 lib-getrandom.json getrandom-6a73bb18c9683d61 build-script-build-script-build.json getrandom-a020d3a53d85421e run-build-script-build-script-build.json getrandom-bad0b3d2954d8ed6 lib-getrandom.json gimli-46bd364cbae40b89 lib-gimli.json gimli-c277895b178c53db lib-gimli.json h2-ef86309093cb9236 lib-h2.json hashbrown-6fde390b68c63702 lib-hashbrown.json hashbrown-f7f67cefd10efb36 lib-hashbrown.json heck-f53c7857da10975a lib-heck.json hex-1e9d13052eba1fd3 lib-hex.json hex-7014142ddea3146a lib-hex.json hex-fb12a001e1673ece lib-hex.json home-70e79bf1e208cc0a lib-home.json home-dd9a2860658d53c2 lib-home.json http-1f793a6dee31b216 lib-http.json http-body-75ea0168d8b7ed34 lib-http-body.json httparse-5122b3ae9aa0cf66 build-script-build-script-build.json httparse-894fa19cc89748d7 lib-httparse.json httparse-a7971dc50238fa36 run-build-script-build-script-build.json httpdate-98b3c48f29dc69d0 lib-httpdate.json hyper-effc4552d32b0b8a lib-hyper.json hyper-tls-a41d480f4a4c0068 lib-hyper-tls.json iana-time-zone-19761721e85d29ee lib-iana-time-zone.json iana-time-zone-b0919317c75cf72a lib-iana-time-zone.json idna-5a87d3005967055b lib-idna.json indexmap-4ae1151602a0ebfa build-script-build-script-build.json indexmap-ac4d8e3fa78af6be run-build-script-build-script-build.json indexmap-c335e7b46797ce04 lib-indexmap.json integration-tests-fbd58f64eb7d95b6 example-integration-tests.json io-lifetimes-7e241839f3a29465 run-build-script-build-script-build.json io-lifetimes-8dfddc8399044457 build-script-build-script-build.json io-lifetimes-a06b427e993780fa lib-io-lifetimes.json io-lifetimes-cf4e2c13f972a0b5 lib-io-lifetimes.json ipnet-ef1aa033b8b30543 lib-ipnet.json is_executable-8be1ae0c9df28565 lib-is_executable.json is_executable-8e53c7fb157bcf35 lib-is_executable.json itoa-7871e2d45397f5cf lib-itoa.json itoa-ab3c6c4fe96382ee lib-itoa.json lazy_static-09734c73690c4008 lib-lazy_static.json libc-5b6545317c1501e9 run-build-script-build-script-build.json libc-84cb21f021656555 build-script-build-script-build.json libc-95403f559cb4eeec lib-libc.json libc-ae6e44a3800878dc lib-libc.json libz-sys-0032717ab57106b4 build-script-build-script-build.json libz-sys-2aaecf698847294b run-build-script-build-script-build.json libz-sys-4f358d603758efb9 lib-libz-sys.json libz-sys-6f8283a6bc32c4af lib-libz-sys.json lock_api-512d1ab0756e4caa lib-lock_api.json lock_api-5ba4e0227c0d9228 build-script-build-script-build.json lock_api-92a51d0a15e2d4cd run-build-script-build-script-build.json log-190e8fed2c29e177 lib-log.json log-bdf7e85e30027f88 lib-log.json maplit-371a64dd914ac8f0 lib-maplit.json matchers-12f0d1fa1954ad16 lib-matchers.json memchr-abc39b0169cba384 lib-memchr.json memchr-e0ed842de172db88 lib-memchr.json mime-9022810023c94fbd lib-mime.json miniz_oxide-f28fec6f3fb54095 lib-miniz_oxide.json miniz_oxide-f916ceccba1f0e8b lib-miniz_oxide.json mio-146efdd8a345803c lib-mio.json native-tls-2de273d0b20c8e1f run-build-script-build-script-build.json native-tls-30d89ad5a6cdea83 lib-native-tls.json native-tls-ab79808a8da0a2d7 build-script-build-script-build.json near-account-id-c0624beec61c1ac8 lib-near-account-id.json near-chain-configs-1a92b07163ce165b lib-near-chain-configs.json near-crypto-9612ab4ed818e578 lib-near-crypto.json near-jsonrpc-client-62a5a8ffe373b90e lib-near-jsonrpc-client.json near-jsonrpc-primitives-44a9933f6a8c5bef lib-near-jsonrpc-primitives.json near-primitives-0e678eafcc961fd6 lib-near-primitives.json near-primitives-core-9eb4815fa414939b lib-near-primitives-core.json near-rpc-error-core-32b71a8bd2252760 lib-near-rpc-error-core.json near-rpc-error-macro-dfa4e085dc3fccbd lib-near-rpc-error-macro.json near-sandbox-utils-35e1a6dddce64b01 lib-near-sandbox-utils.json near-sandbox-utils-bad4fe0ebdec387e run-build-script-build-script-build.json near-sandbox-utils-c56557d2f45aa0fd lib-near-sandbox-utils.json near-sandbox-utils-e3f5aec3ef3a0c53 build-script-build-script-build.json near-units-31b5edfbc31e7ccc lib-near-units.json near-units-core-3d677e133a19deed lib-near-units-core.json near-units-core-641437c8ac43ad48 lib-near-units-core.json near-units-macro-bd99a1a18cf1b410 lib-near-units-macro.json near-vm-errors-d2c7595e14a682cd lib-near-vm-errors.json nu-ansi-term-601a6a37bdddbd67 lib-nu-ansi-term.json num-bigint-10cada73a2856123 run-build-script-build-script-build.json num-bigint-ae8b62e375a643e5 lib-num-bigint.json num-bigint-ba46fa44fc1222cd build-script-build-script-build.json num-format-16ac9b14c3ef6e54 lib-num-format.json num-format-d8cffd9da8365189 lib-num-format.json num-integer-51afd3190b5476b7 build-script-build-script-build.json num-integer-bc3d41f9e551238c run-build-script-build-script-build.json num-integer-e809a327ef51a2dc lib-num-integer.json num-rational-47ca0984fed0294d build-script-build-script-build.json num-rational-62e125b49c275883 run-build-script-build-script-build.json num-rational-c0a1d53c25a657d8 lib-num-rational.json num-traits-2f2611516571c0b1 run-build-script-build-script-build.json num-traits-552a91a53cf31010 build-script-build-script-build.json num-traits-d713addef3fb9692 lib-num-traits.json num-traits-dbef2fc3fc372886 lib-num-traits.json num_cpus-64434e1181fce881 lib-num_cpus.json object-196531ef6f6e1b95 lib-object.json object-6ec7aae6050d874e lib-object.json once_cell-6c76acca5e158921 lib-once_cell.json opaque-debug-a3337a4b35c8c00e lib-opaque-debug.json overload-7c98fc36f4b035aa lib-overload.json parking-57e857aed025653b lib-parking.json parking-a8e5eaa055bcd914 lib-parking.json parking_lot-73e517f524b8dcd8 lib-parking_lot.json parking_lot_core-1f27d1fdc268bc5a lib-parking_lot_core.json parking_lot_core-d9944f7ec69c6589 run-build-script-build-script-build.json parking_lot_core-df01e200f65e3386 build-script-build-script-build.json percent-encoding-63932c7ed6ed2cc5 lib-percent-encoding.json pin-project-8f48415e57530a66 lib-pin-project.json pin-project-internal-be10519f0b3a6053 lib-pin-project-internal.json pin-project-lite-3ed97e49724750d2 lib-pin-project-lite.json pin-project-lite-763b5e606c0e192d lib-pin-project-lite.json pin-utils-0a5a1ee2f9186e73 lib-pin-utils.json pkg-config-57585fb7da087cf4 lib-pkg-config.json pkg-config-d63d5e5c4a522236 lib-pkg-config.json polling-099667578d3a97e1 lib-polling.json polling-66499ac716320323 lib-polling.json polling-6a94869a402341f1 build-script-build-script-build.json polling-ca9b628a51192cfa run-build-script-build-script-build.json portpicker-c360e3e30347cacf lib-portpicker.json ppv-lite86-acd224a756fd208c lib-ppv-lite86.json primitive-types-8528cd487fb52f5d lib-primitive-types.json proc-macro-crate-63506b0b30873c36 lib-proc-macro-crate.json proc-macro2-3c015a460b278a16 lib-proc-macro2.json proc-macro2-90dc97af59964299 build-script-build-script-build.json proc-macro2-fd49a5163e1f2f25 run-build-script-build-script-build.json quote-1add6fd47e9598b5 lib-quote.json rand-72afd4ae5697fe96 lib-rand.json rand-f83c3e396fadc4e8 lib-rand.json rand_chacha-13096a8e3d5b4a76 lib-rand_chacha.json rand_chacha-737550eb3467f317 lib-rand_chacha.json rand_core-086ba154a627a286 lib-rand_core.json rand_core-8399156137a8bc39 lib-rand_core.json reed-solomon-erasure-88fcd5d11b5cbe2b run-build-script-build-script-build.json reed-solomon-erasure-dd499b2dcc27b68b lib-reed-solomon-erasure.json reed-solomon-erasure-efe9a6831b061980 build-script-build-script-build.json regex-1dc6c85ecdfc4cf3 lib-regex.json regex-9a386c72325f69a4 lib-regex.json regex-automata-17a1c66780e5c98c lib-regex-automata.json regex-automata-f6419ed5daa98680 lib-regex-automata.json regex-automata-fd0551807ba8519f lib-regex-automata.json regex-syntax-4d92745b520fd554 lib-regex-syntax.json regex-syntax-875a33f0211a6ac9 lib-regex-syntax.json regex-syntax-8eaacb2b6bdebdc6 lib-regex-syntax.json reqwest-75df31c1fa7f3160 lib-reqwest.json rustc-demangle-53bc639f98aacbc8 lib-rustc-demangle.json rustc-demangle-9133ab2dd80cfcc5 lib-rustc-demangle.json rustix-22d079b009e9969d lib-rustix.json rustix-577eefd4ba3a628c run-build-script-build-script-build.json rustix-5787e35423e1b70c build-script-build-script-build.json rustix-a06ee1f71de858e7 lib-rustix.json rustix-b104f470ac6e3b2f run-build-script-build-script-build.json rustix-b207555c9289d524 lib-rustix.json rustix-d2c566b0d9f768f5 lib-rustix.json rustix-e54184f81fe0ed4d build-script-build-script-build.json rustversion-33cbd60acc479c1d lib-rustversion.json rustversion-6cde50f3c25402bc run-build-script-build-script-build.json rustversion-d979a190c4096a5f build-script-build-script-build.json ryu-1c1077400d7c556d lib-ryu.json scopeguard-9e31ae53f2ac8a83 lib-scopeguard.json secp256k1-90720495621a3233 lib-secp256k1.json secp256k1-sys-4d32ae82689a15ac run-build-script-build-script-build.json secp256k1-sys-b31692025d1d1a01 lib-secp256k1-sys.json secp256k1-sys-f0c9ab023d7a63b7 build-script-build-script-build.json security-framework-001acf711bb2a3b9 lib-security-framework.json security-framework-sys-4eab8a709cb29542 lib-security-framework-sys.json serde-269369066ff3000c lib-serde.json serde-782e933ebcd7bb8e lib-serde.json serde-92b092b389162a2f build-script-build-script-build.json serde-fcb012c177d3aa3e run-build-script-build-script-build.json serde_derive-f89a81eea1e857ac lib-serde_derive.json serde_json-031d00c9ebbb2bd2 lib-serde_json.json serde_json-7113abaac6277ce6 build-script-build-script-build.json serde_json-743f69c6d02dc6c8 run-build-script-build-script-build.json serde_repr-c0790de684cffb74 lib-serde_repr.json serde_urlencoded-7318ba7cf650710f lib-serde_urlencoded.json sha2-4574d2ba5bde7e0b lib-sha2.json sha2-dc99dc68427479f4 lib-sha2.json sharded-slab-203b99f74188cc56 lib-sharded-slab.json signal-hook-registry-15378868e5521054 lib-signal-hook-registry.json signal-hook-registry-f662ae4821fc1ff9 lib-signal-hook-registry.json signature-3b44bc0765318baf lib-signature.json siphasher-2899cc570f94de75 lib-siphasher.json siphasher-2cf2c88ef1e9ea48 lib-siphasher.json slab-04ef9121e3515b4f run-build-script-build-script-build.json slab-27150bfbc4967107 build-script-build-script-build.json slab-8f3b3b817ca97c63 lib-slab.json slab-fd5a105db9fa21bc lib-slab.json smallvec-0faa8f879102b9bd lib-smallvec.json smart-default-3045d748c3bac74d lib-smart-default.json socket2-193213917883fac1 lib-socket2.json socket2-8d4540446c2bb3fc lib-socket2.json socket2-ea49c1ebbfdd7a5b lib-socket2.json static_assertions-a6e951094df62b70 lib-static_assertions.json strum-22910cd43501794c lib-strum.json strum_macros-b271fa7ff7e8072e lib-strum_macros.json subtle-705566a687a5fcaa lib-subtle.json syn-239286cdeabdb889 run-build-script-build-script-build.json syn-4d2353c8ce2e0cd7 lib-syn.json syn-7a8dc973d4ce2cb6 build-script-build-script-build.json syn-dcb010de73dd4767 lib-syn.json synstructure-87b7b2e1ef3c8c4a lib-synstructure.json system-configuration-cd6362c7637c7617 lib-system-configuration.json system-configuration-sys-18c4a17d2523cb8c lib-system-configuration-sys.json system-configuration-sys-44e325252211ea5e run-build-script-build-script-build.json system-configuration-sys-97710620b210acd5 build-script-build-script-build.json tar-5b76c2c75a96c2c4 lib-tar.json tar-f58c2d3383aa0857 lib-tar.json tempfile-baa2a79b79e82542 lib-tempfile.json thiserror-832f68b2f0d58241 build-script-build-script-build.json thiserror-8416d372e0621d65 lib-thiserror.json thiserror-c777705c5e2e5296 lib-thiserror.json thiserror-f8d51ff79ff81f61 run-build-script-build-script-build.json thiserror-impl-99255312819ecb77 lib-thiserror-impl.json thread_local-8d761a08dac7ddf2 lib-thread_local.json time-250a60fa16a12611 lib-time.json time-d6e02bed319f790e lib-time.json tinyvec-797be810e63f83dd lib-tinyvec.json tinyvec_macros-b2dbe02aa2b4a810 lib-tinyvec_macros.json tokio-0c6ffefb2f2764a8 lib-tokio.json tokio-macros-76b2cb20497a0961 lib-tokio-macros.json tokio-native-tls-a78b739d890ca533 lib-tokio-native-tls.json tokio-retry-acacf0675e4930ab lib-tokio-retry.json tokio-util-01198b14c8e0975f lib-tokio-util.json toml-237e325ebdd3d1e6 lib-toml.json tower-service-0e67c1e9ceaf62ca lib-tower-service.json tracing-772fc166ba34ce8c lib-tracing.json tracing-attributes-001461bd488d9fdd lib-tracing-attributes.json tracing-core-aaa1c885b294f2e2 lib-tracing-core.json tracing-log-df1c2b7e0f6f2d9d lib-tracing-log.json tracing-subscriber-6843cf65a430fb07 lib-tracing-subscriber.json try-lock-8993eefa2d7dc67c lib-try-lock.json typenum-065ba6fa960be3e8 run-build-script-build-script-main.json typenum-3bd5fb5d75e4b054 build-script-build-script-main.json typenum-8517bb9e3d571ddc lib-typenum.json uint-c25699c51b6c3510 lib-uint.json unicode-bidi-2a96523614cdb056 lib-unicode_bidi.json unicode-ident-30bffaffa70cce66 lib-unicode-ident.json unicode-normalization-110710aee3b827eb lib-unicode-normalization.json unicode-xid-067c8bb269fa28cf lib-unicode-xid.json url-f6a968cc22d14169 lib-url.json uuid-1a0512e140f8a47e lib-uuid.json vcpkg-afc73e63fa216afe lib-vcpkg.json version_check-9f5b1902f3f8fdcd lib-version_check.json waker-fn-989faf0c35a0c30e lib-waker-fn.json waker-fn-cbd6a43820fd1a6f lib-waker-fn.json want-0643e58b9a050f95 lib-want.json workspaces-58eb0bbaaa7c68c9 lib-workspaces.json workspaces-b0b98a1254651d40 run-build-script-build-script-build.json workspaces-ecc167a1c98d946f build-script-build-script-build.json xattr-9dc79ff463f41377 lib-xattr.json xattr-a6fddaa8980b51b4 lib-xattr.json zeroize-46e62f55d134f258 lib-zeroize.json zeroize_derive-3709f3874cfbb7ec lib-zeroize_derive.json zip-3178d240baa343c7 lib-zip.json zip-d7159f5f01b45bac lib-zip.json build anyhow-171893a834e5f157 out probe.rs bzip2-sys-87e77b0f99dd6d89 out include bzlib.h crunchy-8dbbd6b9b02b7472 out lib.rs num-bigint-10cada73a2856123 out radix_bases.rs reed-solomon-erasure-88fcd5d11b5cbe2b out table.rs secp256k1-sys-4d32ae82689a15ac out flag_check.c thiserror-f8d51ff79ff81f61 out probe.rs typenum-065ba6fa960be3e8 out consts.rs op.rs tests.rs Public header file for the library. bzlib.h end bzlib.h package-lock.json package.json rust-toolchain.toml
# Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. registry-near ================== This app was initialized with [create-near-app]
levalleux-ludo_near.decentradocs
.eslintrc.js .gitpod.yml .travis.yml README.md as-pect.config.js asconfig.js assembly __tests__ as-pect.d.ts dvsRegistry.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.js gulpfile.js neardev default dev-1582817300252.json shared-test-staging test.near.json shared-test test.near.json package.json src App.js config.js index.html index.js tests integration App-integration.test.js ui App-ui.test.js ubuntu Launch.cmd build.cmd
Guest Book ========== [![Build Status](https://travis-ci.com/near-examples/guest-book.svg?branch=master)](https://travis-ci.com/near-examples/guest-book) [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/guest-book) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend. Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you have node.js installed (we like [asdf] for this), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`) 2. Install dependencies: `yarn install` (or just `yarn`) 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app. Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html] is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-shell -------------------------- You need near-shell installed globally. Here's how: npm install --global near-shell This will give you the `near` [CLI] tool. Ensure that it's installed with: near --version Step 1: Create an account for the contract ------------------------------------------ Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account. Now authorize NEAR shell for this new account, and follow the instructions it gives you: near login Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contracts to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. [NEAR]: https://nearprotocol.com/ [asdf]: https://github.com/asdf-vm/asdf [yarn]: https://yarnpkg.com/ [AssemblyScript]: https://docs.assemblyscript.org/ [React]: https://reactjs.org [smart contract docs]: https://docs.nearprotocol.com/docs/roles/developer/contracts/assemblyscript [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.nearprotocol.com/docs/concepts/account [NEAR Wallet]: https://wallet.nearprotocol.com [near-shell]: https://github.com/nearprotocol/near-shell [CLI]: https://www.w3schools.com/whatis/whatis_cli.asp [create-near-app]: https://github.com/nearprotocol/create-near-app [gh-pages]: https://github.com/tschaub/gh-pages
near_social-docs
.github workflows build.yml links.yml spellcheck.yml README.md babel.config.js docs discovery api cache.md clipboard.md fetch.md home.md near.md primitives.md social.md state.md storage.md components files.md home.md infiniteScroll.md ipfsimageupload.md markdown.md overlayTrigger.md styledComponents.md tooltip.md typeahead.md widget.md home.md index.md social contract.md home.md standards.md tech.md tutorial hello-near.md quickstart.md | docusaurus.config.js mlc_config.json package.json plugins monaco-editor index.js sidebars.js src components social-widget.js css custom.css theme Root.js static img logo.svg logo_dark.svg index.html
# Website This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. ### Installation ``` $ yarn ``` ### Local Development ``` $ yarn start ``` This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. ### Build ``` $ yarn build ``` This command generates static content into the `build` directory and can be served using any static contents hosting service. ### Deployment Using SSH: ``` $ USE_SSH=true yarn deploy ``` Not using SSH: ``` $ GIT_USER=<Your GitHub username> yarn deploy ``` If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
jesus13th_NearGames
README.md as-pect.config.js asconfig.json assembly Models.ts __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js neardev dev-account.env node_modules .bin acorn.cmd acorn.ps1 asb.cmd asb.ps1 asbuild.cmd asbuild.ps1 asc.cmd asc.ps1 asinit.cmd asinit.ps1 asp.cmd asp.ps1 aspect.cmd aspect.ps1 assemblyscript-build.cmd assemblyscript-build.ps1 eslint.cmd eslint.ps1 esparse.cmd esparse.ps1 esvalidate.cmd esvalidate.ps1 js-yaml.cmd js-yaml.ps1 mkdirp.cmd mkdirp.ps1 near-vm-as.cmd near-vm-as.ps1 near-vm.cmd near-vm.ps1 nearley-railroad.cmd nearley-railroad.ps1 nearley-test.cmd nearley-test.ps1 nearley-unparse.cmd nearley-unparse.ps1 nearleyc.cmd nearleyc.ps1 node-which.cmd node-which.ps1 resolve.cmd resolve.ps1 rimraf.cmd rimraf.ps1 semver.cmd semver.ps1 shjs.cmd shjs.ps1 wasm-opt.cmd wasm-opt.ps1 .package-lock.json @as-covers assembly CONTRIBUTING.md README.md index.ts package.json tsconfig.json core CONTRIBUTING.md README.md package.json glue README.md lib index.d.ts index.js package.json transform README.md lib index.d.ts index.js util.d.ts util.js node_modules visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js toString.d.ts toString.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformRange.d.ts transformRange.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json package.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @eslint eslintrc CHANGELOG.md README.md conf config-schema.js environments.js eslint-all.js eslint-recommended.js lib cascading-config-array-factory.js config-array-factory.js config-array config-array.js config-dependency.js extracted-config.js ignore-pattern.js index.js override-tester.js flat-compat.js index.js shared ajv.js config-ops.js config-validator.js deprecation-warnings.js naming.js relative-module-resolver.js types.js package.json @humanwhocodes config-array README.md api.js package.json object-schema .eslintrc.js .github workflows nodejs-test.yml release-please.yml CHANGELOG.md README.md package.json src index.js merge-strategy.js object-schema.js validation-strategy.js tests merge-strategy.js object-schema.js validation-strategy.js acorn-jsx README.md index.d.ts index.js package.json xhtml.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json as-bignum README.md assembly __tests__ as-pect.d.ts i128.spec.as.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts package.json asbuild README.md dist cli.d.ts cli.js commands build.d.ts build.js fmt.d.ts fmt.js index.d.ts index.js init cmd.d.ts cmd.js files asconfigJson.d.ts asconfigJson.js aspecConfig.d.ts aspecConfig.js assembly_files.d.ts assembly_files.js eslintConfig.d.ts eslintConfig.js gitignores.d.ts gitignores.js index.d.ts index.js indexJs.d.ts indexJs.js packageJson.d.ts packageJson.js test_files.d.ts test_files.js index.d.ts index.js interfaces.d.ts interfaces.js run.d.ts run.js test.d.ts test.js index.d.ts index.js main.d.ts main.js utils.d.ts utils.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json assemblyscript-json .eslintrc.js .travis.yml README.md assembly JSON.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json temp-docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md assemblyscript-regex .eslintrc.js .github workflows benchmark.yml release.yml test.yml README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __spec_tests__ generated.spec.ts __tests__ alterations.spec.ts as-pect.d.ts boundary-assertions.spec.ts capture-group.spec.ts character-classes.spec.ts character-sets.spec.ts characters.ts empty.ts quantifiers.spec.ts range-quantifiers.spec.ts regex.spec.ts utils.ts char.ts env.ts index.ts nfa matcher.ts nfa.ts types.ts walker.ts parser node.ts parser.ts string-iterator.ts walker.ts regexp.ts tsconfig.json util.ts benchmark benchmark.js package.json spec test-generator.js ts index.ts tsconfig.json assemblyscript-temporal .github workflows node.js.yml release.yml .vscode launch.json README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __tests__ README.md as-pect.d.ts date.spec.ts duration.spec.ts empty.ts plaindate.spec.ts plaindatetime.spec.ts plainmonthday.spec.ts plaintime.spec.ts plainyearmonth.spec.ts timezone.spec.ts zoneddatetime.spec.ts constants.ts date.ts duration.ts enums.ts env.ts index.ts instant.ts now.ts plaindate.ts plaindatetime.ts plainmonthday.ts plaintime.ts plainyearmonth.ts timezone.ts tsconfig.json tz __tests__ index.spec.ts rule.spec.ts zone.spec.ts iana.ts index.ts rule.ts zone.ts utils.ts zoneddatetime.ts development.md package.json tzdb README.md iana theory.html zoneinfo2tdf.pl assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md bin rtplot.js index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json astral-regex index.d.ts index.js package.json readme.md axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js CHANGELOG.md README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json csv-stringify README.md lib browser index.js sync.js es5 index.d.ts index.js sync.d.ts sync.js index.d.ts index.js sync.d.ts sync.js package.json debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js diff CONTRIBUTING.md README.md dist diff.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js doctrine CHANGELOG.md README.md lib doctrine.js typed.js utility.js package.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js enquirer CHANGELOG.md README.md index.d.ts index.js lib ansi.js combos.js completer.js interpolate.js keypress.js placeholder.js prompt.js prompts autocomplete.js basicauth.js confirm.js editable.js form.js index.js input.js invisible.js list.js multiselect.js numeral.js password.js quiz.js scale.js select.js snippet.js sort.js survey.js text.js toggle.js render.js roles.js state.js styles.js symbols.js theme.js timer.js types array.js auth.js boolean.js index.js number.js string.js utils.js package.json env-paths index.d.ts index.js package.json readme.md escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js package.json eslint-utils README.md index.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json eslint CHANGELOG.md README.md bin eslint.js conf category-list.json config-schema.js default-cli-options.js eslint-all.js eslint-recommended.js replacements.json lib api.js cli-engine cli-engine.js file-enumerator.js formatters checkstyle.js codeframe.js compact.js html.js jslint-xml.js json-with-metadata.js json.js junit.js stylish.js table.js tap.js unix.js visualstudio.js hash.js index.js lint-result-cache.js load-rules.js xml-escape.js cli.js config default-config.js flat-config-array.js flat-config-schema.js rule-validator.js eslint eslint.js index.js init autoconfig.js config-file.js config-initializer.js config-rule.js npm-utils.js source-code-utils.js linter apply-disable-directives.js code-path-analysis code-path-analyzer.js code-path-segment.js code-path-state.js code-path.js debug-helpers.js fork-context.js id-generator.js config-comment-parser.js index.js interpolate.js linter.js node-event-generator.js report-translator.js rule-fixer.js rules.js safe-emitter.js source-code-fixer.js timing.js options.js rule-tester index.js rule-tester.js rules accessor-pairs.js array-bracket-newline.js array-bracket-spacing.js array-callback-return.js array-element-newline.js arrow-body-style.js arrow-parens.js arrow-spacing.js block-scoped-var.js block-spacing.js brace-style.js callback-return.js camelcase.js capitalized-comments.js class-methods-use-this.js comma-dangle.js comma-spacing.js comma-style.js complexity.js computed-property-spacing.js consistent-return.js consistent-this.js constructor-super.js curly.js default-case-last.js default-case.js default-param-last.js dot-location.js dot-notation.js eol-last.js eqeqeq.js for-direction.js func-call-spacing.js func-name-matching.js func-names.js func-style.js function-call-argument-newline.js function-paren-newline.js generator-star-spacing.js getter-return.js global-require.js grouped-accessor-pairs.js guard-for-in.js handle-callback-err.js id-blacklist.js id-denylist.js id-length.js id-match.js implicit-arrow-linebreak.js indent-legacy.js indent.js index.js init-declarations.js jsx-quotes.js key-spacing.js keyword-spacing.js line-comment-position.js linebreak-style.js lines-around-comment.js lines-around-directive.js lines-between-class-members.js max-classes-per-file.js max-depth.js max-len.js max-lines-per-function.js max-lines.js max-nested-callbacks.js max-params.js max-statements-per-line.js max-statements.js multiline-comment-style.js multiline-ternary.js new-cap.js new-parens.js newline-after-var.js newline-before-return.js newline-per-chained-call.js no-alert.js no-array-constructor.js no-async-promise-executor.js no-await-in-loop.js no-bitwise.js no-buffer-constructor.js no-caller.js no-case-declarations.js no-catch-shadow.js no-class-assign.js no-compare-neg-zero.js no-cond-assign.js no-confusing-arrow.js no-console.js no-const-assign.js no-constant-condition.js no-constructor-return.js no-continue.js no-control-regex.js no-debugger.js no-delete-var.js no-div-regex.js no-dupe-args.js no-dupe-class-members.js no-dupe-else-if.js no-dupe-keys.js no-duplicate-case.js no-duplicate-imports.js no-else-return.js no-empty-character-class.js no-empty-function.js no-empty-pattern.js no-empty.js no-eq-null.js no-eval.js no-ex-assign.js no-extend-native.js no-extra-bind.js no-extra-boolean-cast.js no-extra-label.js no-extra-parens.js no-extra-semi.js no-fallthrough.js no-floating-decimal.js no-func-assign.js no-global-assign.js no-implicit-coercion.js no-implicit-globals.js no-implied-eval.js no-import-assign.js no-inline-comments.js no-inner-declarations.js no-invalid-regexp.js no-invalid-this.js no-irregular-whitespace.js no-iterator.js no-label-var.js no-labels.js no-lone-blocks.js no-lonely-if.js no-loop-func.js no-loss-of-precision.js no-magic-numbers.js no-misleading-character-class.js no-mixed-operators.js no-mixed-requires.js no-mixed-spaces-and-tabs.js no-multi-assign.js no-multi-spaces.js no-multi-str.js no-multiple-empty-lines.js no-native-reassign.js no-negated-condition.js no-negated-in-lhs.js no-nested-ternary.js no-new-func.js no-new-object.js no-new-require.js no-new-symbol.js no-new-wrappers.js no-new.js no-nonoctal-decimal-escape.js no-obj-calls.js no-octal-escape.js no-octal.js no-param-reassign.js no-path-concat.js no-plusplus.js no-process-env.js no-process-exit.js no-promise-executor-return.js no-proto.js no-prototype-builtins.js no-redeclare.js no-regex-spaces.js no-restricted-exports.js no-restricted-globals.js no-restricted-imports.js no-restricted-modules.js no-restricted-properties.js no-restricted-syntax.js no-return-assign.js no-return-await.js no-script-url.js no-self-assign.js no-self-compare.js no-sequences.js no-setter-return.js no-shadow-restricted-names.js no-shadow.js no-spaced-func.js no-sparse-arrays.js no-sync.js no-tabs.js no-template-curly-in-string.js no-ternary.js no-this-before-super.js no-throw-literal.js no-trailing-spaces.js no-undef-init.js no-undef.js no-undefined.js no-underscore-dangle.js no-unexpected-multiline.js no-unmodified-loop-condition.js no-unneeded-ternary.js no-unreachable-loop.js no-unreachable.js no-unsafe-finally.js no-unsafe-negation.js no-unsafe-optional-chaining.js no-unused-expressions.js no-unused-labels.js no-unused-vars.js no-use-before-define.js no-useless-backreference.js no-useless-call.js no-useless-catch.js no-useless-computed-key.js no-useless-concat.js no-useless-constructor.js no-useless-escape.js no-useless-rename.js no-useless-return.js no-var.js no-void.js no-warning-comments.js no-whitespace-before-property.js no-with.js nonblock-statement-body-position.js object-curly-newline.js object-curly-spacing.js object-property-newline.js object-shorthand.js one-var-declaration-per-line.js one-var.js operator-assignment.js operator-linebreak.js padded-blocks.js padding-line-between-statements.js prefer-arrow-callback.js prefer-const.js prefer-destructuring.js prefer-exponentiation-operator.js prefer-named-capture-group.js prefer-numeric-literals.js prefer-object-spread.js prefer-promise-reject-errors.js prefer-reflect.js prefer-regex-literals.js prefer-rest-params.js prefer-spread.js prefer-template.js quote-props.js quotes.js radix.js require-atomic-updates.js require-await.js require-jsdoc.js require-unicode-regexp.js require-yield.js rest-spread-spacing.js semi-spacing.js semi-style.js semi.js sort-imports.js sort-keys.js sort-vars.js space-before-blocks.js space-before-function-paren.js space-in-parens.js space-infix-ops.js space-unary-ops.js spaced-comment.js strict.js switch-colon-spacing.js symbol-description.js template-curly-spacing.js template-tag-spacing.js unicode-bom.js use-isnan.js utils ast-utils.js fix-tracker.js keywords.js lazy-loading-rule-map.js patterns letters.js unicode index.js is-combining-character.js is-emoji-modifier.js is-regional-indicator-symbol.js is-surrogate-pair.js valid-jsdoc.js valid-typeof.js vars-on-top.js wrap-iife.js wrap-regex.js yield-star-spacing.js yoda.js shared ajv.js ast-utils.js config-validator.js deprecation-warnings.js logging.js relative-module-resolver.js runtime-info.js string-utils.js traverser.js types.js source-code index.js source-code.js token-store backward-token-comment-cursor.js backward-token-cursor.js cursor.js cursors.js decorative-cursor.js filter-cursor.js forward-token-comment-cursor.js forward-token-cursor.js index.js limit-cursor.js padded-token-cursor.js skip-cursor.js utils.js messages all-files-ignored.js extend-config-missing.js failed-to-read-json.js file-not-found.js no-config-found.js plugin-conflict.js plugin-invalid.js plugin-missing.js print-config-with-directory-path.js whitespace-found.js package.json espree CHANGELOG.md README.md espree.js lib ast-node-types.js espree.js features.js options.js token-translator.js visitor-keys.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esquery README.md dist esquery.esm.js esquery.esm.min.js esquery.js esquery.lite.js esquery.lite.min.js esquery.min.js license.txt node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json parser.js esrecurse README.md esrecurse.js gulpfile.babel.js node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json estraverse README.md estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-deep-equal README.md es6 index.d.ts index.js react.d.ts react.js index.d.ts index.js package.json react.d.ts react.js fast-json-stable-stringify .eslintrc.yml .github FUNDING.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.d.ts index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json file-entry-cache README.md cache.js changelog.md package.json find-up index.d.ts index.js package.json readme.md flat-cache README.md changelog.md package.json src cache.js del.js utils.js flatted .github FUNDING.yml workflows node.js.yml README.md SPECS.md cjs index.js package.json es.js esm index.js index.js min.js package.json php flatted.php types.d.ts follow-redirects README.md http.js https.js index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js ms index.js license.md package.json readme.md package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js functional-red-black-tree README.md bench test.js package.json rbtree.js test test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globals globals.json index.d.ts index.js package.json readme.md has-flag index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hasurl README.md index.js package.json ignore CHANGELOG.md README.md index.d.ts index.js legacy.js package.json import-fresh index.d.ts index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json interpret README.md index.js mjs-stub.js package.json is-core-module CHANGELOG.md README.md core.json index.js package.json test index.js is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.js package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json js-tokens CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-stable-stringify-without-jsonify .travis.yml example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js replacer.js space.js str.js to-json.js levn README.md lib cast.js index.js parse-string.js package.json line-column README.md lib line-column.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.merge README.md index.js package.json lodash.sortby README.md index.js package.json lodash.truncate README.md index.js package.json long README.md dist long.js index.js package.json src long.js lru-cache README.md index.js package.json minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md natural-compare README.md index.js package.json near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt empty.ts generic.ts includeBytes.spec.ts main.ts max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts json.lib.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts maxHeap.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts datetime.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ empty.ts exportAs.ts model.ts sentences.ts singleton copy.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md parent-module index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-key index.d.ts index.js package.json readme.md path-parse README.md index.js package.json prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json rechoir .travis.yml README.md index.js lib extension.js normalize.js register.js package.json regexpp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json require-from-string index.js package.json readme.md require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve-from index.js package.json readme.md resolve .github FUNDING.yml SECURITY.md appveyor.yml async.js example async.js sync.js index.js lib async.js caller.js core.js core.json homedir.js is-core.js node-modules-paths.js normalize-options.js sync.js package.json sync.js test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js home_paths.js home_paths_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json malformed_package_json index.js package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json semver CHANGELOG.md README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md shelljs CHANGELOG.md README.md commands.js global.js make.js package.json plugin.js shell.js src cat.js cd.js chmod.js common.js cp.js dirs.js echo.js error.js exec-child.js exec.js find.js grep.js head.js ln.js ls.js mkdir.js mv.js popd.js pushd.js pwd.js rm.js sed.js set.js sort.js tail.js tempdir.js test.js to.js toEnd.js touch.js uniq.js which.js slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md supports-preserve-symlinks-flag .github FUNDING.yml CHANGELOG.md README.md browser.js index.js package.json test index.js table README.md dist src alignSpanningCell.d.ts alignSpanningCell.js alignString.d.ts alignString.js alignTableData.d.ts alignTableData.js calculateCellHeight.d.ts calculateCellHeight.js calculateMaximumColumnWidths.d.ts calculateMaximumColumnWidths.js calculateOutputColumnWidths.d.ts calculateOutputColumnWidths.js calculateRowHeights.d.ts calculateRowHeights.js calculateSpanningCellWidth.d.ts calculateSpanningCellWidth.js createStream.d.ts createStream.js drawBorder.d.ts drawBorder.js drawContent.d.ts drawContent.js drawRow.d.ts drawRow.js drawTable.d.ts drawTable.js generated validators.d.ts validators.js getBorderCharacters.d.ts getBorderCharacters.js index.d.ts index.js injectHeaderConfig.d.ts injectHeaderConfig.js makeRangeConfig.d.ts makeRangeConfig.js makeStreamConfig.d.ts makeStreamConfig.js makeTableConfig.d.ts makeTableConfig.js mapDataUsingRowHeights.d.ts mapDataUsingRowHeights.js padTableData.d.ts padTableData.js schemas config.json shared.json streamConfig.json spanningCellManager.d.ts spanningCellManager.js stringifyTableData.d.ts stringifyTableData.js table.d.ts table.js truncateTableData.d.ts truncateTableData.js types api.d.ts api.js internal.d.ts internal.js utils.d.ts utils.js validateConfig.d.ts validateConfig.js validateSpanningCellConfig.d.ts validateSpanningCellConfig.js validateTableData.d.ts validateTableData.js wrapCell.d.ts wrapCell.js wrapString.d.ts wrapString.js wrapWord.d.ts wrapWord.js node_modules ajv .runkit_example.js README.md dist 2019.d.ts 2019.js 2020.d.ts 2020.js ajv.d.ts ajv.js compile codegen code.d.ts code.js index.d.ts index.js scope.d.ts scope.js errors.d.ts errors.js index.d.ts index.js jtd parse.d.ts parse.js serialize.d.ts serialize.js types.d.ts types.js names.d.ts names.js ref_error.d.ts ref_error.js resolve.d.ts resolve.js rules.d.ts rules.js util.d.ts util.js validate applicability.d.ts applicability.js boolSchema.d.ts boolSchema.js dataType.d.ts dataType.js defaults.d.ts defaults.js index.d.ts index.js keyword.d.ts keyword.js subschema.d.ts subschema.js core.d.ts core.js jtd.d.ts jtd.js refs data.json json-schema-2019-09 index.d.ts index.js meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.d.ts index.js meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.d.ts jtd-schema.js runtime equal.d.ts equal.js parseJson.d.ts parseJson.js quote.d.ts quote.js re2.d.ts re2.js timestamp.d.ts timestamp.js ucs2length.d.ts ucs2length.js uri.d.ts uri.js validation_error.d.ts validation_error.js standalone index.d.ts index.js instance.d.ts instance.js types index.d.ts index.js json-schema.d.ts json-schema.js jtd-schema.d.ts jtd-schema.js vocabularies applicator additionalItems.d.ts additionalItems.js additionalProperties.d.ts additionalProperties.js allOf.d.ts allOf.js anyOf.d.ts anyOf.js contains.d.ts contains.js dependencies.d.ts dependencies.js dependentSchemas.d.ts dependentSchemas.js if.d.ts if.js index.d.ts index.js items.d.ts items.js items2020.d.ts items2020.js not.d.ts not.js oneOf.d.ts oneOf.js patternProperties.d.ts patternProperties.js prefixItems.d.ts prefixItems.js properties.d.ts properties.js propertyNames.d.ts propertyNames.js thenElse.d.ts thenElse.js code.d.ts code.js core id.d.ts id.js index.d.ts index.js ref.d.ts ref.js discriminator index.d.ts index.js types.d.ts types.js draft2020.d.ts draft2020.js draft7.d.ts draft7.js dynamic dynamicAnchor.d.ts dynamicAnchor.js dynamicRef.d.ts dynamicRef.js index.d.ts index.js recursiveAnchor.d.ts recursiveAnchor.js recursiveRef.d.ts recursiveRef.js errors.d.ts errors.js format format.d.ts format.js index.d.ts index.js jtd discriminator.d.ts discriminator.js elements.d.ts elements.js enum.d.ts enum.js error.d.ts error.js index.d.ts index.js metadata.d.ts metadata.js nullable.d.ts nullable.js optionalProperties.d.ts optionalProperties.js properties.d.ts properties.js ref.d.ts ref.js type.d.ts type.js union.d.ts union.js values.d.ts values.js metadata.d.ts metadata.js next.d.ts next.js unevaluated index.d.ts index.js unevaluatedItems.d.ts unevaluatedItems.js unevaluatedProperties.d.ts unevaluatedProperties.js validation const.d.ts const.js dependentRequired.d.ts dependentRequired.js enum.d.ts enum.js index.d.ts index.js limitContains.d.ts limitContains.js limitItems.d.ts limitItems.js limitLength.d.ts limitLength.js limitNumber.d.ts limitNumber.js limitProperties.d.ts limitProperties.js multipleOf.d.ts multipleOf.js pattern.d.ts pattern.js required.d.ts required.js uniqueItems.d.ts uniqueItems.js lib 2019.ts 2020.ts ajv.ts compile codegen code.ts index.ts scope.ts errors.ts index.ts jtd parse.ts serialize.ts types.ts names.ts ref_error.ts resolve.ts rules.ts util.ts validate applicability.ts boolSchema.ts dataType.ts defaults.ts index.ts keyword.ts subschema.ts core.ts jtd.ts refs data.json json-schema-2019-09 index.ts meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.ts meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.ts runtime equal.ts parseJson.ts quote.ts re2.ts timestamp.ts ucs2length.ts uri.ts validation_error.ts standalone index.ts instance.ts types index.ts json-schema.ts jtd-schema.ts vocabularies applicator additionalItems.ts additionalProperties.ts allOf.ts anyOf.ts contains.ts dependencies.ts dependentSchemas.ts if.ts index.ts items.ts items2020.ts not.ts oneOf.ts patternProperties.ts prefixItems.ts properties.ts propertyNames.ts thenElse.ts code.ts core id.ts index.ts ref.ts discriminator index.ts types.ts draft2020.ts draft7.ts dynamic dynamicAnchor.ts dynamicRef.ts index.ts recursiveAnchor.ts recursiveRef.ts errors.ts format format.ts index.ts jtd discriminator.ts elements.ts enum.ts error.ts index.ts metadata.ts nullable.ts optionalProperties.ts properties.ts ref.ts type.ts union.ts values.ts metadata.ts next.ts unevaluated index.ts unevaluatedItems.ts unevaluatedProperties.ts validation const.ts dependentRequired.ts enum.ts index.ts limitContains.ts limitItems.ts limitLength.ts limitNumber.ts limitProperties.ts multipleOf.ts pattern.ts required.ts uniqueItems.ts package.json json-schema-traverse .eslintrc.yml .github FUNDING.yml workflows build.yml publish.yml README.md index.d.ts index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json text-table .travis.yml example align.js center.js dotalign.js doubledot.js table.js index.js package.json test align.js ansi-colors.js center.js dotalign.js doubledot.js table.js tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json type-check README.md lib check.js index.js parse-type.js package.json type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts universal-url README.md browser.js index.js package.json uri-js README.md dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js ws.d.ts ws.js wss.d.ts wss.js uri.d.ts uri.js util.d.ts util.js package.json v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js word-wrap README.md index.d.ts index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json | features not yet implemented issues with the tests differences between PCRE and JS regex | | | package-lock.json package.json
# AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` # fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>. See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. You can install via npm `npm install prelude-ls` ### Development `make test` to test `make build` to build `lib` from `src` `make build-browser` to build browser versions discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` # file-entry-cache > Super simple cache for file metadata, useful for process that work o a given series of files > and that only need to repeat the job on the changed ones since the previous run of the process — Edit [![NPM Version](http://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) [![Build Status](http://img.shields.io/travis/royriojas/file-entry-cache.svg?style=flat)](https://travis-ci.org/royriojas/file-entry-cache) ## install ```bash npm i --save file-entry-cache ``` ## Usage The module exposes two functions `create` and `createFromFile`. ## `create(cacheName, [directory, useCheckSum])` - **cacheName**: the name of the cache to be created - **directory**: Optional the directory to load the cache from - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ## `createFromFile(pathToCache, [useCheckSum])` - **pathToCache**: the path to the cache file (this combines the cache name and directory) - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ```js // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var fileEntryCache = require('file-entry-cache'); var cache = fileEntryCache.create('testCache'); var files = expand('../fixtures/*.txt'); // the first time this method is called, will return all the files var oFiles = cache.getUpdatedFiles(files); // this will persist this to disk checking each file stats and // updating the meta attributes `size` and `mtime`. // custom fields could also be added to the meta object and will be persisted // in order to retrieve them later cache.reconcile(); // use this if you want the non visited file entries to be kept in the cache // for more than one execution // // cache.reconcile( true /* noPrune */) // on a second run var cache2 = fileEntryCache.create('testCache'); // will return now only the files that were modified or none // if no files were modified previous to the execution of this function var oFiles = cache.getUpdatedFiles(files); // if you want to prevent a file from being considered non modified // something useful if a file failed some sort of validation // you can then remove the entry from the cache doing cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` // that will effectively make the file to appear again as modified until the validation is passed. In that // case you should not remove it from the cache // if you need all the files, so you can determine what to do with the changed ones // you can call var oFiles = cache.normalizeEntries(files); // oFiles will be an array of objects like the following entry = { key: 'some/name/file', the path to the file changed: true, // if the file was changed since previous run meta: { size: 3242, // the size of the file mtime: 231231231, // the modification time of the file data: {} // some extra field stored for this file (useful to save the result of a transformation on the file } } ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with optional file persistance. The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, then store the new state of the files. The next time this module request for `getChangedFiles` will return only the files that were modified. Making the process to end faster. This module could also be used by processes that modify the files applying a transform, in that case the result of the transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed the transformed stored data could be used instead of actually applying the transformation, saving time in case of only a few files changed. In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. ## Important notes - The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values - All the changes to the cache state are done to memory first and only persisted after reconcile. ## License MIT # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC [![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) This package is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy to use and powerful. It was first released in 2010 and is tested against big data sets by a large community. ## Documentation * [Project homepage](http://csv.js.org/stringify/) * [API](http://csv.js.org/stringify/api/) * [Options](http://csv.js.org/stringify/options/) * [Examples](http://csv.js.org/stringify/examples/) ## Main features * Follow the Node.js streaming API * Simplicity with the optional callback API * Support for custom formatters, delimiters, quotes, escape characters and header * Support big datasets * Complete test coverage and samples for inspiration * Only 1 external dependency * to be used conjointly with `csv-generate`, `csv-parse` and `stream-transform` * MIT License ## Usage The module is built on the Node.js Stream API. For the sake of simplicity, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: ```javascript const stringify = require('csv-stringify') const assert = require('assert') // import stringify from 'csv-stringify' // import assert from 'assert/strict' const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] stringify(input, function(err, output) { const expected = '1,2,3,4\na,b,c,d\n' assert.strictEqual(output, expected, `output.should.eql ${expected}`) console.log("Passed.", output) }) ``` ## Development Tests are executed with mocha. To install it, run `npm install` followed by `npm test`. It will install mocha and its dependencies in your project "node_modules" directory and run the test suite. The tests run against the CoffeeScript source files. To generate the JavaScript files, run `npm run build`. The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node-csv-stringify). See the [Travis definition file](https://github.com/adaltas/node-csv-stringify/blob/master/.travis.yml) to view the tested Node.js version. ## Contributors * David Worms: <https://github.com/wdavidw> [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform [examples]: http://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value = <JSON.Value>valueOrNull; // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let innerString = (<JSON.Str>value).valueOf(); let jsonString = (<JSON.Str>value).stringify(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: string = encoder.stringify(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i64): void { // Handle field } setFloat(name: string, value: f64): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv v7 beta is released [Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: - to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. - to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. - to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. - schemas are compiled to ES6 code (ES5 code generation is supported with an option). - to improve reliability and maintainability the code is migrated to TypeScript. **Please note**: - the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). - all formats are separated to ajv-formats package - they have to be explicitely added if you use them. See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. To install the new version: ```bash npm install ajv@beta ``` See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. ## Mozilla MOSS grant and OpenJS Foundation [<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP/HTTPS Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true ### WS/WSS Support URI.parse("wss://example.com/foo?bar=baz"); //returns: //{ // scheme : "wss", // host: "example.com", // resourceName: "/foo?bar=baz", // secure: true, //} URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "uuid", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: npm install uri-js # OR yarn add uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. # type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) <a name="type-check" /> `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). npm install type-check ## Quick Examples ```js // Basic types: var typeCheck = require('type-check').typeCheck; typeCheck('Number', 1); // true typeCheck('Number', 'str'); // false typeCheck('Error', new Error); // true typeCheck('Undefined', undefined); // true // Comment typeCheck('count::Number', 1); // true // One type OR another type: typeCheck('Number | String', 2); // true typeCheck('Number | String', 'str'); // true // Wildcard, matches all types: typeCheck('*', 2) // true // Array, all elements of a single type: typeCheck('[Number]', [1, 2, 3]); // true typeCheck('[Number]', [1, 'str', 3]); // false // Tuples, or fixed length arrays with elements of different types: typeCheck('(String, Number)', ['str', 2]); // true typeCheck('(String, Number)', ['str']); // false typeCheck('(String, Number)', ['str', 2, 5]); // false // Object properties: typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true typeCheck('{x: Number, y: Boolean}', {x: 2}); // false typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true // A particular type AND object properties: typeCheck('RegExp{source: String, ...}', /re/i); // true typeCheck('RegExp{source: String, ...}', {source: 're'}); // false // Custom types: var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; typeCheck('Even', 2, opt); // true // Nested: var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true ``` Check out the [type syntax format](#syntax) and [guide](#guide). ## Usage `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. ```js // typeCheck(type, input, options); typeCheck('Number', 2); // true // parseType(type); var parsedType = parseType('Number'); // object // parsedTypeCheck(parsedType, input, options); parsedTypeCheck(parsedType, 2); // true ``` ### typeCheck(type, input, options) `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js typeCheck('Number', 2); // true ``` ### parseType(type) `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to parse ##### returns `Object` - an object in the parsed type format representing the parsed type ##### example ```js parseType('Number'); // [{type: 'Number'}] ``` ### parsedTypeCheck(parsedType, input, options) `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js parsedTypeCheck([{type: 'Number'}], 2); // true var parsedType = parseType('String'); parsedTypeCheck(parsedType, 'str'); // true ``` <a name="type-format" /> ## Type Format ### Syntax White space is ignored. The root node is a __Types__. * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` ### Guide `type-check` uses `Object.toString` to find out the basic type of a value. Specifically, ```js {}.toString.call(VALUE).slice(8, -1) {}.toString.call(true).slice(8, -1) // 'Boolean' ``` A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. The wildcard `*` matches all types. There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. ## Options Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. <a name="custom-types" /> ### Custom Types __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; } } } }; typeCheck('Even', 2, options); // true typeCheck('Even', 3, options); // false ``` `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. ## Technical About `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 10.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) [![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## Enterprise support json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # Optionator <a name="optionator" /> Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). [About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format) ## Why? The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. $ cmd --halp Invalid option '--halp' - perhaps you meant '--help'? $ cmd --count str Invalid value for option 'count' - expected type Int, received value: str. Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. ## About Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. MIT license. Version 0.9.1 npm install optionator For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. ## Usage `require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. ```js var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` ### parse(input, parseOptions) `parse` processes the `input` according to your settings, and returns an object with the results. ##### arguments * input - `[String] | Object | String` - the input you wish to parse * parseOptions - `{slice: Int}` - all options optional - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) ##### returns `Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. ##### example ```js parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} parse('--count 2 positional'); // {count: 2, _: ['positional']} parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} ``` ### parseArgv(input) `parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. ##### arguments * input - `[String]` - the input you wish to parse ##### returns See "returns" section in "parse" ##### example ```js parseArgv(process.argv); ``` ### generateHelp(helpOptions) `generateHelp` produces help text based on your settings. ##### arguments * helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` ##### returns `String` - the generated help text ##### example ```js generateHelp(); /* "Usage: cmd [options] positional -h, --help displays help -c, --count Int number of things Version 1.0.0 "*/ ``` ### generateHelpForOption(optionName) `generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. ##### arguments * optionName - `String` - the name of the option to display ##### returns `String` - the generated help text for the option ##### example ```js generateHelpForOption('count'); /* "-c, --count Int description: number of things example: cmd --count 2 "*/ ``` ## Settings Format When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: { prepend: String, append: String, options: [{heading: String} | { option: String, alias: [String] | String, type: String, enum: [String], default: String, restPositional: Boolean, required: Boolean, overrideRequired: Boolean, dependsOn: [String] | String, concatRepeatedArrays: Boolean | (Boolean, Object), mergeRepeatedObjects: Boolean, description: String, longDescription: String, example: [String] | String }], helpStyle: { aliasSeparator: String, typeSeparator: String, descriptionSeparator: String, initialIndent: Int, secondaryIndent: Int, maxPadFactor: Number }, mutuallyExclusive: [[String | [String]]], concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object mergeRepeatedObjects: Boolean, // deprecated, set in defaults object positionalAnywhere: Boolean, typeAliases: Object, defaults: Object } All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. ### Top Level Properties * `prepend` is an optional string to be placed before the options in the help text * `append` is an optional string to be placed after the options in the help text * `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified * `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text * `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present * `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` * `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` * `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property #### Heading Properties * `heading` a required string, the name of the heading #### Option Properties * `option` the required name of the option - use dash-case, without the leading dashes * `alias` is an optional string or array of strings which specify any aliases for the option * `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it * `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` * `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` * `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument * `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined * `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags * `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. * `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` * `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set * `description` is an optional string, which will be displayed next to the option in the help text * `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used * `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used #### Help Style Properties * `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' * `typeSeparator` is an optional string, separates the type from the names - default: ' ' * `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' * `initialIndent` is an optional int - the amount of indent for options - default: 2 * `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 * `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 ## Argument Format At the highest level there are two types of arguments: named, and positional. Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. Everything after an `--` is positional, even if it looks like a named argument. You may optionally use `=` to separate option names from values, for example: `--count=2`. If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. If duplicate named arguments are present, the last one will be taken. ## Technical About `optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. # `asbuild` [![Stars](https://img.shields.io/github/stars/AssemblyScript/asbuild.svg?style=social&maxAge=3600&label=Star)](https://github.com/AssemblyScript/asbuild/stargazers) *A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.* ## 🚩 Table of Contents - [Installing](#-installing) - [Usage](#-usage) - [`asb init`](#asb-init---create-an-empty-project) - [`asb test`](#asb-test---run-as-pect-tests) - [`asb fmt`](#asb-fmt---format-as-files-using-eslint) - [`asb run`](#asb-run---run-a-wasi-binary) - [`asb build`](#asb-build---compile-the-project-using-asc) - [Background](#-background) ## 🔧 Installing Install it globally ``` npm install -g asbuild ``` Or, locally as dev dependencies ``` npm install --save-dev asbuild ``` ## 💡 Usage ``` Build tool for AssemblyScript projects. Usage: asb [command] [options] Commands: asb Alias of build command, to maintain back-ward compatibility [default] asb build Compile a local package and all of its dependencies [aliases: compile, make] asb init [baseDir] Create a new AS package in an given directory asb test Run as-pect tests asb fmt [paths..] This utility formats current module using eslint. [aliases: format, lint] Options: --version Show version number [boolean] --help Show help [boolean] ``` ### `asb init` - Create an empty project ``` asb init [baseDir] Create a new AS package in an given directory Positionals: baseDir Create a sample AS project in this directory [string] [default: "."] Options: --version Show version number [boolean] --help Show help [boolean] --yes Skip the interactive prompt [boolean] [default: false] ``` ### `asb test` - Run as-pect tests ``` asb test Run as-pect tests USAGE: asb test [options] -- [aspect_options] Options: --version Show version number [boolean] --help Show help [boolean] --verbose, --vv Print out arguments passed to as-pect [boolean] [default: false] ``` ### `asb fmt` - Format AS files using ESlint ``` asb fmt [paths..] This utility formats current module using eslint. Positionals: paths Paths to format [array] [default: ["."]] Initialisation: --init Generates recommended eslint config for AS Projects [boolean] Miscellaneous --lint, --dry-run Tries to fix problems without saving the changes to the file system [boolean] [default: false] Options: --version Show version number [boolean] --help Show help ``` ### `asb run` - Run a WASI binary ``` asb run Run a WASI binary USAGE: asb run [options] [binary path] -- [binary options] Positionals: binary path to Wasm binary [string] [required] Options: --version Show version number [boolean] --help Show help [boolean] --preopen, -p comma separated list of directories to open. [default: "."] ``` ### `asb build` - Compile the project using asc ``` asb build Compile a local package and all of its dependencies USAGE: asb build [entry_file] [options] -- [asc_options] Options: --version Show version number [boolean] --help Show help [boolean] --baseDir, -d Base directory of project. [string] [default: "."] --config, -c Path to asconfig file [string] [default: "./asconfig.json"] --wat Output wat file to outDir [boolean] [default: false] --outDir Directory to place built binaries. Default "./build/<target>/" [string] --target Target for compilation [string] [default: "release"] --verbose Print out arguments passed to asc [boolean] [default: false] Examples: asb build Build release of 'assembly/index.ts to build/release/packageName.wasm asb build --target release Build a release binary asb build -- --measure Pass argument to 'asc' ``` #### Defaults ##### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ##### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./tests/build_test) ## 📖 Background Asbuild started as wrapper around `asc` to provide an easier CLI interface and now has been extened to support other commands like `init`, `test` and `fmt` just like `cargo` to become a one stop build tool for AS Projects. ## 📜 License This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/). # word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Acorn-JSX [![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) [![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. ## Transpiler Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. ## Usage Requiring this module provides you with an Acorn plugin that you can use like this: ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');"); ``` Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `[email protected]`. If you still want to opt-in to support of such constructions, you can pass the following option: ```javascript acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) ``` Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: ```javascript acorn.Parser.extend(jsx({ allowNamespaces: false })) ``` Note that by default `allowNamespaces` is enabled for spec compliancy. ## License This plugin is issued under the [MIT license](./LICENSE). # flat-cache > A stupidly simple key/value storage using files to persist the data [![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) [![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache) ## install ```bash npm i --save flat-cache ``` ## Usage ```js var flatCache = require('flat-cache') // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var cache = flatCache.load('cacheId'); // sets a key on the cache cache.setKey('key', { foo: 'var' }); // get a key from the cache cache.getKey('key') // { foo: 'var' } // fetch the entire persisted object cache.all() // { 'key': { foo: 'var' } } // remove a key cache.removeKey('key'); // removes a key from the cache // save it to disk cache.save(); // very important, if you don't save no changes will be persisted. // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys // loads the cache from a given directory, if one does // not exists for the given Id a new one will be prepared to be created var cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); // The following methods are useful to clear the cache // delete a given cache flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists. // delete all cache flatCache.clearAll(); // remove the cache directory ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` storage was needed and Bam! this module was born. ## Important notes - If no directory is especified when the `load` method is called, a folder named `.cache` will be created inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you might want to ignore the default `.cache` folder, or specify a custom directory. - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references - All the changes to the cache state are done to memory - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module intentionally dumb and simple - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call like: `cache.save( true /* noPrune */ )`. ## License MIT ## Changelog [changelog](./changelog.md) # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore). Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module. ##### Tested on - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - [Guide for 2.x -> 3.x](#upgrade-2x---3x) - [Guide for 3.x -> 4.x](#upgrade-3x---4x) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array<Pathname>): Array<Pathname> ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory. ```js // WRONG ig.ignores('./abc') // WRONG, for it will never happen. // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js ig.add('config/') // `ig` does NOT know if 'config' is a normal file, directory or something ig.ignores('config') // And it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` **** # Upgrade Guide ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* # eslint-utils [![npm version](https://img.shields.io/npm/v/eslint-utils.svg)](https://www.npmjs.com/package/eslint-utils) [![Downloads/month](https://img.shields.io/npm/dm/eslint-utils.svg)](http://www.npmtrends.com/eslint-utils) [![Build Status](https://github.com/mysticatea/eslint-utils/workflows/CI/badge.svg)](https://github.com/mysticatea/eslint-utils/actions) [![Coverage Status](https://codecov.io/gh/mysticatea/eslint-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-utils) [![Dependency Status](https://david-dm.org/mysticatea/eslint-utils.svg)](https://david-dm.org/mysticatea/eslint-utils) ## 🏁 Goal This package provides utility functions and classes for make ESLint custom rules. For examples: - [getStaticValue](https://eslint-utils.mysticatea.dev/api/ast-utils.html#getstaticvalue) evaluates static value on AST. - [ReferenceTracker](https://eslint-utils.mysticatea.dev/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. ## 📖 Usage See [documentation](https://eslint-utils.mysticatea.dev/). ## 📰 Changelog See [releases](https://github.com/mysticatea/eslint-utils/releases). ## ❤️ Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run clean` removes the coverage result of `npm test` command. - `npm run coverage` shows the coverage result of the last `npm test` command. - `npm run lint` runs ESLint. - `npm run watch` runs tests on each file change. # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Aliases Create custom aliases for styles. ```js const colors = require('ansi-colors'); colors.alias('primary', colors.yellow); colors.alias('secondary', colors.bold); console.log(colors.primary.secondary('Foo')); ``` ## Themes A theme is an object of custom aliases. ```js const colors = require('ansi-colors'); colors.theme({ danger: colors.red, dark: colors.dim.gray, disabled: colors.gray, em: colors.italic, heading: colors.bold.underline, info: colors.cyan, muted: colors.dim, primary: colors.blue, strong: colors.bold, success: colors.green, underline: colors.underline, warning: colors.yellow }); // Now, we can use our custom styles alongside the built-in styles! console.log(colors.danger.strong.em('Error!')); console.log(colors.warning('Heads up!')); console.log(colors.info('Did you know...')); console.log(colors.success.bold('It worked!')); ``` ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 48 | [jonschlinkert](https://github.com/jonschlinkert) | | 42 | [doowb](https://github.com/doowb) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._ # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. [![build status](https://app.travis-ci.com/dankogai/js-base64.svg)](https://app.travis-ci.com/github/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.encode(latin, true)); // ZGFua29nYWk skips padding Base64.encodeURI(latin)); // ZGFua29nYWk Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.decode( 'ZGFua29nYWk'); // dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend Uint8Array.prototype Base64.extendUint8Array(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IEs before 11. Do the following in your shell. ```shell $ make base64.es5.js ``` ## Brief History * Since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. * Since version 3.7 `base64.js` is ES5-compatible again (hence IE11-compabile). * Since 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above) # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # regexpp [![npm version](https://img.shields.io/npm/v/regexpp.svg)](https://www.npmjs.com/package/regexpp) [![Downloads/month](https://img.shields.io/npm/dm/regexpp.svg)](http://www.npmtrends.com/regexpp) [![Build Status](https://github.com/mysticatea/regexpp/workflows/CI/badge.svg)](https://github.com/mysticatea/regexpp/actions) [![codecov](https://codecov.io/gh/mysticatea/regexpp/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/regexpp) [![Dependency Status](https://david-dm.org/mysticatea/regexpp.svg)](https://david-dm.org/mysticatea/regexpp) A regular expression parser for ECMAScript. ## 💿 Installation ```bash $ npm install regexpp ``` - require Node.js 8 or newer. ## 📖 Usage ```ts import { AST, RegExpParser, RegExpValidator, RegExpVisitor, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST } from "regexpp" ``` ### parseRegExpLiteral(source, options?) Parse a given regular expression literal then make AST object. This is equivalent to `new RegExpParser(options).parseLiteral(source)`. - **Parameters:** - `source` (`string | RegExp`) The source code to parse. - `options?` ([`RegExpParser.Options`]) The options to parse. - **Return:** - The AST of the regular expression. ### validateRegExpLiteral(source, options?) Validate a given regular expression literal. This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. - **Parameters:** - `source` (`string`) The source code to validate. - `options?` ([`RegExpValidator.Options`]) The options to validate. ### visitRegExpAST(ast, handlers) Visit each node of a given AST. This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. ### RegExpParser #### new RegExpParser(options?) - **Parameters:** - `options?` ([`RegExpParser.Options`]) The options to parse. #### parser.parseLiteral(source, start?, end?) Parse a regular expression literal. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression. #### parser.parsePattern(source, start?, end?, uFlag?) Parse a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"abc"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. - **Return:** - The AST of the regular expression pattern. #### parser.parseFlags(source, start?, end?) Parse a regular expression flags. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"gim"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression flags. ### RegExpValidator #### new RegExpValidator(options) - **Parameters:** - `options` ([`RegExpValidator.Options`]) The options to validate. #### validator.validateLiteral(source, start, end) Validate a regular expression literal. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. #### validator.validatePattern(source, start, end, uFlag) Validate a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. #### validator.validateFlags(source, start, end) Validate a regular expression flags. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. ### RegExpVisitor #### new RegExpVisitor(handlers) - **Parameters:** - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. #### visitor.visit(ast) Validate a regular expression literal. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. ## 📰 Changelog - [GitHub Releases](https://github.com/mysticatea/regexpp/releases) ## 🍻 Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. - `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. - `npm run lint` runs ESLint. - `npm run update:test` updates test fixtures. - `npm run update:ids` updates `src/unicode/ids.ts`. - `npm run watch` runs tests with `--watch` option. [`AST.Node`]: src/ast.ts#L4 [`RegExpParser.Options`]: src/parser.ts#L539 [`RegExpValidator.Options`]: src/validator.ts#L127 [`RegExpVisitor.Handlers`]: src/visitor.ts#L204 # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. <h1 align="center">Enquirer</h1> <p align="center"> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version"> </a> <a href="https://travis-ci.org/enquirer/enquirer"> <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis"> </a> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br> <sub>>_ Prompts should be more like conversations than inquisitions▌</sub> </p> <br> <p align="center"> <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br> <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br> <a href="#built-in-prompts"><strong>See more prompt examples</strong></a> </p> <br> <br> Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases. * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_) * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb). * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement. * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos. * **Intuitive** - Keypress combos are available to simplify usage. * **Flexible** - All prompts can be used standalone or chained together. * **Stylish** - Easily override semantic styles and symbols for any part of the prompt. * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts). * **Pluggable** - Add advanced features to Enquirer using plugins. * **Validation** - Optionally validate user input with any prompt. * **Well tested** - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values. * **Examples** - There are numerous [examples](examples) available to help you get started. If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks! <br> <p align="center"> <b>>_ Ready to start making prompts your users will love? ▌</b><br> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750"> </p> <br> <br> ## ❯ Getting started Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts. * [Install](#-install) * [Usage](#-usage) * [Enquirer](#-enquirer) * [Prompts](#-prompts) - [Built-in Prompts](#-prompts) - [Custom Prompts](#-custom-prompts) * [Key Bindings](#-key-bindings) * [Options](#-options) * [Release History](#-release-history) * [Performance](#-performance) * [About](#-about) <br> ## ❯ Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install enquirer --save ``` Install with [yarn](https://yarnpkg.com/en/): ```sh $ yarn add enquirer ``` <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750"> </p> _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_ <br> ## ❯ Usage ### Single prompt The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method. ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); // { username: 'jonschlinkert' } ``` _(Examples with `await` need to be run inside an `async` function)_ ### Multiple prompts Pass an array of ["question" objects](#prompt-options) to run a series of prompts. ```js const response = await prompt([ { type: 'input', name: 'name', message: 'What is your name?' }, { type: 'input', name: 'username', message: 'What is your username?' } ]); console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' } ``` ### Different ways to run enquirer #### 1. By importing the specific `built-in prompt` ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Did you like enquirer?' }); prompt.run() .then(answer => console.log('Answer:', answer)); ``` #### 2. By passing the options to `prompt` ```js const { prompt } = require('enquirer'); prompt({ type: 'confirm', name: 'question', message: 'Did you like enquirer?' }) .then(answer => console.log('Answer:', answer)); ``` **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings) <br> ## ❯ Enquirer **Enquirer is a prompt runner** Add Enquirer to your JavaScript project with following line of code. ```js const Enquirer = require('enquirer'); ``` The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts. ```js const { prompt } = require('enquirer'); const question = [ { type: 'input', name: 'username', message: 'What is your username?' }, { type: 'password', name: 'password', message: 'What is your password?' } ]; let answers = await prompt(question); console.log(answers); ``` **Prompts control how values are rendered and returned** Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application. **How can I customize prompts?** Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt. All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`. Use this approach if you need to modify a prompt instance, or listen for events on the prompt. **Example** ```js const { Input } = require('enquirer'); const prompt = new Input({ name: 'username', message: 'What is your username?' }); prompt.run() .then(answer => console.log('Username:', answer)) .catch(console.error); ``` ### [Enquirer](index.js#L20) Create an instance of `Enquirer`. **Params** * `options` **{Object}**: (optional) Options to use with all prompts. * `answers` **{Object}**: (optional) Answers object to initialize with. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` ### [register()](index.js#L42) Register a custom prompt type. **Params** * `type` **{String}** * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class. * `returns` **{Object}**: Returns the Enquirer instance **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); enquirer.register('customType', require('./custom-prompt')); ``` ### [prompt()](index.js#L78) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const response = await enquirer.prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` ### [use()](index.js#L160) Use an enquirer plugin. **Params** * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer. * `returns` **{Object}**: Returns the Enquirer instance. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const plugin = enquirer => { // do stuff to enquire instance }; enquirer.use(plugin); ``` ### [Enquirer#prompt](index.js#L210) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` <br> ## ❯ Prompts This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept. **Getting started with Enquirer's prompts** * [Prompt](#prompt) - The base `Prompt` class used by other prompts - [Prompt Options](#prompt-options) * [Built-in prompts](#built-in-prompts) * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts * [Custom prompts](#%E2%9D%AF-custom-prompts) - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use. ### Prompt The base `Prompt` class is used to create all other prompts. ```js const { Prompt } = require('enquirer'); class MyCustomPrompt extends Prompt {} ``` See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works. #### Prompt Options Each prompt takes an options object (aka "question" object), that implements the following interface: ```js { // required type: string | function, name: string | function, message: string | function | async function, // optional skip: boolean | function | async function, initial: string | function | async function, format: function | async function, result: function | async function, validate: function | async function, } ``` Each property of the options object is described below: | **Property** | **Required?** | **Type** | **Description** | | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. | | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. | | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. | | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. | | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. | | `format` | no | `function` | Function to format user input in the terminal. | | `result` | no | `function` | Function to format the final submitted value before it's returned. | | `validate` | no | `function` | Function to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message. | **Example usage** ```js const { prompt } = require('enquirer'); const question = { type: 'input', name: 'username', message: 'What is your username?' }; prompt(question) .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` <br> ### Built-in prompts * [AutoComplete Prompt](#autocomplete-prompt) * [BasicAuth Prompt](#basicauth-prompt) * [Confirm Prompt](#confirm-prompt) * [Form Prompt](#form-prompt) * [Input Prompt](#input-prompt) * [Invisible Prompt](#invisible-prompt) * [List Prompt](#list-prompt) * [MultiSelect Prompt](#multiselect-prompt) * [Numeral Prompt](#numeral-prompt) * [Password Prompt](#password-prompt) * [Quiz Prompt](#quiz-prompt) * [Survey Prompt](#survey-prompt) * [Scale Prompt](#scale-prompt) * [Select Prompt](#select-prompt) * [Sort Prompt](#sort-prompt) * [Snippet Prompt](#snippet-prompt) * [Toggle Prompt](#toggle-prompt) ### AutoComplete Prompt Prompt that auto-completes as the user types, and returns the selected value as a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750"> </p> **Example Usage** ```js const { AutoComplete } = require('enquirer'); const prompt = new AutoComplete({ name: 'flavor', message: 'Pick your favorite flavor', limit: 10, initial: 2, choices: [ 'Almond', 'Apple', 'Banana', 'Blackberry', 'Blueberry', 'Cherry', 'Chocolate', 'Cinnamon', 'Coconut', 'Cranberry', 'Grape', 'Nougat', 'Orange', 'Pear', 'Pineapple', 'Raspberry', 'Strawberry', 'Vanilla', 'Watermelon', 'Wintergreen' ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **AutoComplete Options** | Option | Type | Default | Description | | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. | | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. | | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. | | `initial` | `number` | 0 | Preselected item in the list of choices. | | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) | **Related prompts** * [Select](#select-prompt) * [MultiSelect](#multiselect-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### BasicAuth Prompt Prompt that asks for username and password to authenticate the user. The default implementation of `authenticate` function in `BasicAuth` prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the `authenticate` function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750"> </p> **Example Usage** ```js const { BasicAuth } = require('enquirer'); const prompt = new BasicAuth({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '123', showPassword: true }); prompt .run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Confirm Prompt Prompt that returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750"> </p> **Example Usage** ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Want to answer?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Form Prompt Prompt that allows the user to enter and submit multiple values on a single terminal screen. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750"> </p> **Example Usage** ```js const { Form } = require('enquirer'); const prompt = new Form({ name: 'user', message: 'Please provide the following information:', choices: [ { name: 'firstname', message: 'First Name', initial: 'Jon' }, { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' }, { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' } ] }); prompt.run() .then(value => console.log('Answer:', value)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Input Prompt Prompt that takes user input and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750"> </p> **Example Usage** ```js const { Input } = require('enquirer'); const prompt = new Input({ message: 'What is your username?', initial: 'jonschlinkert' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.log); ``` You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)). **Related prompts** * [Confirm](#confirm-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Invisible Prompt Prompt that takes user input, hides it from the terminal, and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750"> </p> **Example Usage** ```js const { Invisible } = require('enquirer'); const prompt = new Invisible({ name: 'secret', message: 'What is your secret?' }); prompt.run() .then(answer => console.log('Answer:', { secret: answer })) .catch(console.error); ``` **Related prompts** * [Password](#password-prompt) * [Input](#input-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### List Prompt Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750"> </p> **Example Usage** ```js const { List } = require('enquirer'); const prompt = new List({ name: 'keywords', message: 'Type comma-separated keywords' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Sort](#sort-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### MultiSelect Prompt Prompt that allows the user to select multiple items from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750"> </p> **Example Usage** ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: ['aqua', 'blue', 'fuchsia'] ``` **Example key-value pairs** Optionally, pass a `result` function and use the `.map` method to return an object of key-value pairs of the selected names and values: [example](./examples/multiselect/option-result.js) ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ], result(names) { return this.map(names); } }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' } ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Numeral Prompt Prompt that takes a number as input. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750"> </p> **Example Usage** ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ name: 'number', message: 'Please enter a number' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Confirm](#confirm-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Password Prompt Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt) <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750"> </p> **Example Usage** ```js const { Password } = require('enquirer'); const prompt = new Password({ name: 'password', message: 'What is your password?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Invisible](#invisible-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Quiz Prompt Prompt that allows the user to play multiple-choice quiz questions. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750"> </p> **Example Usage** ```js const { Quiz } = require('enquirer'); const prompt = new Quiz({ name: 'countries', message: 'How many countries are there in the world?', choices: ['165', '175', '185', '195', '205'], correctChoice: 3 }); prompt .run() .then(answer => { if (answer.correct) { console.log('Correct!'); } else { console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); } }) .catch(console.error); ``` **Quiz Options** | Option | Type | Required | Description | | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | | `choices` | `array` | Yes | The list of possible answers to the quiz question. | | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. | **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Survey Prompt Prompt that allows the user to provide feedback for a list of questions. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"> </p> **Example Usage** ```js const { Survey } = require('enquirer'); const prompt = new Survey({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.' }, { name: 'navigation', message: 'The website is easy to navigate.' }, { name: 'images', message: 'The website usually has good images.' }, { name: 'upload', message: 'The website makes it easy to upload images.' }, { name: 'colors', message: 'The website has a pleasing color palette.' } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [Scale](#scale-prompt) * [Snippet](#snippet-prompt) * [Select](#select-prompt) *** ### Scale Prompt A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale). <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750"> </p> **Example Usage** ```js const { Scale } = require('enquirer'); const prompt = new Scale({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.', initial: 2 }, { name: 'navigation', message: 'The website is easy to navigate.', initial: 2 }, { name: 'images', message: 'The website usually has good images.', initial: 2 }, { name: 'upload', message: 'The website makes it easy to upload images.', initial: 2 }, { name: 'colors', message: 'The website has a pleasing color palette.', initial: 2 } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Select Prompt Prompt that allows the user to select from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750"> </p> **Example Usage** ```js const { Select } = require('enquirer'); const prompt = new Select({ name: 'color', message: 'Pick a flavor', choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [MultiSelect](#multiselect-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Sort Prompt Prompt that allows the user to sort items in a list. **Example** In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750"> </p> **Example Usage** ```js const colors = require('ansi-colors'); const { Sort } = require('enquirer'); const prompt = new Sort({ name: 'colors', message: 'Sort the colors in order of preference', hint: 'Top is best, bottom is worst', numbered: true, choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ name: n, message: colors[n](n) })) }); prompt.run() .then(function(answer = []) { console.log(answer); console.log('Your preferred order of colors is:'); console.log(answer.map(key => colors[key](key)).join('\n')); }) .catch(console.error); ``` **Related prompts** * [List](#list-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Snippet Prompt Prompt that allows the user to replace placeholders in a snippet of code or text. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750"> </p> **Example Usage** ```js const semver = require('semver'); const { Snippet } = require('enquirer'); const prompt = new Snippet({ name: 'username', message: 'Fill out the fields in package.json', required: true, fields: [ { name: 'author_name', message: 'Author Name' }, { name: 'version', validate(value, state, item, index) { if (item && item.name === 'version' && !semver.valid(value)) { return prompt.styles.danger('version should be a valid semver value'); } return true; } } ], template: `{ "name": "\${name}", "description": "\${description}", "version": "\${version}", "homepage": "https://github.com/\${username}/\${name}", "author": "\${author_name} (https://github.com/\${username})", "repository": "\${username}/\${name}", "license": "\${license:ISC}" } ` }); prompt.run() .then(answer => console.log('Answer:', answer.result)) .catch(console.error); ``` **Related prompts** * [Survey](#survey-prompt) * [AutoComplete](#autocomplete-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Toggle Prompt Prompt that allows the user to toggle between two values then returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750"> </p> **Example Usage** ```js const { Toggle } = require('enquirer'); const prompt = new Toggle({ message: 'Want to answer?', enabled: 'Yep', disabled: 'Nope' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Confirm](#confirm-prompt) * [Input](#input-prompt) * [Sort](#sort-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Prompt Types There are 5 (soon to be 6!) type classes: * [ArrayPrompt](#arrayprompt) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [Choices](#choices) - [Defining choices](#defining-choices) - [Choice properties](#choice-properties) - [Related prompts](#related-prompts) * [AuthPrompt](#authprompt) * [BooleanPrompt](#booleanprompt) * DatePrompt (Coming Soon!) * [NumberPrompt](#numberprompt) * [StringPrompt](#stringprompt) Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how. ### ArrayPrompt The `ArrayPrompt` class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the [Select](#select) and [Survey](#survey) prompts. #### Options In addition to the [options](#options) available to all prompts, Array prompts also support the following options. | **Option** | **Required?** | **Type** | **Description** | | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | | | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. | | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. | | | #### Properties Array prompts have the following instance properties and getters. | **Property name** | **Type** | **Description** | | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. | | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. | | `enabled` | `array` | Returns an array of enabled choices. | | `focused` | `array` | Returns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is _focused_, the list will scroll to the focused choice and re-render. | | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. | | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. | | `limit` | `number` | The number of choices to display on-screen. | | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. | | `visible` | `string` | | #### Methods | **Method** | **Description** | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pointer()` | Returns the visual symbol to use to identify the choice that currently has focus. The `❯` symbol is often used for this. The pointer is not always visible, as with the `autocomplete` prompt. | | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. | | `focus()` | Sets focus on a choice, if it can be focused. | #### Choices Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal. **Type**: `string|object` **Example** ```js const { prompt } = require('enquirer'); const questions = [{ type: 'select', name: 'color', message: 'Favorite color?', initial: 1, choices: [ { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object ] }]; let answers = await prompt(questions); console.log('Answer:', answers.color); ``` #### Defining choices Whether defined as a string or object, choices are normalized to the following interface: ```js { name: string; message: string | undefined; value: string | undefined; hint: string | undefined; disabled: boolean | string | undefined; } ``` **Example** ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: ['Apple', 'Orange', 'Raspberry'] }; ``` Normalizes to the following when the prompt is run: ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: [ { name: 'Apple', message: 'Apple', value: 'Apple' }, { name: 'Orange', message: 'Orange', value: 'Orange' }, { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } ] }; ``` #### Choice properties The following properties are supported on `choice` objects. | **Option** | **Type** | **Description** | | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The unique key to identify a choice | | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. | | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. | | `choices` | `array` | Array of "child" choices. | | `hint` | `string` | Help message to display next to a choice. | | `role` | `string` | Determines how the choice will be displayed. Currently the only role supported is `separator`. Additional roles may be added in the future (like `heading`, etc). Please create a [feature request] | | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). | | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. | | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). | #### Related prompts * [AutoComplete](#autocomplete-prompt) * [Form](#form-prompt) * [MultiSelect](#multiselect-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) *** ### AuthPrompt The `AuthPrompt` is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the [BasicAuth Prompt](#basicauth-prompt). You can also find prompt examples in `examples/auth/` folder that utilizes `AuthPrompt` to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others. `AuthPrompt` has a factory function that creates an instance of `AuthPrompt` class and it expects an `authenticate` function, as an argument, which overrides the `authenticate` function of the `AuthPrompt` class. #### Methods | **Method** | **Description** | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticate()` | Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default `authenticate` function throws an error if no other function is provided. | #### Choices Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt). **Example** ```js const { AuthPrompt } = require('enquirer'); function authenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } const CustomAuthPrompt = AuthPrompt.create(authenticate); const prompt = new CustomAuthPrompt({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '1234567', choices: [ { name: 'username', message: 'username' }, { name: 'password', message: 'password' } ] }); prompt .run() .then(answer => console.log('Authenticated?', answer)) .catch(console.error); ``` #### Related prompts * [BasicAuth Prompt](#basicauth-prompt) *** ### BooleanPrompt The `BooleanPrompt` class is used for creating prompts that display and return a boolean value. ```js const { BooleanPrompt } = require('enquirer'); const prompt = new BooleanPrompt({ header: '========================', message: 'Do you love enquirer?', footer: '========================', }); prompt.run() .then(answer => console.log('Selected:', answer)) .catch(console.error); ``` **Returns**: `boolean` *** ### NumberPrompt The `NumberPrompt` class is used for creating prompts that display and return a numerical value. ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ header: '************************', message: 'Input the Numbers:', footer: '************************', }); prompt.run() .then(answer => console.log('Numbers are:', answer)) .catch(console.error); ``` **Returns**: `string|number` (number, or number formatted as a string) *** ### StringPrompt The `StringPrompt` class is used for creating prompts that display and return a string value. ```js const { StringPrompt } = require('enquirer'); const prompt = new StringPrompt({ header: '************************', message: 'Input the String:', footer: '************************' }); prompt.run() .then(answer => console.log('String is:', answer)) .catch(console.error); ``` **Returns**: `string` <br> ## ❯ Custom prompts With Enquirer 2.0, custom prompts are easier than ever to create and use. **How do I create a custom prompt?** Custom prompts are created by extending either: * Enquirer's `Prompt` class * one of the built-in [prompts](#-prompts), or * low-level [types](#-types). <!-- Example: HaiKarate Custom Prompt --> ```js const { Prompt } = require('enquirer'); class HaiKarate extends Prompt { constructor(options = {}) { super(options); this.value = options.initial || 0; this.cursorHide(); } up() { this.value++; this.render(); } down() { this.value--; this.render(); } render() { this.clear(); // clear previously rendered prompt from the terminal this.write(`${this.state.message}: ${this.value}`); } } // Use the prompt by creating an instance of your custom prompt class. const prompt = new HaiKarate({ message: 'How many sprays do you want?', initial: 10 }); prompt.run() .then(answer => console.log('Sprays:', answer)) .catch(console.error); ``` If you want to be able to specify your prompt by `type` so that it may be used alongside other prompts, you will need to first create an instance of `Enquirer`. ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` Then use the `.register()` method to add your custom prompt. ```js enquirer.register('haikarate', HaiKarate); ``` Now you can do the following when defining "questions". ```js let spritzer = require('cologne-drone'); let answers = await enquirer.prompt([ { type: 'haikarate', name: 'cologne', message: 'How many sprays do you need?', initial: 10, async onSubmit(name, value) { await spritzer.activate(value); //<= activate drone return value; } } ]); ``` <br> ## ❯ Key Bindings ### All prompts These key combinations may be used with all prompts. | **command** | **description** | | -------------------------------- | -------------------------------------- | | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. | | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. | <br> ### Move cursor These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>left</kbd> | Move the cursor back one character. | | <kbd>right</kbd> | Move the cursor forward one character. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> ### Edit Input These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> | **command (Mac)** | **command (Windows)** | **description** | | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. | | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. | | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | ### Select choices These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true. | **command** | **description** | | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. | | <kbd>i</kbd> | Invert the current selection of choices. | | <kbd>g</kbd> | Toggle the current choice group. | <br> ### Hide/show choices | **command** | **description** | | ------------------------------- | ---------------------------------------------- | | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. | | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. | <br> ### Move/lock Pointer | **command** | **description** | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>up</kbd> | Move the pointer up. | | <kbd>down</kbd> | Move the pointer down. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. | | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). | | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). | <br> | **command (Mac)** | **command (Windows)** | **description** | | -------------------------------- | --------------------- | ---------------------------------------------------------- | | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. | | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. | <br> ## ❯ Release History Please see [CHANGELOG.md](CHANGELOG.md). ## ❯ Performance ### System specs MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB. ### Load time Time it takes for the module to load the first time (average of 3 runs): ``` enquirer: 4.013ms inquirer: 286.717ms ``` <br> ## ❯ About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Todo We're currently working on documentation for the following items. Please star and watch the repository for updates! * [ ] Customizing symbols * [ ] Customizing styles (palette) * [ ] Customizing rendered input * [ ] Customizing returned values * [ ] Customizing key bindings * [ ] Question validation * [ ] Choice validation * [ ] Skipping questions * [ ] Async choices * [ ] Async timers: loaders, spinners and other animations * [ ] Links to examples </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ```sh $ yarn && yarn test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> #### Contributors | **Commits** | **Contributor** | | --- | --- | | 283 | [jonschlinkert](https://github.com/jonschlinkert) | | 82 | [doowb](https://github.com/doowb) | | 32 | [rajat-sr](https://github.com/rajat-sr) | | 20 | [318097](https://github.com/318097) | | 15 | [g-plane](https://github.com/g-plane) | | 12 | [pixelass](https://github.com/pixelass) | | 5 | [adityavyas611](https://github.com/adityavyas611) | | 5 | [satotake](https://github.com/satotake) | | 3 | [tunnckoCore](https://github.com/tunnckoCore) | | 3 | [Ovyerus](https://github.com/Ovyerus) | | 3 | [sw-yx](https://github.com/sw-yx) | | 2 | [DanielRuf](https://github.com/DanielRuf) | | 2 | [GabeL7r](https://github.com/GabeL7r) | | 1 | [AlCalzone](https://github.com/AlCalzone) | | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) | | 1 | [danieldelcore](https://github.com/danieldelcore) | | 1 | [ImgBotApp](https://github.com/ImgBotApp) | | 1 | [jsonkao](https://github.com/jsonkao) | | 1 | [knpwrs](https://github.com/knpwrs) | | 1 | [yeskunall](https://github.com/yeskunall) | | 1 | [mischah](https://github.com/mischah) | | 1 | [renarsvilnis](https://github.com/renarsvilnis) | | 1 | [sbugert](https://github.com/sbugert) | | 1 | [stephencweiss](https://github.com/stephencweiss) | | 1 | [skellock](https://github.com/skellock) | | 1 | [whxaxes](https://github.com/whxaxes) | #### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) #### Credit Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts. #### License Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 (2020, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 10. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). [![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). # is-core-module <sup>[![Version Badge][2]][1]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module [codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module [actions-url]: https://github.com/inspect-js/is-core-module/actions <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. # ShellJS - Unix shell commands for Node.js [![Travis](https://img.shields.io/travis/shelljs/shelljs/master.svg?style=flat-square&label=unix)](https://travis-ci.org/shelljs/shelljs) [![AppVeyor](https://img.shields.io/appveyor/ci/shelljs/shelljs/master.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/shelljs/shelljs/branch/master) [![Codecov](https://img.shields.io/codecov/c/github/shelljs/shelljs/master.svg?style=flat-square&label=coverage)](https://codecov.io/gh/shelljs/shelljs) [![npm version](https://img.shields.io/npm/v/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) [![npm downloads](https://img.shields.io/npm/dm/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! ShellJS is proudly tested on every node release since `v4`! The project is [unit-tested](http://travis-ci.org/shelljs/shelljs) and battle-tested in projects like: + [Firebug](http://getfirebug.com/) - Firefox's infamous debugger + [JSHint](http://jshint.com) & [ESLint](http://eslint.org/) - popular JavaScript linters + [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers + [Yeoman](http://yeoman.io/) - Web application stack and development tool + [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + And [many more](https://npmjs.org/browse/depended/shelljs). If you have feedback, suggestions, or need help, feel free to post in our [issue tracker](https://github.com/shelljs/shelljs/issues). Think ShellJS is cool? Check out some related projects in our [Wiki page](https://github.com/shelljs/shelljs/wiki)! Upgrading from an older version? Check out our [breaking changes](https://github.com/shelljs/shelljs/wiki/Breaking-Changes) page to see what changes to watch out for while upgrading. ## Command line use If you just want cross platform UNIX commands, checkout our new project [shelljs/shx](https://github.com/shelljs/shx), a utility to expose `shelljs` to the command line. For example: ``` $ shx mkdir -p foo $ shx touch foo/bar.txt $ shx rm -rf foo ``` ## Plugin API ShellJS now supports third-party plugins! You can learn more about using plugins and writing your own ShellJS commands in [the wiki](https://github.com/shelljs/shelljs/wiki/Using-ShellJS-Plugins). ## A quick note about the docs For documentation on all the latest features, check out our [README](https://github.com/shelljs/shelljs). To read docs that are consistent with the latest release, check out [the npm page](https://www.npmjs.com/package/shelljs) or [shelljs.org](http://documentup.com/shelljs/shelljs). ## Installing Via npm: ```bash $ npm install [-g] shelljs ``` ## Examples ```javascript var shell = require('shelljs'); if (!shell.which('git')) { shell.echo('Sorry, this script requires git'); shell.exit(1); } // Copy files to release dir shell.rm('-rf', 'out/Release'); shell.cp('-R', 'stuff/', 'out/Release'); // Replace macros in each .js file shell.cd('lib'); shell.ls('*.js').forEach(function (file) { shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file); shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); shell.cd('..'); // Run external tool synchronously if (shell.exec('git commit -am "Auto-commit"').code !== 0) { shell.echo('Error: Git commit failed'); shell.exit(1); } ``` ## Exclude options If you need to pass a parameter that looks like an option, you can do so like: ```js shell.grep('--', '-v', 'path/to/file'); // Search for "-v", no grep options shell.cp('-R', '-dir', 'outdir'); // If already using an option, you're done ``` ## Global vs. Local We no longer recommend using a global-import for ShellJS (i.e. `require('shelljs/global')`). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution. Instead, we recommend a local import (standard for npm packages): ```javascript var shell = require('shelljs'); shell.echo('hello world'); ``` <!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED --> ## Command reference All commands run synchronously, unless otherwise stated. All commands accept standard bash globbing characters (`*`, `?`, etc.), compatible with the [node `glob` module](https://github.com/isaacs/node-glob). For less-commonly used commands and features, please check out our [wiki page](https://github.com/shelljs/shelljs/wiki). ### cat([options,] file [, file ...]) ### cat([options,] file_array) Available options: + `-n`: number all output lines Examples: ```javascript var str = cat('file*.txt'); var str = cat('file1', 'file2'); var str = cat(['file1', 'file2']); // same as above ``` Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). ### cd([dir]) Changes to directory `dir` for the duration of the script. Changes to home directory if no argument is supplied. ### chmod([options,] octal_mode || octal_string, file) ### chmod([options,] symbolic_mode, file) Available options: + `-v`: output a diagnostic for every file processed + `-c`: like verbose, but report only when a change is made + `-R`: change files and directories recursively Examples: ```javascript chmod(755, '/Users/brandon'); chmod('755', '/Users/brandon'); // same as above chmod('u+x', '/Users/brandon'); chmod('-R', 'a-w', '/Users/brandon'); ``` Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + In symbolic modes, `a-r` and `-r` are identical. No consideration is given to the `umask`. + There is no "quiet" option, since default behavior is to run silent. ### cp([options,] source [, source ...], dest) ### cp([options,] source_array, dest) Available options: + `-f`: force (default behavior) + `-n`: no-clobber + `-u`: only copy if `source` is newer than `dest` + `-r`, `-R`: recursive + `-L`: follow symlinks + `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` Copies files. ### pushd([options,] [dir | '-N' | '+N']) Available options: + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. Examples: ```javascript // process.cwd() === '/usr' pushd('/etc'); // Returns /etc /usr pushd('+1'); // Returns /usr /etc ``` Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. ### popd([options,] ['-N' | '+N']) Available options: + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. Examples: ```javascript echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(); // '/usr' echo(process.cwd()); // '/usr' ``` When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. ### dirs([options | '+N' | '-N']) Available options: + `-c`: Clears the directory stack by deleting all of the elements. + `-q`: Supresses output to the console. Arguments: + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. See also: `pushd`, `popd` ### echo([options,] string [, string ...]) Available options: + `-e`: interpret backslash escapes (default) + `-n`: remove trailing newline from output Examples: ```javascript echo('hello world'); var str = echo('hello world'); echo('-n', 'no newline at end'); ``` Prints `string` to stdout, and returns string with additional utility methods like `.to()`. ### exec(command [, options] [, callback]) Available options: + `async`: Asynchronous execution. If a callback is provided, it will be set to `true`, regardless of the passed value (default: `false`). + `silent`: Do not echo program output to console (default: `false`). + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and what is written to stdout and stderr when not in silent mode (default: `'utf8'`). + and any option available to Node.js's [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) Examples: ```javascript var version = exec('node --version', {silent:true}).stdout; var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... do something with data ... */ }); exec('some_long_running_process', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); }); ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process object, and the `callback` receives the arguments `(code, stdout, stderr)`. Not seeing the behavior you want? `exec()` runs everything through `sh` by default (or `cmd.exe` on Windows), which differs from `bash`. If you need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. ### find(path [, path ...]) ### find(path_array) Examples: ```javascript find('src', 'lib'); find(['src', 'lib']); // same as above find('.').filter(function(file) { return file.match(/\.js$/); }); ``` Returns array of all files (however deep) in the given paths. The main difference from `ls('-R', path)` is that the resulting file names include the base directories (e.g., `lib/resources/file1` instead of just `file1`). ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Invert `regex_filter` (only print non-matching lines). + `-l`: Print only filenames of matching files. + `-i`: Ignore case. Examples: ```javascript grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the file that match the given `regex_filter`. ### head([{'-n': \<num\>},] file [, file ...]) ### head([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the first `<num>` lines of the files Examples: ```javascript var str = head({'-n': 1}, 'file*.txt'); var str = head('file1', 'file2'); var str = head(['file1', 'file2']); // same as above ``` Read the start of a file. ### ln([options,] source, dest) Available options: + `-s`: symlink + `-f`: force Examples: ```javascript ln('file', 'newlink'); ln('-sf', 'file', 'existing'); ``` Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. ### ls([options,] [path, ...]) ### ls([options,] path_array) Available options: + `-R`: recursive + `-A`: all files (include files beginning with `.`, except for `.` and `..`) + `-L`: follow symlinks + `-d`: list directories themselves, not their contents + `-l`: list objects representing each file, each with fields containing `ls -l` output fields. See [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) for more info Examples: ```javascript ls('projs/*.js'); ls('-R', '/users/me', '/tmp'); ls('-R', ['/users/me', '/tmp']); // same as above ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} ``` Returns array of files in the given `path`, or files in the current directory if no `path` is provided. ### mkdir([options,] dir [, dir ...]) ### mkdir([options,] dir_array) Available options: + `-p`: full path (and create intermediate directories, if necessary) Examples: ```javascript mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above ``` Creates directories. ### mv([options ,] source [, source ...], dest') ### mv([options ,] source_array, dest') Available options: + `-f`: force (default behavior) + `-n`: no-clobber Examples: ```javascript mv('-n', 'file', 'dir/'); mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` Moves `source` file(s) to `dest`. ### pwd() Returns the current directory. ### rm([options,] file [, file ...]) ### rm([options,] file_array) Available options: + `-f`: force + `-r, -R`: recursive Examples: ```javascript rm('-rf', '/tmp/*'); rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` Removes files. ### sed([options,] search_regex, replacement, file [, file ...]) ### sed([options,] search_regex, replacement, file_array) Available options: + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ Examples: ```javascript sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); ``` Reads an input string from `file`s, and performs a JavaScript `replace()` on the input using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. Note: Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified using the `$n` syntax: ```javascript sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); ``` ### set(options) Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) + `+/-f`: disable filename expansion (globbing) Examples: ```javascript set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" ``` Sets global configuration variables. ### sort([options,] file [, file ...]) ### sort([options,] file_array) Available options: + `-r`: Reverse the results + `-n`: Compare according to numerical value Examples: ```javascript sort('foo.txt', 'bar.txt'); sort('-r', 'foo.txt'); ``` Return the contents of the `file`s, sorted line-by-line. Sorting multiple files mixes their content (just as unix `sort` does). ### tail([{'-n': \<num\>},] file [, file ...]) ### tail([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the last `<num>` lines of `file`s Examples: ```javascript var str = tail({'-n': 1}, 'file*.txt'); var str = tail('file1', 'file2'); var str = tail(['file1', 'file2']); // same as above ``` Read the end of a `file`. ### tempdir() Examples: ```javascript var tmp = tempdir(); // "/tmp" for most *nix platforms ``` Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). ### test(expression) Available expression primaries: + `'-b', 'path'`: true if path is a block device + `'-c', 'path'`: true if path is a character device + `'-d', 'path'`: true if path is a directory + `'-e', 'path'`: true if path exists + `'-f', 'path'`: true if path is a regular file + `'-L', 'path'`: true if path is a symbolic link + `'-p', 'path'`: true if path is a pipe (FIFO) + `'-S', 'path'`: true if path is a socket Examples: ```javascript if (test('-d', path)) { /* do something with dir */ }; if (!test('-f', path)) continue; // skip if it's a regular file ``` Evaluates `expression` using the available primaries and returns corresponding value. ### ShellString.prototype.to(file) Examples: ```javascript cat('input.txt').to('output.txt'); ``` Analogous to the redirection operator `>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix redirections, `to()` will overwrite any existing file!_ ### ShellString.prototype.toEnd(file) Examples: ```javascript cat('input.txt').toEnd('output.txt'); ``` Analogous to the redirect-and-append operator `>>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). ### touch([options,] file [, file ...]) ### touch([options,] file_array) Available options: + `-a`: Change only the access time + `-c`: Do not create any files + `-m`: Change only the modification time + `-d DATE`: Parse `DATE` and use it instead of current time + `-r FILE`: Use `FILE`'s times instead of current time Examples: ```javascript touch('source.js'); touch('-c', '/path/to/some/dir/source.js'); touch({ '-r': FILE }, '/path/to/some/dir/source.js'); ``` Update the access and modification times of each `FILE` to the current time. A `FILE` argument that does not exist is created empty, unless `-c` is supplied. This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). ### uniq([options,] [input, [output]]) Available options: + `-i`: Ignore case while comparing + `-c`: Prefix lines by the number of occurrences + `-d`: Only print duplicate lines, one for each group of identical lines Examples: ```javascript uniq('foo.txt'); uniq('-i', 'foo.txt'); uniq('-cd', 'foo.txt', 'bar.txt'); ``` Filter adjacent matching lines from `input`. ### which(command) Examples: ```javascript var nodeExec = which('node'); ``` Searches for `command` in the system's `PATH`. On Windows, this uses the `PATHEXT` variable to append the extension if it's not already executable. Returns string containing the absolute path to `command`. ### exit(code) Exits the current process with the given exit `code`. ### error() Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise. **Note**: do not rely on the return value to be an error message. If you need the last error message, use the `.stderr` attribute from the last command's return value instead. ### ShellString(str) Examples: ```javascript var foo = ShellString('hello world'); ``` Turns a regular string into a string-like object similar to what each command returns. This has special methods, like `.to()` and `.toEnd()`. ### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to `process.env`. ### Pipes Examples: ```javascript grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); echo('files with o\'s in the name:\n' + ls().grep('o')); cat('test.js').exec('node'); // pipe to exec() call ``` Commands can send their output to another command in a pipe-like fashion. `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand side of a pipe. Pipes can be chained. ## Configuration ### config.silent Example: ```javascript var sh = require('shelljs'); var silentState = sh.config.silent; // save old silent state sh.config.silent = true; /* ... */ sh.config.silent = silentState; // restore old silent state ``` Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` If `true`, the script will throw a Javascript error when any shell.js command encounters an error. Default is `false`. This is analogous to Bash's `set -e`. ### config.verbose Example: ```javascript config.verbose = true; // or set('-v'); cd('dir/'); rm('-rf', 'foo.txt', 'bar.txt'); exec('echo hello'); ``` Will print each command as follows: ``` cd dir/ rm -rf foo.txt bar.txt exec echo hello ``` ### config.globOptions Example: ```javascript config.globOptions = {nodir: true}; ``` Use this value for calls to `glob.sync()` instead of the default options. ### config.reset() Example: ```javascript var shell = require('shelljs'); // Make changes to shell.config, and do stuff... /* ... */ shell.config.reset(); // reset to original state // Do more stuff, but with original settings /* ... */ ``` Reset `shell.config` to the defaults: ```javascript { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, } ``` ## Team | [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Brandon Freitag](https://avatars1.githubusercontent.com/u/5988055?v=3&s=130)](http://github.com/freitagbr) | |:---:|:---:| | [Nate Fischer](https://github.com/nfischer) | [Brandon Freitag](http://github.com/freitagbr) | Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # flatted [![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) ![snow flake](./flatted.jpg) <sup>**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**</sup> ## Announcement 📣 There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general. The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax. However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍 - - - A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). Now available also for **[PHP](./php/flatted.php)**. ```js npm i flatted ``` Usable via [CDN](https://unpkg.com/flatted) or as regular module. ```js // ESM import {parse, stringify, toJSON, fromJSON} from 'flatted'; // CJS const {parse, stringify, toJSON, fromJSON} = require('flatted'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}] ``` ## toJSON and fromJSON If you'd like to implicitly survive JSON serialization, these two helpers helps: ```js import {toJSON, fromJSON} from 'flatted'; class RecursiveMap extends Map { static fromJSON(any) { return new this(fromJSON(any)); } toJSON() { return toJSON([...this.entries()]); } } const recursive = new RecursiveMap; const same = {}; same.same = same; recursive.set('same', same); const asString = JSON.stringify(recursive); const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); asMap.get('same') === asMap.get('same').same; // true ``` ## Flatted VS JSON As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. ### New in V1: Exact same JSON API * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. ### Compatibility All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. ### How does it work ? While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` Once parsed, all indexes will be replaced through the flattened collection. <sup><sub>`*` represented as string to avoid conflicts with numbers</sub></sup> ```js // logic example var a = [{one: 1}, {two: '2'}]; a[0].a = a; // a is the main object, will be at index '0' // {one: 1} is the second object, index '1' // {two: '2'} the third, in '2', and it has a string // which will be found at index '3' Flatted.stringify(a); // [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] // a[one,two] {one: 1, a} {two: '2'} '2' ``` ## assemblyscript-temporal An implementation of temporal within AssemblyScript, with an initial focus on non-timezone-aware classes and functionality. ### Why? AssemblyScript has minimal `Date` support, however, the JS Date API itself is terrible and people tend not to use it that often. As a result libraries like moment / luxon have become staple replacements. However, there is now a [relatively mature TC39 proposal](https://github.com/tc39/proposal-temporal) that adds greatly improved date support to JS. The goal of this project is to implement Temporal for AssemblyScript. ### Usage This library currently supports the following types: #### `PlainDateTime` A `PlainDateTime` represents a calendar date and wall-clock time that does not carry time zone information, e.g. December 7th, 1995 at 3:00 PM (in the Gregorian calendar). For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindatetime.html), this implementation follows the specification as closely as possible. You can create a `PlainDateTime` from individual components, a string or an object literal: ```javascript datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.year; // 2019; datetime.month; // 11; // ... datetime.nanosecond; // 789; datetime = PlainDateTime.from("1976-11-18T12:34:56"); datetime.toString(); // "1976-11-18T12:34:56" datetime = PlainDateTime.from({ year: 1966, month: 3, day: 3 }); datetime.toString(); // "1966-03-03T00:00:00" ``` There are various ways you can manipulate a date: ```javascript // use 'with' to copy a date but with various property values overriden datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.with({ year: 2019 }).toString(); // "2019-11-18T15:23:30.123456789" // use 'add' or 'substract' to add / subtract a duration datetime = PlainDateTime.from("2020-01-12T15:00"); datetime.add({ months: 1 }).toString(); // "2020-02-12T15:00:00"); // add / subtract support Duration objects or object literals datetime.add(new Duration(1)).toString(); // "2021-01-12T15:00:00"); ``` You can compare dates and check for equality ```javascript dt1 = PlainDateTime.from("1976-11-18"); dt2 = PlainDateTime.from("2019-10-29"); PlainDateTime.compare(dt1, dt1); // 0 PlainDateTime.compare(dt1, dt2); // -1 dt1.equals(dt1); // true ``` Currently `PlainDateTime` only supports the ISO 8601 (Gregorian) calendar. #### `PlainDate` A `PlainDate` object represents a calendar date that is not associated with a particular time or time zone, e.g. August 24th, 2006. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindate.html), this implementation follows the specification as closely as possible. The `PlainDate` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainTime` A `PlainTime` object represents a wall-clock time that is not associated with a particular date or time zone, e.g. 7:39 PM. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaintime.html), this implementation follows the specification as closely as possible. The `PlainTime` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainMonthDay` A date without a year component. This is useful to express things like "Bastille Day is on the 14th of July". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainmonthday.html) , this implementation follows the specification as closely as possible. ```javascript const monthDay = PlainMonthDay.from({ month: 7, day: 14 }); // => 07-14 const date = monthDay.toPlainDate({ year: 2030 }); // => 2030-07-14 date.dayOfWeek; // => 7 ``` The `PlainMonthDay` API is almost identical to `PlainDateTime`, so see above for more API usage examples. #### `PlainYearMonth` A date without a day component. This is useful to express things like "the October 2020 meeting". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainyearmonth.html) , this implementation follows the specification as closely as possible. The `PlainYearMonth` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `now` The `now` object has several methods which give information about the current time and date. ```javascript dateTime = now.plainDateTimeISO(); dateTime.toString(); // 2021-04-01T12:05:47.357 ``` ## Contributing This project is open source, MIT licensed and your contributions are very much welcomed. There is a [brief document that outlines implementation progress and priorities](./development.md). <a name="table"></a> # Table > Produces a string that represents array data in a text table. [![Github action status](https://github.com/gajus/table/actions/workflows/main.yml/badge.svg)](https://github.com/gajus/table/actions) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) [![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical) [![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas) * [Table](#table) * [Features](#table-features) * [Install](#table-install) * [Usage](#table-usage) * [API](#table-api) * [table](#table-api-table-1) * [createStream](#table-api-createstream) * [getBorderCharacters](#table-api-getbordercharacters) ![Demo of table displaying a list of missions to the Moon.](./.README/demo.png) <a name="table-features"></a> ## Features * Works with strings containing [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) characters. * Works with strings containing [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). * Configurable border characters. * Configurable content alignment per column. * Configurable content padding per column. * Configurable column width. * Text wrapping. <a name="table-install"></a> ## Install ```bash npm install table ``` [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) [![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) <a name="table-usage"></a> ## Usage ```js import { table } from 'table'; // Using commonjs? // const { table } = require('table'); const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; console.log(table(data)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ ``` <a name="table-api"></a> ## API <a name="table-api-table-1"></a> ### table Returns the string in the table format **Parameters:** - **_data_:** The data to display - Type: `any[][]` - Required: `true` - **_config_:** Table configuration - Type: `object` - Required: `false` <a name="table-api-table-1-config-border"></a> ##### config.border Type: `{ [type: string]: string }`\ Default: `honeywell` [template](#getbordercharacters) Custom borders. The keys are any of: - `topLeft`, `topRight`, `topBody`,`topJoin` - `bottomLeft`, `bottomRight`, `bottomBody`, `bottomJoin` - `joinLeft`, `joinRight`, `joinBody`, `joinJoin` - `bodyLeft`, `bodyRight`, `bodyJoin` - `headerJoin` ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: { topBody: `─`, topJoin: `┬`, topLeft: `┌`, topRight: `┐`, bottomBody: `─`, bottomJoin: `┴`, bottomLeft: `└`, bottomRight: `┘`, bodyLeft: `│`, bodyRight: `│`, bodyJoin: `│`, joinBody: `─`, joinLeft: `├`, joinRight: `┤`, joinJoin: `┼` } }; console.log(table(data, config)); ``` ``` ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ ``` <a name="table-api-table-1-config-drawverticalline"></a> ##### config.drawVerticalLine Type: `(lineIndex: number, columnCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a vertical line. This callback is called for each vertical border of the table. If the table has `n` columns, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawVerticalLine: (lineIndex, columnCount) => { return lineIndex === 0 || lineIndex === columnCount; } }; console.log(table(data, config)); ``` ``` ╔════════════╗ ║ 0A 0B 0C ║ ╟────────────╢ ║ 1A 1B 1C ║ ╟────────────╢ ║ 2A 2B 2C ║ ╟────────────╢ ║ 3A 3B 3C ║ ╟────────────╢ ║ 4A 4B 4C ║ ╚════════════╝ ``` <a name="table-api-table-1-config-drawhorizontalline"></a> ##### config.drawHorizontalLine Type: `(lineIndex: number, rowCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a horizontal line. This callback is called for each horizontal border of the table. If the table has `n` rows, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. If the table has `n` rows and contains the header, then the range will be `[0, n+1]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawHorizontalLine: (lineIndex, rowCount) => { return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount - 1 || lineIndex === rowCount; } }; console.log(table(data, config)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ║ 2A │ 2B │ 2C ║ ║ 3A │ 3B │ 3C ║ ╟────┼────┼────╢ ║ 4A │ 4B │ 4C ║ ╚════╧════╧════╝ ``` <a name="table-api-table-1-config-singleline"></a> ##### config.singleLine Type: `boolean`\ Default: `false` If `true`, horizontal lines inside the table are not drawn. This option also overrides the `config.drawHorizontalLine` if specified. ```js const data = [ ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], ]; const config = { singleLine: true }; console.log(table(data, config)); ``` ``` ╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ ║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ ║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ ║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ ║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ ║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ ║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ ╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ ``` <a name="table-api-table-1-config-columns"></a> ##### config.columns Type: `Column[] | { [columnIndex: number]: Column }` Column specific configurations. <a name="table-api-table-1-config-columns-config-columns-width"></a> ###### config.columns[*].width Type: `number`\ Default: the maximum cell widths of the column Column width (excluding the paddings). ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: { 1: { width: 10 } } }; console.log(table(data, config)); ``` ``` ╔════╤════════════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────────────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────────────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════════════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-alignment"></a> ###### config.columns[*].alignment Type: `'center' | 'justify' | 'left' | 'right'`\ Default: `'left'` Cell content horizontal alignment ```js const data = [ ['0A', '0B', '0C', '0D 0E 0F'], ['1A', '1B', '1C', '1D 1E 1F'], ['2A', '2B', '2C', '2D 2E 2F'], ]; const config = { columnDefault: { width: 10, }, columns: [ { alignment: 'left' }, { alignment: 'center' }, { alignment: 'right' }, { alignment: 'justify' } ], }; console.log(table(data, config)); ``` ``` ╔════════════╤════════════╤════════════╤════════════╗ ║ 0A │ 0B │ 0C │ 0D 0E 0F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C │ 1D 1E 1F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C │ 2D 2E 2F ║ ╚════════════╧════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-verticalalignment"></a> ###### config.columns[*].verticalAlignment Type: `'top' | 'middle' | 'bottom'`\ Default: `'top'` Cell content vertical alignment ```js const data = [ ['A', 'B', 'C', 'DEF'], ]; const config = { columnDefault: { width: 1, }, columns: [ { verticalAlignment: 'top' }, { verticalAlignment: 'middle' }, { verticalAlignment: 'bottom' }, ], }; console.log(table(data, config)); ``` ``` ╔═══╤═══╤═══╤═══╗ ║ A │ │ │ D ║ ║ │ B │ │ E ║ ║ │ │ C │ F ║ ╚═══╧═══╧═══╧═══╝ ``` <a name="table-api-table-1-config-columns-config-columns-paddingleft"></a> ###### config.columns[*].paddingLeft Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the left. <a name="table-api-table-1-config-columns-config-columns-paddingright"></a> ###### config.columns[*].paddingRight Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the right. The `paddingLeft` and `paddingRight` options do not count on the column width. So the column has `width = 5`, `paddingLeft = 2` and `paddingRight = 2` will have the total width is `9`. ```js const data = [ ['0A', 'AABBCC', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: [ { paddingLeft: 3 }, { width: 2, paddingRight: 3 } ] }; console.log(table(data, config)); ``` ``` ╔══════╤══════╤════╗ ║ 0A │ AA │ 0C ║ ║ │ BB │ ║ ║ │ CC │ ║ ╟──────┼──────┼────╢ ║ 1A │ 1B │ 1C ║ ╟──────┼──────┼────╢ ║ 2A │ 2B │ 2C ║ ╚══════╧══════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-truncate"></a> ###### config.columns[*].truncate Type: `number`\ Default: `Infinity` The number of characters is which the content will be truncated. To handle a content that overflows the container width, `table` package implements [text wrapping](#config.columns[*].wrapWord). However, sometimes you may want to truncate content that is too long to be displayed in the table. ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20, truncate: 100 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convall… ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-wrapword"></a> ###### config.columns[*].wrapWord Type: `boolean`\ Default: `false` The `table` package implements auto text wrapping, i.e., text that has the width greater than the container width will be separated into multiple lines at the nearest space or one of the special characters: `\|/_.,;-`. When `wrapWord` is `false`: ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convallis ║ ║ dapibus. Nunc venena ║ ║ tis tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` When `wrapWord` is `true`: ``` ╔══════════════════════╗ ║ Lorem ipsum dolor ║ ║ sit amet, ║ ║ consectetur ║ ║ adipiscing elit. ║ ║ Phasellus pulvinar ║ ║ nibh sed mauris ║ ║ convallis dapibus. ║ ║ Nunc venenatis ║ ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columndefault"></a> ##### config.columnDefault Type: `Column`\ Default: `{}` The default configuration for all columns. Column-specific settings will overwrite the default values. <a name="table-api-table-1-config-header"></a> ##### config.header Type: `object` Header configuration. *Deprecated in favor of the new spanning cells API.* The header configuration inherits the most of the column's, except: - `content` **{string}**: the header content. - `width:` calculate based on the content width automatically. - `alignment:` `center` be default. - `verticalAlignment:` is not supported. - `config.border.topJoin` will be `config.border.topBody` for prettier. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ]; const config = { columnDefault: { width: 10, }, header: { alignment: 'center', content: 'THE HEADER\nThis is the table about something', }, } console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════╗ ║ THE HEADER ║ ║ This is the table about something ║ ╟────────────┬────────────┬────────────╢ ║ 0A │ 0B │ 0C ║ ╟────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C ║ ╟────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C ║ ╚════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-spanningcells"></a> ##### config.spanningCells Type: `SpanningCellConfig[]` Spanning cells configuration. The configuration should be straightforward: just specify an array of minimal cell configurations including the position of top-left cell and the number of columns and/or rows will be expanded from it. The content of overlap cells will be ignored to make the `data` shape be consistent. By default, the configuration of column that the top-left cell belongs to will be applied to the whole spanning cell, except: * The `width` will be summed up of all spanning columns. * The `paddingRight` will be received from the right-most column intentionally. Advances customized column-like styles can be configurable to each spanning cell to overwrite the default behavior. ```js const data = [ ['Test Coverage Report', '', '', '', '', ''], ['Module', 'Component', 'Test Cases', 'Failures', 'Durations', 'Success Rate'], ['Services', 'User', '50', '30', '3m 7s', '60.0%'], ['', 'Payment', '100', '80', '7m 15s', '80.0%'], ['Subtotal', '', '150', '110', '10m 22s', '73.3%'], ['Controllers', 'User', '24', '18', '1m 30s', '75.0%'], ['', 'Payment', '30', '24', '50s', '80.0%'], ['Subtotal', '', '54', '42', '2m 20s', '77.8%'], ['Total', '', '204', '152', '12m 42s', '74.5%'], ]; const config = { columns: [ { alignment: 'center', width: 12 }, { alignment: 'center', width: 10 }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' } ], spanningCells: [ { col: 0, row: 0, colSpan: 6 }, { col: 0, row: 2, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 4, colSpan: 2, alignment: 'right'}, { col: 0, row: 5, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 7, colSpan: 2, alignment: 'right' }, { col: 0, row: 8, colSpan: 2, alignment: 'right' } ], }; console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Test Coverage Report ║ ╟──────────────┬────────────┬────────────┬──────────┬───────────┬──────────────╢ ║ Module │ Component │ Test Cases │ Failures │ Durations │ Success Rate ║ ╟──────────────┼────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 50 │ 30 │ 3m 7s │ 60.0% ║ ║ Services ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 100 │ 80 │ 7m 15s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 150 │ 110 │ 10m 22s │ 73.3% ║ ╟──────────────┬────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 24 │ 18 │ 1m 30s │ 75.0% ║ ║ Controllers ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 30 │ 24 │ 50s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 54 │ 42 │ 2m 20s │ 77.8% ║ ╟───────────────────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Total │ 204 │ 152 │ 12m 42s │ 74.5% ║ ╚═══════════════════════════╧════════════╧══════════╧═══════════╧══════════════╝ ``` <a name="table-api-createstream"></a> ### createStream `table` package exports `createStream` function used to draw a table and append rows. **Parameter:** - _**config:**_ the same as `table`'s, except `config.columnDefault.width` and `config.columnCount` must be provided. ```js import { createStream } from 'table'; const config = { columnDefault: { width: 50 }, columnCount: 1 }; const stream = createStream(config); setInterval(() => { stream.write([new Date()]); }, 500); ``` ![Streaming current date.](./.README/api/stream/streaming.gif) `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { createStream } from 'table'; import _ from 'lodash'; const config = { columnDefault: { width: 50 }, columnCount: 3, columns: [ { width: 10, alignment: 'right' }, { alignment: 'center' }, { width: 10 } ] }; const stream = createStream(config); let i = 0; setInterval(() => { let random; random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/api/stream/streaming-random.gif) <a name="table-api-getbordercharacters"></a> ### getBorderCharacters **Parameter:** - **_template_** - Type: `'honeywell' | 'norc' | 'ramac' | 'void'` - Required: `true` You can load one of the predefined border templates using `getBorderCharacters` function. ```js import { table, getBorderCharacters } from 'table'; const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: getBorderCharacters(`name of the template`) }; console.log(table(data, config)); ``` ``` # honeywell ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ # norc ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ # ramac (ASCII; for use in terminals that do not support Unicode characters) +----+----+----+ | 0A | 0B | 0C | |----|----|----| | 1A | 1B | 1C | |----|----|----| | 2A | 2B | 2C | +----+----+----+ # void (no borders; see "borderless table" section of the documentation) 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` Raise [an issue](https://github.com/gajus/table/issues) if you'd like to contribute a new border template. <a name="table-api-getbordercharacters-borderless-table"></a> #### Borderless Table Simply using `void` border character template creates a table with a lot of unnecessary spacing. To create a more pleasant to the eye table, reset the padding and remove the joining rows, e.g. ```js const output = table(data, { border: getBorderCharacters('void'), columnDefault: { paddingLeft: 0, paddingRight: 1 }, drawHorizontalLine: () => false } ); console.log(output); ``` ``` 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) ### Status: Work in progress Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js const rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ ## Test Strategy - tests are copied from the [polyfill implementation](https://github.com/tc39/proposal-temporal/tree/main/polyfill/test) - tests should be removed if they relate to features that do not make sense for TS/AS, i.e. tests that validate the shape of an object do not make sense in a language with compile-time type checking - tests that fail because a feature has not been implemented yet should be left as failures. JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation Node.js version 8 and up: `$ npm install cross-spawn` Node.js version 7 and under: `$ npm install cross-spawn@6` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) ## Timezone support In order to provide support for timezones, without relying on the JavaScript host or any other time-zone aware environment, this library makes use of teh IANA Timezone Database directly: https://www.iana.org/time-zones The database files are parsed by the scripts in this folder, which emit AssemblyScript code which is used to process the various rules at runtime. bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.mjs': '/absolute/path/to/interpret/mjs-stub.js', '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', 'sucrase/register/ts', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', 'sucrase/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # line-column [![Build Status](https://travis-ci.org/io-monad/line-column.svg?branch=master)](https://travis-ci.org/io-monad/line-column) [![Coverage Status](https://coveralls.io/repos/github/io-monad/line-column/badge.svg?branch=master)](https://coveralls.io/github/io-monad/line-column?branch=master) [![npm version](https://badge.fury.io/js/line-column.svg)](https://badge.fury.io/js/line-column) Node module to convert efficiently index to/from line-column in a string. ## Install npm install line-column ## Usage ### lineColumn(str, options = {}) Returns a `LineColumnFinder` instance for given string `str`. #### Options | Key | Description | Default | | ------- | ----------- | ------- | | `origin` | The origin value of line number and column number | `1` | ### lineColumn(str, index) This is just a shorthand for `lineColumn(str).fromIndex(index)`. ### LineColumnFinder#fromIndex(index) Find line and column from index in the string. Parameters: - `index` - `number` Index in the string. (0-origin) Returns: - `{ line: x, col: y }` Found line number and column number. - `null` if the given index is out of range. ### LineColumnFinder#toIndex(line, column) Find index from line and column in the string. Parameters: - `line` - `number` Line number in the string. - `column` - `number` Column number in the string. or - `{ line: x, col: y }` - `Object` line and column numbers in the string.<br>A key name `column` can be used instead of `col`. or - `[ line, col ]` - `Array` line and column numbers in the string. Returns: - `number` Found index in the string. - `-1` if the given line or column is out of range. ## Example ```js var lineColumn = require("line-column"); var testString = [ "ABCDEFG\n", // line:0, index:0 "HIJKLMNOPQRSTU\n", // line:1, index:8 "VWXYZ\n", // line:2, index:23 "日本語の文字\n", // line:3, index:29 "English words" // line:4, index:36 ].join(""); // length:49 lineColumn(testString).fromIndex(3) // { line: 1, col: 4 } lineColumn(testString).fromIndex(33) // { line: 4, col: 5 } lineColumn(testString).toIndex(1, 4) // 3 lineColumn(testString).toIndex(4, 5) // 33 // Shorthand of .fromIndex (compatible with find-line-column) lineColumn(testString, 33) // { line:4, col: 5 } // Object or Array is also acceptable lineColumn(testString).toIndex({ line: 4, col: 5 }) // 33 lineColumn(testString).toIndex({ line: 4, column: 5 }) // 33 lineColumn(testString).toIndex([4, 5]) // 33 // You can cache it for the same string. It is so efficient. (See benchmark) var finder = lineColumn(testString); finder.fromIndex(33) // { line: 4, column: 5 } finder.toIndex(4, 5) // 33 // For 0-origin line and column numbers var oneOrigin = lineColumn(testString, { origin: 0 }); oneOrigin.fromIndex(33) // { line: 3, column: 4 } oneOrigin.toIndex(3, 4) // 33 ``` ## Testing npm test ## Benchmark The popular package [find-line-column](https://www.npmjs.com/package/find-line-column) provides the same "index to line-column" feature. Here is some benchmarking on `line-column` vs `find-line-column`. You can run this benchmark by `npm run benchmark`. See [benchmark/](benchmark/) for the source code. ``` long text + line-column (not cached) x 72,989 ops/sec ±0.83% (89 runs sampled) long text + line-column (cached) x 13,074,242 ops/sec ±0.32% (89 runs sampled) long text + find-line-column x 33,887 ops/sec ±0.54% (84 runs sampled) short text + line-column (not cached) x 1,636,766 ops/sec ±0.77% (82 runs sampled) short text + line-column (cached) x 21,699,686 ops/sec ±1.04% (82 runs sampled) short text + find-line-column x 382,145 ops/sec ±1.04% (85 runs sampled) ``` As you might have noticed, even not cached version of `line-column` is 2x - 4x faster than `find-line-column`, and cached version of `line-column` is remarkable 50x - 380x faster. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT (See LICENSE) # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` ## Enterprise support fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(low: `number`, high: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg"> &nbsp; # Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). [![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-%2307b4b9)](https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2Fap4lMFzfXF8Hzmh-Vz0WNxp_1jKiOa-h%23MCowBQYDK2VuAyEAcdefddRvDfI8iAuBpztm_J3qFucj8MDZoVs_2EcMTzU%3D) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv sponsors [<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv) ## Contributing More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). ## Documentation All documentation is available on the [Ajv website](https://ajv.js.org). Some useful site links: - [Getting started](https://ajv.js.org/guide/getting-started.html) - [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) - [API reference](https://ajv.js.org/api.html) - [Strict mode](https://ajv.js.org/strict-mode.html) - [Standalone validation code](https://ajv.js.org/standalone.html) - [Security considerations](https://ajv.js.org/security.html) - [Command line interface](https://ajv.js.org/packages/ajv-cli.html) - [Frequently Asked Questions](https://ajv.js.org/faq.html) ## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a> ## Performance Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus&#x2F;schemasafe|is-my-json-valid|djv|@cfworker&#x2F;json-schema|jsonschema&chd=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) - support of recursive references between schemas - correct string lengths for strings with unicode pairs - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) - NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) - meta-schema for JTD schemas - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) - supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current - [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) - [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) - [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items - [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords - [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) - additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords ## Install To install version 8: ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://runkit.com/npm/ajv In JavaScript: ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false, } const data = { foo: 1, bar: "abc" } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) ## Changes history See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) **Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) [Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](./LICENSE) # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config Shims used when bundling asc for browser usage. [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png [1]: https://travis-ci.org/litejs/natural-compare-lite [2]: https://coveralls.io/r/litejs/natural-compare-lite [npm package]: https://npmjs.org/package/natural-compare-lite [GitHub repo]: https://github.com/litejs/natural-compare-lite @version 1.4.0 @date 2015-10-26 @stability 3 - Stable Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2] =============== Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering". ```text Standard sorting: Natural order sorting: img1.png img1.png img10.png img2.png img12.png img10.png img2.png img12.png ``` String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function. ### Installation - In browser ```html <script src=min.natural-compare.js></script> ``` - In node.js: `npm install natural-compare-lite` ```javascript require("natural-compare-lite") ``` ### Usage ```javascript // Simple case sensitive example var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; a.sort(String.naturalCompare); // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] // Use wrapper function for case insensitivity a.sort(function(a, b){ return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); }) // In most cases we want to sort an array of objects var a = [ {"street":"350 5th Ave", "room":"A-1021"} , {"street":"350 5th Ave", "room":"A-21046-b"} ]; // sort by street, then by room a.sort(function(a, b){ return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); }) // When text transformation is needed (eg toLowerCase()), // it is best for performance to keep // transformed key in that object. // There are no need to do text transformation // on each comparision when sorting. var a = [ {"make":"Audi", "model":"A6"} , {"make":"Kia", "model":"Rio"} ]; // sort by make, then by model a.map(function(car){ car.sort_key = (car.make + " " + car.model).toLowerCase(); }) a.sort(function(a, b){ return String.naturalCompare(a.sort_key, b.sort_key); }) ``` - Works well with dates in ISO format eg "Rev 2012-07-26.doc". ### Custom alphabet It is possible to configure a custom alphabet to achieve a desired order. ```javascript // Estonian alphabet String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" ["t", "z", "x", "õ"].sort(String.naturalCompare) // ["z", "t", "õ", "x"] // Russian alphabet String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" ["Ё", "А", "Б"].sort(String.naturalCompare) // ["А", "Б", "Ё"] ``` External links -------------- - [GitHub repo][https://github.com/litejs/natural-compare-lite] - [jsperf test](http://jsperf.com/natural-sort-2/12) Licence ------- Copyright (c) 2012-2015 Lauri Rooden &lt;[email protected]&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) Like `chown -R`. Takes the same arguments as `fs.chown()` # assemblyscript-regex A regex engine for AssemblyScript. [AssemblyScript](https://www.assemblyscript.org/) is a new language, based on TypeScript, that runs on WebAssembly. AssemblyScript has a lightweight standard library, but lacks support for Regular Expression. The project fills that gap! This project exposes an API that mirrors the JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class: ```javascript const regex = new RegExp("fo*", "g"); const str = "table football, foul"; let match: Match | null = regex.exec(str); while (match != null) { // first iteration // match.index = 6 // match.matches[0] = "foo" // second iteration // match.index = 16 // match.matches[0] = "fo" match = regex.exec(str); } ``` ## Project status The initial focus of this implementation has been feature support and functionality over performance. It currently supports a sufficient number of regex features to be considered useful, including most character classes, common assertions, groups, alternations, capturing groups and quantifiers. The next phase of development will focussed on more extensive testing and performance. The project currently has reasonable unit test coverage, focussed on positive and negative test cases on a per-feature basis. It also includes a more exhaustive test suite with test cases borrowed from another regex library. ### Feature support Based on the classfication within the [MDN cheatsheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) **Character sets** - [x] . - [x] \d - [x] \D - [x] \w - [x] \W - [x] \s - [x] \S - [x] \t - [x] \r - [x] \n - [x] \v - [x] \f - [ ] [\b] - [ ] \0 - [ ] \cX - [x] \xhh - [x] \uhhhh - [ ] \u{hhhh} or \u{hhhhh} - [x] \ **Assertions** - [x] ^ - [x] $ - [ ] \b - [ ] \B **Other assertions** - [ ] x(?=y) Lookahead assertion - [ ] x(?!y) Negative lookahead assertion - [ ] (?<=y)x Lookbehind assertion - [ ] (?<!y)x Negative lookbehind assertion **Groups and ranges** - [x] x|y - [x] [xyz][a-c] - [x] [^xyz][^a-c] - [x] (x) capturing group - [ ] \n back reference - [ ] (?<Name>x) named capturing group - [x] (?:x) Non-capturing group **Quantifiers** - [x] x\* - [x] x+ - [x] x? - [x] x{n} - [x] x{n,} - [x] x{n,m} - [ ] x\*? / x+? / ... **RegExp** - [x] global - [ ] sticky - [x] case insensitive - [x] multiline - [x] dotAll - [ ] unicode ### Development This project is open source, MIT licenced and your contributions are very much welcomed. To get started, check out the repository and install dependencies: ``` $ npm install ``` A few general points about the tools and processes this project uses: - This project uses prettier for code formatting and eslint to provide additional syntactic checks. These are both run on `npm test` and as part of the CI build. - The unit tests are executed using [as-pect](https://github.com/jtenner/as-pect) - a native AssemblyScript test runner - The specification tests are within the `spec` folder. The `npm run test:generate` target transforms these tests into as-pect tests which execute as part of the standard build / test cycle - In order to support improved debugging you can execute this library as TypeScript (rather than WebAssembly), via the `npm run tsrun` target. # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0,4.1,4.2?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) # rechoir [![Build Status](https://secure.travis-ci.org/tkellen/js-rechoir.png)](http://travis-ci.org/tkellen/js-rechoir) > Require any supported file as a node module. [![NPM](https://nodei.co/npm/rechoir.png)](https://nodei.co/npm/rechoir/) ## What is it? This module, in conjunction with [interpret]-like objects can register any file type the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. ## API ### prepare(config, filepath, requireFrom) Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). `config` An [interpret]-like configuration object. `filepath` A file whose type you'd like to register a module loader for. `requireFrom` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. If calling this method is successful (aka: it doesn't throw), you can now require files of the type you requested natively. An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. If a loader is already registered, this will simply return `true`. **Note:** While rechoir will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. #### Usage ```js const config = require('interpret').extensions; const rechoir = require('rechoir'); rechoir.prepare(config, './test/fixtures/test.coffee'); rechoir.prepare(config, './test/fixtures/test.csv'); rechoir.prepare(config, './test/fixtures/test.toml'); console.log(require('./test/fixtures/test.coffee')); console.log(require('./test/fixtures/test.csv')); console.log(require('./test/fixtures/test.toml')); ``` [interpret]: http://github.com/tkellen/js-interpret [Liftoff]: http://github.com/tkellen/js-liftoff # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. [![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) [![Build Status](https://travis-ci.org/eslint/espree.svg?branch=master)](https://travis-ci.org/eslint/espree) [![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) # Espree Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. ## Usage Install: ``` npm i espree ``` And in your Node.js code: ```javascript const espree = require("espree"); const ast = espree.parse(code); ``` ## API ### `parse()` `parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). ```javascript const espree = require("espree"); const ast = espree.parse(code, options); ``` **Example :** ```js const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); console.log(ast); ``` <details><summary>Output</summary> <p> ``` Node { type: 'Program', start: 0, end: 15, body: [ Node { type: 'VariableDeclaration', start: 0, end: 15, declarations: [Array], kind: 'let' } ], sourceType: 'script' } ``` </p> </details> ### `tokenize()` `tokenize` returns the tokens of a given code. It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array **Example :** ```js const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); console.log(tokens); ``` <details><summary>Output</summary> <p> ``` Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, Token { type: 'String', value: '"bar"', start: 10, end: 15 } ``` </p> </details> ### `version` Returns the current `espree` version ### `VisitorKeys` Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) ### `latestEcmaVersion` Returns the latest ECMAScript supported by `espree` ### `supportedEcmaVersions` Returns an array of all supported ECMAScript versions ## Options ```js const options = { // attach range information to each node range: false, // attach line/column location information to each node loc: false, // create a top-level comments array containing all comments comment: false, // create a top-level tokens array containing all tokens tokens: false, // Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming. ecmaVersion: 5, // specify which type of script you're parsing ("script" or "module") sourceType: "script", // specify additional language features ecmaFeatures: { // enable JSX parsing jsx: false, // enable return in global scope globalReturn: false, // enable implied strict mode (if ecmaVersion >= 5) impliedStrict: false } } ``` ## Esprima Compatibility Going Forward The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. Espree may also deviate from Esprima in the interface it exposes. ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). Espree is licensed under a permissive BSD 2-clause license. ## Security Policy We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting * `npm run browserify` - creates a version of Espree that is usable in a browser ## Differences from Espree 2.x * The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. * Trailing whitespace no longer is counted as part of a node. * `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. * The `esparse` and `esvalidate` binary scripts have been removed. * There is no `tolerant` option. We will investigate adding this back in the future. ## Known Incompatibilities In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. ### Esprima 1.2.2 * Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. * Espree does not parse `let` and `const` declarations by default. * Error messages returned for parsing errors are different. * There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. ### Esprima 2.x * Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. ## Frequently Asked Questions ### Why another parser [ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. ### Have you tried working with Esprima? Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. ### Why don't you just use Acorn? Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. ### What ECMAScript features do you support? Espree supports all ECMAScript 2020 features and partially supports ECMAScript 2021 features. Because ECMAScript 2021 is still under development, we are implementing features as they are finalized. Currently, Espree supports: * [Logical Assignment Operators](https://github.com/tc39/proposal-logical-assignment) * [Numeric Separators](https://github.com/tc39/proposal-numeric-separator) See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. ### How do you determine which experimental features to support? In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. # lodash.truncate v4.4.2 The [lodash](https://lodash.com/) method `_.truncate` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.truncate ``` In Node.js: ```js var truncate = require('lodash.truncate'); ``` See the [documentation](https://lodash.com/docs#truncate) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.truncate) for more details. Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ``` ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # lodash.merge v4.6.2 The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.merge ``` In Node.js: ```js var merge = require('lodash.merge'); ``` See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) [![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) [![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) <br /> [![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) [![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) [![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) # ESLint [Website](https://eslint.org) | [Configuring](https://eslint.org/docs/user-guide/configuring) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | [Code of Conduct](https://eslint.org/conduct) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://eslint.org/chat) ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. ## Table of Contents 1. [Installation and Usage](#installation-and-usage) 2. [Configuration](#configuration) 3. [Code of Conduct](#code-of-conduct) 4. [Filing Issues](#filing-issues) 5. [Frequently Asked Questions](#faq) 6. [Releases](#releases) 7. [Security Policy](#security-policy) 8. [Semantic Versioning Policy](#semantic-versioning-policy) 9. [Stylistic Rule Updates](#stylistic-rule-updates) 10. [License](#license) 11. [Team](#team) 12. [Sponsors](#sponsors) 13. [Technology Sponsors](#technology-sponsors) ## <a name="installation-and-usage"></a>Installation and Usage Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install ESLint using npm: ``` $ npm install eslint --save-dev ``` You should then set up a configuration file: ``` $ ./node_modules/.bin/eslint --init ``` After that, you can run ESLint on any file or directory like this: ``` $ ./node_modules/.bin/eslint yourfile.js ``` ## <a name="configuration"></a>Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: ```json { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). ## <a name="code-of-conduct"></a>Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://eslint.org/conduct). ## <a name="filing-issues"></a>Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: * [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) * [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) ## <a name="faq"></a>Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. ### Why can't ESLint find my plugins? * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. * Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. ### What ECMAScript versions does ESLint support? ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). ### What about experimental features? ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). ### Why doesn't ESLint lock dependency versions? Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. ## <a name="releases"></a>Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. ## <a name="security-policy"></a>Security Policy ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## <a name="semantic-versioning-policy"></a>Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: * Patch release (intended to not break your lint build) * A bug fix in a rule that results in ESLint reporting fewer linting errors. * A bug fix to the CLI or core (including formatters). * Improvements to documentation. * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). * Minor release (might break your lint build) * A bug fix in a rule that results in ESLint reporting more linting errors. * A new rule is created. * A new option to an existing rule that does not result in ESLint reporting more linting errors by default. * A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. * An existing rule is deprecated. * A new CLI capability is created. * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). * A new formatter is created. * `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). * Major release (likely to break your lint build) * `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). * A new option to an existing rule that results in ESLint reporting more linting errors by default. * An existing formatter is removed. * Part of the public API is removed or changed in an incompatible way. The public API includes: * Rule schemas * Configuration schema * Command-line options * Node.js API * Rule, formatter, parser, plugin APIs According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. ## <a name="stylistic-rule-updates"></a>Stylistic Rule Updates Stylistic rules are frozen according to [our policy](https://eslint.org/blog/2020/05/changes-to-rules-policies) on how we evaluate new rules and rule changes. This means: * **Bug fixes**: We will still fix bugs in stylistic rules. * **New ECMAScript features**: We will also make sure stylistic rules are compatible with new ECMAScript features. * **New options**: We will **not** add any new options to stylistic rules unless an option is the only way to fix a bug or support a newly-added ECMAScript feature. ## <a name="license"></a>License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) ## <a name="team"></a>Team These folks keep the project moving and are resources for help. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--teamstart--> ### Technical Steering Committee (TSC) The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/nzakas"> <img src="https://github.com/nzakas.png?s=75" width="75" height="75"><br /> Nicholas C. Zakas </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/btmills"> <img src="https://github.com/btmills.png?s=75" width="75" height="75"><br /> Brandon Mills </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/mdjermanovic"> <img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br /> Milos Djermanovic </a> </td></tr></tbody></table> ### Reviewers The people who review and implement new features. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/mysticatea"> <img src="https://github.com/mysticatea.png?s=75" width="75" height="75"><br /> Toru Nagashima </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/aladdin-add"> <img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br /> 薛定谔的猫 </a> </td></tr></tbody></table> ### Committers The people who review and fix bugs and help triage issues. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/brettz9"> <img src="https://github.com/brettz9.png?s=75" width="75" height="75"><br /> Brett Zamir </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/bmish"> <img src="https://github.com/bmish.png?s=75" width="75" height="75"><br /> Bryan Mishkin </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/g-plane"> <img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br /> Pig Fang </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/anikethsaha"> <img src="https://github.com/anikethsaha.png?s=75" width="75" height="75"><br /> Anix </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/yeonjuan"> <img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br /> YeonJuan </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/snitin315"> <img src="https://github.com/snitin315.png?s=75" width="75" height="75"><br /> Nitin Kumar </a> </td></tr></tbody></table> <!--teamend--> ## <a name="sponsors"></a>Sponsors The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--sponsorsstart--> <h3>Platinum Sponsors</h3> <p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3> <p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p> <!--sponsorsend--> ## <a name="technology-sponsors"></a>Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) * Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) * Password management is sponsored by [1Password](https://www.1password.com) # levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" /> __Light ECMAScript (JavaScript) Value Notation__ Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. __How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. npm install levn For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). ## Quick Examples ```js var parse = require('levn').parse; parse('Number', '2'); // 2 parse('String', '2'); // '2' parse('String', 'levn'); // 'levn' parse('String', 'a b'); // 'a b' parse('Boolean', 'true'); // true parse('Date', '#2011-11-11#'); // (Date object) parse('Date', '2011-11-11'); // (Date object) parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi parse('RegExp', 're'); // /re/ parse('Int', '2'); // 2 parse('Number | String', 'str'); // 'str' parse('Number | String', '2'); // 2 parse('[Number]', '[1,2,3]'); // [1,2,3] parse('(String, Boolean)', '(hi, false)'); // ['hi', false] parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} // at the top level, you can ommit surrounding delimiters parse('[Number]', '1,2,3'); // [1,2,3] parse('(String, Boolean)', 'hi, false'); // ['hi', false] parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} // wildcard - auto choose type parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] ``` ## Usage `require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. ```js // parse(type, input, options); parse('[Number]', '1,2,3'); // [1, 2, 3] // parsedTypeParse(parsedType, input, options); var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ### parse(type, input, options) `parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. ##### arguments * type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js parse('[Number]', '1,2,3'); // [1, 2, 3] ``` ### parsedTypeParse(parsedType, input, options) `parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ## Levn Format Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). * `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` * `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` * `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` * `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents * `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. * `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). * `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. * Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: * If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. * If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. * If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. * If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. * If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). * If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. Whitespace between special characters and elements is inconsequential. ## Options Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. ### Explicit A `Boolean`. By default it is `false`. __Example:__ ```js parse('RegExp', 're', {explicit: false}); // /re/ parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... parse('RegExp | String', 're', {explicit: true}); // 're' ``` `explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. ### customTypes An `Object`. Empty `{}` by default. __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function (x) { return x % 2 === 0; }, cast: function (x) { return {type: 'Just', value: parseInt(x)}; } } } } parse('Even', '2', options); // 2 parse('Even', '3', options); // Error: Value: "3" does not type check... ``` __Another Example:__ ```js function Person(name, age){ this.name = name; this.age = age; } var options = { customTypes: { Person: { typeOf: 'Object', validate: function (x) { x instanceof Person; }, cast: function (value, options, typesCast) { var name, age; if ({}.toString.call(value).slice(8, -1) !== 'Object') { return {type: 'Nothing'}; } name = typesCast(value.name, [{type: 'String'}], options); age = typesCast(value.age, [{type: 'Numger'}], options); return {type: 'Just', value: new Person(name, age)}; } } } parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} ``` `customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. `cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. ## Technical About `levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: [demo](https://estools.github.io/esquery/) The following selectors are supported: * AST node type: `ForStatement` * [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` * [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` * [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` * attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` * attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` * nested attribute: `[attr.level2="foo"]` * field: `FunctionDeclaration > Identifier.id` * [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` * [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` * [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` * [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` * [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` * [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` * [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` * [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` * [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)` * [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` * [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` * class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` [![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/eslint/doctrine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/doctrine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Doctrine Doctrine is a [JSDoc](http://usejsdoc.org) parser that parses documentation comments from JavaScript (you need to pass in the comment, not a whole JavaScript file). ## Installation You can install Doctrine using [npm](https://npmjs.com): ``` $ npm install doctrine --save-dev ``` Doctrine can also be used in web browsers using [Browserify](http://browserify.org). ## Usage Require doctrine inside of your JavaScript: ```js var doctrine = require("doctrine"); ``` ### parse() The primary method is `parse()`, which accepts two arguments: the JSDoc comment to parse and an optional options object. The available options are: * `unwrap` - set to `true` to delete the leading `/**`, any `*` that begins a line, and the trailing `*/` from the source text. Default: `false`. * `tags` - an array of tags to return. When specified, Doctrine returns only tags in this array. For example, if `tags` is `["param"]`, then only `@param` tags will be returned. Default: `null`. * `recoverable` - set to `true` to keep parsing even when syntax errors occur. Default: `false`. * `sloppy` - set to `true` to allow optional parameters to be specified in brackets (`@param {string} [foo]`). Default: `false`. * `lineNumbers` - set to `true` to add `lineNumber` to each node, specifying the line on which the node is found in the source. Default: `false`. * `range` - set to `true` to add `range` to each node, specifying the start and end index of the node in the original comment. Default: `false`. Here's a simple example: ```js var ast = doctrine.parse( [ "/**", " * This function comment is parsed by doctrine", " * @param {{ok:String}} userName", "*/" ].join('\n'), { unwrap: true }); ``` This example returns the following AST: { "description": "This function comment is parsed by doctrine", "tags": [ { "title": "param", "description": null, "type": { "type": "RecordType", "fields": [ { "type": "FieldType", "key": "ok", "value": { "type": "NameExpression", "name": "String" } } ] }, "name": "userName" } ] } See the [demo page](http://eslint.org/doctrine/demo/) more detail. ## Team These folks keep the project moving and are resources for help: * Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) - project lead * Yusuke Suzuki ([@constellation](https://github.com/constellation)) - reviewer ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/doctrine/issues). ## Frequently Asked Questions ### Can I pass a whole JavaScript file to Doctrine? No. Doctrine can only parse JSDoc comments, so you'll need to pass just the JSDoc comment to Doctrine in order to work. ### License #### doctrine Copyright JS Foundation and other contributors, https://js.foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #### esprima some of functions is derived from esprima Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #### closure-compiler some of extensions is derived from closure-compiler Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ ### Where to ask for help? Join our [Chatroom](https://gitter.im/eslint/doctrine) [npm-image]: https://img.shields.io/npm/v/doctrine.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/doctrine [travis-image]: https://img.shields.io/travis/eslint/doctrine/master.svg?style=flat-square [travis-url]: https://travis-ci.org/eslint/doctrine [coveralls-image]: https://img.shields.io/coveralls/eslint/doctrine/master.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/eslint/doctrine?branch=master [downloads-image]: http://img.shields.io/npm/dm/doctrine.svg?style=flat-square [downloads-url]: https://www.npmjs.com/package/doctrine functional-red-black-tree ========================= A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. # Install npm install functional-red-black-tree # Example Here is an example of some basic usage: ```javascript //Load the library var createTree = require("functional-red-black-tree") //Create a tree var t1 = createTree() //Insert some items into the tree var t2 = t1.insert(1, "foo") var t3 = t2.insert(2, "bar") //Remove something var t4 = t3.remove(1) ``` # API ```javascript var createTree = require("functional-red-black-tree") ``` ## Overview - [Tree methods](#tree-methods) - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) - [`tree.keys`](#treekeys) - [`tree.values`](#treevalues) - [`tree.length`](#treelength) - [`tree.get(key)`](#treegetkey) - [`tree.insert(key, value)`](#treeinsertkey-value) - [`tree.remove(key)`](#treeremovekey) - [`tree.find(key)`](#treefindkey) - [`tree.ge(key)`](#treegekey) - [`tree.gt(key)`](#treegtkey) - [`tree.lt(key)`](#treeltkey) - [`tree.le(key)`](#treelekey) - [`tree.at(position)`](#treeatposition) - [`tree.begin`](#treebegin) - [`tree.end`](#treeend) - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) - [`tree.root`](#treeroot) - [Node properties](#node-properties) - [`node.key`](#nodekey) - [`node.value`](#nodevalue) - [`node.left`](#nodeleft) - [`node.right`](#noderight) - [Iterator methods](#iterator-methods) - [`iter.key`](#iterkey) - [`iter.value`](#itervalue) - [`iter.node`](#iternode) - [`iter.tree`](#itertree) - [`iter.index`](#iterindex) - [`iter.valid`](#itervalid) - [`iter.clone()`](#iterclone) - [`iter.remove()`](#iterremove) - [`iter.update(value)`](#iterupdatevalue) - [`iter.next()`](#iternext) - [`iter.prev()`](#iterprev) - [`iter.hasNext`](#iterhasnext) - [`iter.hasPrev`](#iterhasprev) ## Tree methods ### `var tree = createTree([compare])` Creates an empty functional tree * `compare` is an optional comparison function, same semantics as array.sort() **Returns** An empty tree ordered by `compare` ### `tree.keys` A sorted array of all the keys in the tree ### `tree.values` An array array of all the values in the tree ### `tree.length` The number of items in the tree ### `tree.get(key)` Retrieves the value associated to the given key * `key` is the key of the item to look up **Returns** The value of the first node associated to `key` ### `tree.insert(key, value)` Creates a new tree with the new pair inserted. * `key` is the key of the item to insert * `value` is the value of the item to insert **Returns** A new tree with `key` and `value` inserted ### `tree.remove(key)` Removes the first item with `key` in the tree * `key` is the key of the item to remove **Returns** A new tree with the given item removed if it exists ### `tree.find(key)` Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. ### `tree.ge(key)` Find the first item in the tree whose key is `>= key` * `key` is the key to search for **Returns** An iterator at the given element. ### `tree.gt(key)` Finds the first item in the tree whose key is `> key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.lt(key)` Finds the last item in the tree whose key is `< key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.le(key)` Finds the last item in the tree whose key is `<= key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.at(position)` Finds an iterator starting at the given element * `position` is the index at which the iterator gets created **Returns** An iterator starting at position ### `tree.begin` An iterator pointing to the first element in the tree ### `tree.end` An iterator pointing to the last element in the tree ### `tree.forEach(visitor(key,value)[, lo[, hi]])` Walks a visitor function over the nodes of the tree in order. * `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. * `lo` is an optional start of the range to visit (inclusive) * `hi` is an optional end of the range to visit (non-inclusive) **Returns** The last value returned by the callback ### `tree.root` Returns the root node of the tree ## Node properties Each node of the tree has the following properties: ### `node.key` The key associated to the node ### `node.value` The value associated to the node ### `node.left` The left subtree of the node ### `node.right` The right subtree of the node ## Iterator methods ### `iter.key` The key of the item referenced by the iterator ### `iter.value` The value of the item referenced by the iterator ### `iter.node` The value of the node at the iterator's current position. `null` is iterator is node valid. ### `iter.tree` The tree associated to the iterator ### `iter.index` Returns the position of this iterator in the sequence. ### `iter.valid` Checks if the iterator is valid ### `iter.clone()` Makes a copy of the iterator ### `iter.remove()` Removes the item at the position of the iterator **Returns** A new binary search tree with `iter`'s item removed ### `iter.update(value)` Updates the value of the node in the tree at this iterator **Returns** A new binary search tree with the corresponding node updated ### `iter.next()` Advances the iterator to the next position ### `iter.prev()` Moves the iterator backward one element ### `iter.hasNext` If true, then the iterator is not at the end of the sequence ### `iter.hasPrev` If true, then the iterator is not at the beginning of the sequence # Credits (c) 2013 Mikola Lysenko. MIT License # node-supports-preserve-symlinks-flag <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] Determine if the current node version supports the `--preserve-symlinks` flag. ## Example ```js var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); var assert = require('assert'); assert.equal(supportsPreserveSymlinks, null); // in a browser assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag [npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag [dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg [dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies [npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg [downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag [codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag [actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions # `NEARGames` # 📄 Descripción NearGames es un Smart-Contract en el que los usuarios se pueden registar, crear juegos y los demas usuarios podran comprarlos. Las funcionalidades del Smart-Contract son: 1. Crear Usuario. 2. Consultar Usuario por su Id. 3. Consultar a todos los usuarios. 4. Registrar un videojuego. 5. Consultar un Videojuego por su Id. 6. Consultar todos los videojuegos existentes. 7. Comprar videojuego para un usuario # 📦 Instalación Para ejecutar este proyecto localmente, debe seguir los siguientes pasos: ## Paso 1: Prerequisitos 1. Asegúrese de haber instalado [Node.js] ≥ 12 (recomendamos usar [nvm]) 2. Asegúrese de haber instalado yarn: `npm install -g yarn` 3. Instalar dependencias: `yarn install` 4. Cree una cuenta de prueba NEAR [https://wallet.testnet.near.org/] 5. Instale NEAR CLI globalmente: [near-cli] es una interfaz de línea de comandos (CLI) para interactuar con NEAR blockchain yarn install --global near-cli ## Step 2: Configuración de NEAR CLI Configure su near-cli para autorizar su cuenta de prueba creada recientemente: near login ## Paso 3: Cree y realice una implementación de desarrollo de contrato inteligente Para crear el Smart-Contract de NearGames en el servidor de desarrollo local ejecute la linea `yarn build`, Este comando crea el contrato inteligente y para desplegar el contrato, ejecutar el comando `yarn deploy`. Una vez generado, le mostrara su contrato con la iniciacion 'dev-'. # 📑 Explorando los métodos de contrato inteligente NearGames Las siguientes lineas de comando le permiten interactuar con los métodos del Smart-Contract utilizando NEAR CLI. ## Comando para ver si el contrato esta funcionando near view $CONTRACT Prueba ## Comando para crear usuario: near call $CONTRACT RegistrarUsuario '{ "UserId":"string", "Email":"string"}' --account-id <"your test account"> ## Comando para consultar todos los usuarios: near view $CONTRACT ConsultarUsuarios ## Comando para consultar un usuario por id: near view $CONTRACT ConsultarUsuario '{"UserId":"string"}' ## Comando para Crear un videojuego near call $CONTRACT RegistrarVideojuego '{ "Name":"string", "Description":"string", "Price":"string"}' --account-id <"your testaccount"> ## Comando para consultar todos los videojuegos: near view $CONTRACT ConsultarVideojuegos ## Comando para consultar un videojuego por nombre: near view $CONTRACT ConsultarVideojuego '{"Name":"string"}' ## 🖥️ Interfáz gráfica de usuario https://www.figma.com/file/FWMc1JDnHZhRY9kfmlEobQ/NearGames?node-id=0%3A1 # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind
near-x_ncd-cn
README.md cohorts ncd-cn-1 README.md slides README.md ncd-cn-10 README.md slides README.md ncd-cn-11 README.md slides README.md cross-contract-call README.md ncd-cn-12 README.md slides README.md ncd-cn-17 README.md slides README.md ncd-cn-18 README.md slides README.md ncd-cn-19 README.md slides README.md ncd-cn-2 README.md slides README.md ncd-cn-20 README.md slides README.md ncd-cn-21 README.md slides README.md ncd-cn-3 README.md slides README.md ncd-cn-4 README.md slides README.md ncd-cn-5 README.md slides README.md ncd-cn-6 README.md slides README.md ncd-cn-7 README.md slides README.md ncd-cn-8 README.md slides README.md ncd-cn-9 README.md slides README.md | events rust-china-conf-2023 README.md
# NEAR 认证开发者中文课程(第一期) ## 课程内容 章节 | 日期 | 幻灯片 | 视频 -- | -- | -- | -- NEAR 核心概念与应用架构 | 8月16日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1Uq4y1S72C/) NEAR Rust 智能合约开发 | 8月18日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV12y4y1V7EL) NEAR DApp 开发与常用工具 | 8月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1BM4y1L7Cj) 在线答疑时间 | 8月22日 | -- | -- NEAR NFT 开发实践 | 8月23日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%884%EF%BC%89%EF%BC%9ANEAR%20NFT%20%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1YA411A7Ls/) Aurora 应用开发实践 | 8月25日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%885%EF%BC%89%EF%BC%9AAurora%20%E5%BA%94%E7%94%A8%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1Lg411L7BR/) 基于 Octopus 的 Substrate 开发实践 | 8月27日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%886%EF%BC%89%EF%BC%9A%E5%9F%BA%E4%BA%8EOctopus%E7%9A%84Substrate%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1s44y1C7xd/) 课程项目演示(Demo Day) | 8月29日 | [作品列表](https://shimo.im/sheets/5xkGM90MO8fKrL3X/uLd1D) | [播放](https://www.bilibili.com/video/BV1oA411c7SL/) 黑客松作品提交 | 9月11日 | -- | -- # NEAR 认证开发者中文课程(第十八期) 2023年8月 ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 8月14日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 8月16日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 8月16日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 8月18日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | Keypom 介绍 | 8月28日 | [下载1](https://bit.ly/ncd-cn-keypom-1) / [下载2](https://bit.ly/ncd-cn-keypom-2) | [播放](https://www.bilibili.com/video/BV1Cu4y1D7eP) | | Demo Day | 8月25日 | -- | -- | # NEAR 认证开发者中文课程(第九期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 6月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 6月22日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | NEAR AssemblyScript 智能合约开发 | 6月22日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T ) | | 用 JavaScript 开发 NEAR 智能合约 | 6月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 6月24日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 6月24日 | -- | -- | | Flux 预言机介绍 | 6月27日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-9/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8828%EF%BC%89%EF%BC%9A%20Flux%E9%A2%84%E8%A8%80%E6%9C%BA%E4%BB%8B%E7%BB%8D.pdf) | [播放](https://www.bilibili.com/video/BV1XY4y1J7Aa) | | Burrow 合约讲解 | 6月29日 | [代码](http://github.com/neardefi/burrowland) | [播放](https://www.bilibili.com/video/BV1rt4y1872w) | | Demo Day | 7月1日 | -- | -- | # NEAR 认证开发者中文课程(第十期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 8月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 8月24日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | NEAR AssemblyScript 智能合约开发 | 8月24日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T ) | | 用 JavaScript 开发 NEAR 智能合约 | 8月24日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 8月26日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 8月26日 | -- | -- | | SputnikDAO v2 合约讲解 | 8月29日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-10/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8832%EF%BC%89%EF%BC%9ASputnikDAO%20v2%E5%90%88%E7%BA%A6%E8%AE%B2%E8%A7%A3.pdf) | [播放](https://www.bilibili.com/video/BV11d4y1G7R2) | | Wasm Runtime 原理 | 8月31日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-10/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8833%EF%BC%89%EF%BC%9AWasm%20Runtime%E5%B7%A5%E4%BD%9C%E5%8E%9F%E7%90%86.pdf) | [播放](https://www.bilibili.com/video/BV12T411F77F) | | Demo Day | 9月2日 | -- | -- | # ncd-cn NEAR Certified Developer Program for Chinese Community # Promise与跨合约调用 (by Coffee) **跨合约调用**指某个合约去调用另一个合约方法的操作,该操作是**异步**的,调用方称为 `predecessor`,被调用方称为 `receiver` ### Review ### Action * [x] `Transfer` (转账 **NEAR**) * [x] `FunctionCall`(转账 **NEP141 Token**、**跨合约调用**) * [x] `Deploy` * [ ] `Stake` * [ ] `CreateAccount` * [ ] `DeleteAcount` * [x] `AddKey` * [x] `DeleteKey` ## Promise near_sdk version >= 4.0.0 * 三种 API * 低级:env * [burrowland/upgrade.rs at main · NearDeFi/burrowland (github.com)](https://github.com/NearDeFi/burrowland/blob/main/contract/src/upgrade.rs) * 中级:Promise * 高级:定义 trait,只适用于单个 `FunctionCall` * 回调函数 * near_sdk 4.0.0 正式版前后写法的区别 * `env::promise_result` * `#[callback_result]` * `#[callback_unwrap]` * 返回 Promise 与 Value 的区别 ## 跨合约调用详解 ### Transaction `Transaction` 有 3 个重要的参数: * `signer_id: AccountId` * `receiver_id: AccountId` * `actions: Array<Action>` 一笔 `Transaction` 就是包含**一个或多个** `Action` 的数组,节点按顺序执行数组中的 `Action` ,执行具有原子性 [Batch Transaction](https://explorer.testnet.near.org/transactions/HfE7ZJrkGTiwnVKz15KpAqnKJEuN3yxC7LHUoVbvqJ16) ### Rceipt `Receipt` 有 3 个重要的参数: * `predecessor_id: AccountId` * `receiver_id: AccountId` * `actions: Array<Action>` 对比一下可以发现,`Receipt` 是 `Transaction` 的另外一种形式,一笔 `Transaction` 需要先转化为对应的 `Receipt` 才能执行,通常该转换需要消耗一个区块时间。 `Receipt` 如果包含 `FunctionCall` , 执行完毕后可能产生新的 `Receipt`(因为合约方法可能包含跨合约调用或其他的 `Action `调用) **一笔交易的完整流程:签名发起 ` Transaction` -> `Transaction` 转 `Receipt` -> 执行 `Receipt` 产生新的 `Receipt` -> ... -> 直到所有 `Receipt` 执行完毕** <img width="801" alt="receipt" src="https://user-images.githubusercontent.com/46699230/192817732-9427220e-c673-42ad-b6b2-0ffffe0ea605.png"> [NEAR Explorer | Transaction](https://explorer.near.org/transactions/CkbjbMFsduiZuU5mFRtVLA5hQvJ1uA4P6PVBtWtWGhvp) [NEAR Explorer | Block](https://explorer.near.org/blocks/ECoy9A83ejqAkNT5kgtbSRdC4JErSsWez74uifKCdWZD) ### Example alice.near 在 ref-finance 用 wnear 兑换 oct,整个流程经历 5 个区块 https://explorer.testnet.near.org/transactions/GPhqfQEQZABc3M2DGNPzHMYXpZoNUPQmpsBidcz4ygVA <img width="1078" alt="example" src="https://user-images.githubusercontent.com/46699230/192817655-d25745c0-e391-4181-a30f-a3ddb5ba96c6.png"> ## 更多信息 [关于 Near 合约开发中 Promise 的思考和总结 - SegmentFault](https://segmentfault.com/a/1190000041842290) # NEAR 认证开发者中文课程(第四期) ## 课程内容 章节 | 日期 | 幻灯片 | 视频 -- | -- | -- | -- NEAR 核心概念与应用架构 [直播+录播] | 11月15日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-2/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV13v411w7Xf/) NEAR Rust 智能合约开发 [录播] | 11月17日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV12y4y1V7EL) NEAR AssemblyScript 智能合约开发 [录播] | 11月17日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T/) NEAR DApp 开发与常用工具 [录播] | 11月19日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1BM4y1L7Cj) 在线答疑时间 | 11月21日 | -- | -- Filecoin: 为 NEAR DApp 提供去中心存储 | 11月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-4/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8814%EF%BC%89%EF%BC%9AFilecoin%EF%BC%9A%E4%B8%BA%20NEAR%20%E5%BA%94%E7%94%A8%E6%8F%90%E4%BE%9B%E5%8E%BB%E4%B8%AD%E5%BF%83%E5%AD%98%E5%82%A8.pdf) | [播放](https://www.bilibili.com/video/BV1Cq4y1u71S/) NEAR Rust 合约安全 | 11月24日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-4/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8815%EF%BC%89%EF%BC%9ANEAR%20Rust%20%E5%90%88%E7%BA%A6%E5%AE%89%E5%85%A8.pdf) | [播放](https://www.bilibili.com/video/BV1yM4y1P7Vk/) NEAR 夜影分片技术介绍 | 11月26日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-4/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8816%EF%BC%89%EF%BC%9ANEAR%E5%A4%9C%E5%BD%B1%E5%88%86%E7%89%87%E6%8A%80%E6%9C%AF%E4%BB%8B%E7%BB%8D.pdf) | [播放](https://www.bilibili.com/video/BV1Vi4y1o7dh/) 课程项目演示(Demo Day) | 11月28日 | | # NEAR 认证开发者中文课程(第三期) ## 课程内容 章节 | 日期 | 幻灯片 | 视频 -- | -- | -- | -- NEAR 核心概念与应用架构 [直播+录播] | 10月18日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-2/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV13v411w7Xf/) NEAR Rust 智能合约开发 [录播] | 10月20日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV12y4y1V7EL) NEAR AssemblyScript 智能合约开发 [录播] | 10月20日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T/) NEAR DApp 开发与常用工具 [录播] | 10月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1BM4y1L7Cj) 在线答疑时间 | 10月24日 | -- | -- NEAR 合约的数据存储 | 10月25日 | | [播放](https://www.bilibili.com/video/BV1P44y1i7aR/) NFT实战:市场 + 盲盒 | 10月27日 | [第一部分](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-3/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8811%EF%BC%89%EF%BC%9ANEAR%20NFT%E5%AE%9E%E6%88%98%EF%BC%9A%E5%B8%82%E5%9C%BA%20%2B%20%E7%9B%B2%E7%9B%92%EF%BC%88Part%20I%EF%BC%89.pdf) / [第二部分](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-3/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8811%EF%BC%89%EF%BC%9ANEAR%20NFT%E5%AE%9E%E6%88%98%EF%BC%9A%E5%B8%82%E5%9C%BA%20%2B%20%E7%9B%B2%E7%9B%92%EF%BC%88Part%20II%EF%BC%89.pdf) | [播放](https://www.bilibili.com/video/BV1Fq4y1R7oW/) 基于 NEAR 和 Crust 的开发实践 | 10月29日 | [代码](https://github.com/RoyTimes/crust-workshop) | [播放](https://www.bilibili.com/video/BV1Tq4y1V7CF/) 课程项目演示(Demo Day) | 10月31日 | | NEAR + The Graph:打造完美的 Web3.0 用户体验 | 11月6日 | [课件](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-3/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8813%EF%BC%89%EF%BC%9ANEAR%20%2B%20The%20Graph%EF%BC%9A%E6%89%93%E9%80%A0%E5%AE%8C%E7%BE%8E%E7%9A%84%20Web3.0%20%E7%94%A8%E6%88%B7%E4%BD%93%E9%AA%8C.pdf) | [播放](https://www.bilibili.com/video/BV1oP4y1V7g5/) ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第二十期) 2023年12月 ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 12月18日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 12月20日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 12月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 12月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | Octopus Network 2.0 Restaking 技术详解 | 12月27日 | [下载](https://bit.ly/ncd-cn-octopus-network-restaking) | [播放](https://www.bilibili.com/video/BV1Up4y1d77S/) | | Demo Day | 12月29日 | -- | -- | # NEAR 认证开发者中文课程(第十七期) 2023年6月 ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 6月19日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 6月21日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 6月21日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 6月23日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) || 在线答疑 Office Hour | 8月26日 | -- | -- | | NEAR BOS Gateway 开发 | 6月26日 | [打开](https://bit.ly/bos-gateway-2023-06) | [播放](https://www.bilibili.com/video/BV19u41187ct) | | NEAR-IBC 介绍 | 6月28日 | [下载](https://bit.ly/near-ibc-2023-06) | [播放](https://www.bilibili.com/video/BV1Xk4y1T7xY) | | Demo Day | 6月30日 | -- | -- | ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第六期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 3月21日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 3月23日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | NEAR DApp 开发与常用工具 | 3月25日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 3月27日 | -- | -- | | NEAR 账户模型与 Linkdrop | 3月28日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8822%EF%BC%89%EF%BC%9A%20NEAR%20%E8%B4%A6%E6%88%B7%E6%A8%A1%E5%9E%8B%E4%B8%8E%20Linkdrop.pdf) | [播放](https://www.bilibili.com/video/BV18Y411J74U) | | Octopus Network 的 NEAR 智能合约实践 | 3月30日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8823%EF%BC%89%EF%BC%9A%20Octopus%20Network%20%E7%9A%84%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1UY4y1p7BW/) | 课程项目演示(Demo Day) | 4月1日 | -- | -- | # NEAR 认证开发者中文课程(第十二期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 10月17日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 10月19日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 10月19日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 10月21日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 10月21日 | -- | -- | | 用 Kurtosis 搭建本地开发环境 | 10月24日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-12/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8836%EF%BC%89%EF%BC%9A%E7%94%A8%20Kurtosis%20%E6%90%AD%E5%BB%BA%E6%9C%AC%E5%9C%B0%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83.pdf) | [播放](https://www.bilibili.com/video/BV12W4y1E7mb) | | Popula 与 Nepbot 的设计与实现 | 10月26日 | [Nepbot-1](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-12/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8837%EF%BC%89%EF%BC%9ANepbot%20%E4%BB%8B%E7%BB%8D.pdf) / [Nepbot-2](https://pitch.com/public/9eee3e1a-91a3-447e-8d9e-5263e27d62cb) / [Popula](https://pitch.com/public/1a25100f-ee8d-49a1-99ce-b26d2a2fe8cd) | [播放](https://www.bilibili.com/video/BV1a84y1B7ox/) | | Demo Day | 10月28日 | -- | -- | # Rust China Conf 2023 ## NEAR Rust 技术见面会 Workshop 介绍 NEAR 技术、生态和开发者社区等方面的最新进展,包括区块链操作系统(BOS)、Rust合约开发、NEAR DevHub 以及NEAR账户模型(以NameSky账户交易市场为例)等话题。 | 时间 | 主题 | 演讲者 | | --- | --- | --- | 1800 - 1830 | [NEAR 区块链操作系统 (BOS) 介绍](https://docs.google.com/presentation/d/1hrkKGpqjkaPT0ivBF9C-P3VoRAVCtRiCjVfbZN1qLeQ/edit?usp=sharing) | Robert Yan, NEAR 工程师 1830 - 1900 | [入门 Rust 合约开发](https://docs.google.com/presentation/d/1tsKRDubNINFqewym1EVGG36f9iJjGhTr/edit?usp=sharing) | Marco Sun, NEAR Rust 合约专家 1900 - 1930 | [NEAR DevHub 开源开发者社区](https://docs.google.com/presentation/d/14hL7nUfzc_ZYWJIBSaJAWZCTDBbOZBBd/edit?usp=sharing) | Bo Yao, Pagoda 1930 - 2000 | [用 Rust 合约实现 NEAR 域名市场](https://docs.google.com/presentation/d/1nvM5EIPwccOJIzAyQpzIkvAnsVVptCLs/edit?usp=sharing) | Coffee, NEAR Rust 合约开发者 听众收益 1. 了解 NEAR 区块链操作系统的设计、应用与发展方向,以及如何参与开发; 2. 入门 Rust 智能合约开发; 3. 认识 NEAR 如何打造一个有创造力的开源社区,并通过贡献开源获得持续报酬; 4. 学习 NEAR 账户模型,并基于它实现有趣的应用; **现场录制视频**:https://www.bilibili.com/video/BV1PX4y1t7ja ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第八期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 5月16日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 5月18日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | NEAR AssemblyScript 智能合约开发 | 5月18日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T ) | | NEAR DApp 开发与常用工具 | 5月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 5月20日 | -- | -- | | 用 JavaScript 开发 NEAR 智能合约 | 5月23日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | Ref Finance 合约代码讲解 | 5月25日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8827%EF%BC%89%EF%BC%9A%20Ref%20Finance%20%E5%90%88%E7%BA%A6%E4%BB%A3%E7%A0%81%E8%AE%B2%E8%A7%A3.pdf) | [播放](https://www.bilibili.com/video/BV1Cv4y1c7M4/) | | Demo Day | 5月27日 | -- | -- | ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第十一期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 9月19日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 9月21日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 9月21日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 9月23日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 9月23日 | -- | -- | | NEAR Data Stack 介绍 | 9月26日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-11/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8834%EF%BC%89%EF%BC%9ANEAR%20%E6%95%B0%E6%8D%AE%E6%8A%80%E6%9C%AF%E6%A0%88.pdf) | [播放](https://www.bilibili.com/video/BV11G411g7Ng) | | NEAR 跨合约调用详解 | 9月28日 | [文档](https://github.com/near-x/ncd-cn/tree/master/cohorts/ncd-cn-11/slides/cross-contract-call) | [播放](https://www.bilibili.com/video/BV1G14y1a7st) | | Demo Day | 9月30日 | -- | -- | # NEAR 认证开发者中文课程(第五期) MetaBUILD 黑客松期间,结合黑客松挑战题等开展了一系列课程和 workshop。 ## 课程内容 章节 | 日期 | 幻灯片 | 视频 -- | -- | -- | -- 零代码构建 NEAR 应用 | 2021年12月30日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-5/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8817%EF%BC%89%EF%BC%9A%E9%9B%B6%E4%BB%A3%E7%A0%81%E6%9E%84%E5%BB%BA%20NEAR%20%E5%BA%94%E7%94%A8.pdf) | [播放](https://www.bilibili.com/video/BV1uZ4y1Q7dj) OIN 稳定币的实现与应用 | 2022年1月7日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-5/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8818%EF%BC%89%EF%BC%9AOIN%20%E7%A8%B3%E5%AE%9A%E5%B8%81%E5%8E%9F%E7%90%86%E4%B8%8E%E5%AE%9E%E7%8E%B0.pptx) | [播放](https://www.bilibili.com/video/BV1Ba411z76k) NEAR 节点和Indexer的搭建与运维 | 2022年1月11日 | [下载](https://github.com/near-x/ncd-cn/tree/master/cohorts/ncd-cn-5/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8819%EF%BC%89%EF%BC%9ANEAR%20%E8%8A%82%E7%82%B9%E5%92%8CIndexer%E7%9A%84%E6%90%AD%E5%BB%BA%E4%B8%8E%E8%BF%90%E7%BB%B4) | [播放](https://www.bilibili.com/video/BV11r4y1v7xb) Akash云计算及其在NEAR的应用 | 2022年1月13日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-5/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8820%EF%BC%89%EF%BC%9AAkash%E4%BA%91%E8%AE%A1%E7%AE%97%E5%8F%8A%E5%85%B6%E5%9C%A8NEAR%E7%9A%84%E5%BA%94%E7%94%A8.pdf) | [播放](https://www.bilibili.com/video/BV1iY411h7ZN) NEAR Linkdrop 详解 | 2022年1月18日 | | Web3.bio:黑客松获奖作品介绍 | 2022年1月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-5/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8821%EF%BC%89%EF%BC%9AWeb3.bio%EF%BC%9A%E5%9F%BA%E4%BA%8E%20NEAR%20%E7%9A%84%20Jamstack%20%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1gb4y1n7Jb/) NEAR 合约测试技巧 | 2022年1月25日 | | Flux:NEAR 和 Aurora 上的预言机 | 2022年1月27日 | | ## 课程幻灯片 ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第十九期) 2023年10月 ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 10月16日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 10月18日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 10月18日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 10月20日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | BOS 多链开发实践 | 10月25日 | [下载](https://bit.ly/ncd-cn-dapdap-bos-gateway) | [播放](https://www.bilibili.com/video/BV1kN411x7qX) | | Demo Day | 10月27日 | -- | -- | ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第七期) ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 4月18日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 4月20日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | NEAR AssemblyScript 智能合约开发 | 4月20日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T ) | | NEAR DApp 开发与常用工具 | 4月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 在线答疑 Office Hour | 4月24日 | -- | -- | | NEAR 合约测试方法 | 4月25日 | [代码](https://github.com/danielwpz/near-rust-contract-test) | [播放](https://www.bilibili.com/video/BV13S4y1w7HS/) | | 用 Sender 和 wallet selector 开发应用 | 4月27日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-7/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8825%EF%BC%89%EF%BC%9A%20%E7%94%A8Sender%E5%92%8CWallet%20Selector%E5%BC%80%E5%8F%91%E5%BA%94%E7%94%A8.pdf) | [播放](https://www.bilibili.com/video/BV1g34y1a7FS/) | | Demo Day | 4月29日 | -- | -- | ## 课程幻灯片 ## 课程幻灯片 # NEAR 认证开发者中文课程(第二期) ## 课程内容 章节 | 日期 | 幻灯片 | 视频 -- | -- | -- | -- NEAR 核心概念与应用架构 | 9月13日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-2/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV13v411w7Xf/) NEAR Rust 智能合约开发 | 9月15日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV12y4y1V7EL) NEAR AssemblyScript 智能合约开发 | 9月15日 | -- | [播放](https://www.bilibili.com/video/BV1Jf4y1w76T/) NEAR DApp 开发与常用工具 | 9月17日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1BM4y1L7Cj) 在线答疑时间 | 9月19日 | -- | -- NEAR 核心合约解读 | 9月22日 | | [播放](https://www.bilibili.com/video/BV15L41147eF/) NEAR 游戏开发实践 | 9月28日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-2/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%889%EF%BC%89%EF%BC%9ANEAR%20%E6%B8%B8%E6%88%8F%E5%BC%80%E5%8F%91%E5%AE%9E%E8%B7%B5.pdf) | [播放](https://www.bilibili.com/video/BV1ZU4y1A7RV/) 课程项目演示(Demo Day) | 9月30日 | [作品列表](https://docs.qq.com/sheet/DSVVqUUxEZ3hDbmNx?tab=BB08J3) | [播放](https://www.bilibili.com/video/BV1xv411G7Ba/) ## 课程幻灯片 # NEAR 认证开发者中文课程(第二十一期) 2024年1月 ## 课程内容 | 章节 | 时间 | 幻灯片 | 视频 | | ----- | ----- | ----- | ----- | | NEAR 核心概念与应用架构 | 1月22日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-6/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%881%EF%BC%89%EF%BC%9ANEAR%20%E6%A0%B8%E5%BF%83%E6%A6%82%E5%BF%B5%E4%B8%8E%E5%BA%94%E7%94%A8%E6%9E%B6%E6%9E%84.pdf) | [播放](https://www.bilibili.com/video/BV1AT4y1S7ms/) | | NEAR Rust 智能合约开发 | 1月24日 | [打开](https://shimo.im/presentation/NJkbW7V6XzcEv2AR/) | [播放](https://www.bilibili.com/video/BV1Jq4y1Y74z/) | | 用 JavaScript 开发 NEAR 智能合约 | 1月24日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-8/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%8826%EF%BC%89%EF%BC%9A%20%E7%94%A8%20JavaScript%20%E5%BC%80%E5%8F%91%20NEAR%20%E6%99%BA%E8%83%BD%E5%90%88%E7%BA%A6.pdf) | [播放](https://www.bilibili.com/video/BV1wS4y1z7oT/) | | NEAR DApp 开发与常用工具 | 1月26日 | [下载](https://github.com/near-x/ncd-cn/raw/master/cohorts/ncd-cn-1/slides/NEAR%20%E8%AE%A4%E8%AF%81%E5%BC%80%E5%8F%91%E8%80%85%EF%BC%883%EF%BC%89%EF%BC%9ANEAR%20DApp%20%E5%BC%80%E5%8F%91%E4%B8%8E%E5%B8%B8%E7%94%A8%E5%B7%A5%E5%85%B7.pdf) | [播放](https://www.bilibili.com/video/BV1vu411q7gp/) | | 账户NFT交易市场 | 2月1日 | [下载](https://bit.ly/ncd-cn-namesky) | [播放](https://www.bilibili.com/video/BV1mm41197Ea/) | | Demo Day | 2月2日 | -- | -- | ## 课程幻灯片
Peaceseller_NEAR-Practice
README.md as-pect.config.js asconfig.json package.json
https://app.patika.dev/peaceseller Build using npm ![image](https://user-images.githubusercontent.com/95380084/160666309-048d29d3-5524-4650-9a92-28dad6cf341c.png) Deploy to Near ![image](https://user-images.githubusercontent.com/95380084/160666454-e95a4b13-ba18-4a93-a7da-df63ad26d4db.png) Check transaction using Transaction Explorer https://explorer.testnet.near.org/transactions/ubg8QDcmuLc69j6hF5zLmfGmZsQLyV8UTvKC9ojS4oU ![image](https://user-images.githubusercontent.com/95380084/160666634-4ad3b771-3d43-4771-b32c-2d1b28e71604.png)
lewisgit_toy_amm
README.md amm Cargo.toml build.sh src constants.rs ft_core.rs internal.rs lib.rs utils.rs integration-tests rs Cargo.toml src tests.rs ts ava.config.js package.json src main.ava.ts
# Toy AMM This project introduces a demonstration of a simple Automated Market Making (AMM) contract implemented in Rust on the NEAR blockchain platform. The demonstration, ToyAMM, is based on the XYK model, similar to [UniswapV2](https://github.com/Uniswap/v2-core). It is initialized with two Fungible Tokens and allows for users to swap between them using the `swap_for_token` function. For simplicity, only the owner of the ToyAMM Contract is permitted to add liquidity, and extra rewards for liquidity providers are not included. To use ToyAMM, please follow the instructions provided in this document. # About Storing Fungbile Token Metadata After some considerations, I don't think it is necessary to store FT's metadata, because we can retrieve metadata simply by call `ft_metadata` of the FT contract. I think it is not a good idea to do cross-contract call in init function. And a little bit redundant to call another function to store metadata. Additionally, AMM only cares about its reserves in u128, exchange formula doesn't involve decimals. Decimals, ticker, and symbols are irrelevant information. So to keep the contract clear and simple, I didn't implement functions for getting Fungible Token's metadata on my ToyAMM. # Prerequisite ## Environment Setup ### Rust * Version: rustc 1.66.0 (69f9c33d7 2022-12-12) * Toolchain: wasm32-unknown-unknown * follow [Near Official Doc](https://docs.near.org/develop/contracts/introduction#rust-and-wasm) ### NodeJS * install [Node](https://github.com/nvm-sh/nvm) version v16.19.0 * install yarn ``` npm install -g yarn ``` ### Deployment Tools * install [NEAR CLI](https://docs.near.org/tools/near-cli#near-deploy) ### Dependencies For Ubuntu Users run the following ```shell apt install git pkg-config libssl-dev ``` For MacOS Users ```shell brew install git ``` # Testnet Deployment ## Contract Building 1. clone this project ```shell git clone https://github.com/lewisgit/toy_amm.git ``` 2. build contract ```shell cd toy_amm/amm ./build.sh ``` compiled contract file will locate in release folder ## Contract Deployment deploy AMM contract ```shell near dev-deploy --wasmFile amm/release/toy_amm.wasm --helperUrl https://near-contract-helper.onrender.com ``` Set the AMM acount id `export AMM=dev-1671796804763-30061579106765`. Add create a subaccount as contract owner by running: ```shell near create-account owner.$AMM --masterAccount $AMM --initialBalance 20 ``` Set Owner account id `export OWNER=owner.dev-1671796804763-30061579106765`. ## Fungible Token Deployment `Make sure every contract you deploy has differenct account id.` deploy Fungible Token(You can refer to deployment steps in details by directing to [FT](https://github.com/near-examples/FT)) 1. use project [FT](https://github.com/near-examples/FT) from [near-example](https://github.com/near-examples). In the root directory of this project, run: ```shell git clone https://github.com/near-examples/FT.git ``` 2. Deploy Fungible Token ```shell cd FT near dev-deploy --wasmFile FT/res/fungible_token.wasm --helperUrl https://near-contract-helper.onrender.com ``` 3. Deploy Fungible Token Twice and make sure Contracts are deployed to different account. FT0 and FT1 are used here to represent different Fungbile Token Contract. run `export FT0=dev-1671796926050-32416921021565` and `export FT1=dev-1671797065250-44306645033899` to store the Fungbile Tokens' account id. 4. Initialize FT0 and FT1 run the following commands for FT0 and FT1 respectively. ```shell near call $FT new '{"owner_id": "'$OWNER'", "total_supply": "1000000000000000", "metadata": { "spec": "ft-1.0.0", "name": "Example Token Name", "symbol": "EXLT", "decimals": $DECIMAL }}' --accountId $FT ``` replace `$DECIMAL` with your preferred one, and use correct `$FT`. Here, `$OWNER` is used as your contract owner account, you can also change it to another account. Register ToyAMM in FT0 and FT1: ```shell near call $FT storage_deposit '' --amount 0.00125 --accountId $AMM ``` replace $FT with `$FT0` and `$FT1` respectively. ## AMM Contract Initialization 1. After Fungible Tokens are deployed, initialize ToyAMM Contract by running: ```shell near call $AMM new '{"owner": "'$OWNER'", "token0": "'$FT0'", "token1": "'$FT1'"}' --accountId $AMM ``` ## Add Liquidity 1. Call Contract FT0 and FT1's `tf_transfer_call` to deposit tokens in ToyAMM. Run: ```shell near call $FT0 ft_transfer_call '{"receiver_id": "'$AMM'", "amount": "30000", "msg": "0"}' --accountId $OWNER --depositYocto "1" --gas "200000000000000" ``` ```shell near call $FT1 ft_transfer_call '{"receiver_id": "'$AMM'", "amount": "70000", "msg": "0"}' --accountId $OWNER --depositYocto "1" --gas "200000000000000" ``` without calling `ft_transfer_call` on both tokens, `add_liquidity` will fail to execute. 2. Call AMM `add_liquidity`: ```shell near call $AMM add_liquidity '{"token0_account": "'$FT0'","amount0_in": "30000", "token1_account": "'$FT1'", "amount1_in": "70000"}' --accountId $OWNER ``` after running `add_liquidity`, ToyAMM can be used for token exchange. ## Token Swap 1. create an user Alice: ```shell near create-account alice.$AMM --masterAccount $AMM --initialBalance 20 ``` add save it in env variable `export ALICE=alice.$AMM`. 2. Register Alice for FT0 and FT1: ```shell near call $FT storage_deposit '' --amount 0.00125 --accountId $ALICE ``` replace $FT with `$FT0` and `$FT1` respectively. 3. Transfer enough FT0 tokens to Alice. ```shell near call $FT0 ft_transfer '{"receiver_id": "'$ALICE'", "amount": "20", "msg": "0"}' --accountId $OWNER --depositYocto "1" --gas "200000000000000" ``` 4. Deposit token FT0 to ToyAMM. ```shell near call $FT0 ft_transfer_call '{"receiver_id": "'$AMM'", "amount": "20", "msg": "0"}' --accountId $ALICE --depositYocto "1" --gas "200000000000000" ``` 5. call ToyAMM `swap_for_token` method: ```shell near call $AMM swap_for_token '{"token_in": "'$FT0'", "token_out": "'$FT1'", "amount_in": "20"}' --accountId $ALICE ``` 6. Check FT1 balance of Alice ```shell near view $FT1 ft_balance_of '{"account_id": "'$ALICE'"}' ``` the terminal will print '46', which means by depositing 20\*10^-$DECIMALS_FT0 FT0, Alice exachange 46\*10^-$DECIMALS_FT1 FT1 through ToyAMM. `All balance are calculated in U128, therefore no need for special treatment of Tokens with arbitrary decimals`. the example account ids are all deployed on testnet, feel free to explore more about this project as you like. # Contract Testing Contract testing covers essential parts of ToyAMM, comprehensive testing is listed in TODO. ## Unit Test In the root directory of this project, run: ```shell cd amm cargo test ``` unit test will test functions of ToyAMM Contract. ## Rust Integration Test In the root directory of this project, run: ```shell cd integration-tests/rs cargo run --example integration-tests ``` ## TS Integration Test In the root directory of this project, run: ```shell cd integration-tests/ts yarn install yarn test ``` running TS Integration Test using node v18.12.0 will fail. (ref:https://github.com/near/workspaces-js/issues/168) integration tests will test cross contract call and add_liquidity funtion and swap_for_token function. # TODO 1. Comprehensive Contract Testing 2. Storage Management 3. Liquidity provider shares 4. AMM factory for convenient AMM contruction # FAQ 1. near-workspaces-js failure check your node version, make sure not version=v16.19.0, version >= v18 will cause bugs in near-workspaces. 2. run `NEAR CLI` timeout better do deployment on a server that locates in US. # References 1. Uniswap V2: https://github.com/Uniswap/v2-core 2. Near FT Tutorial: https://github.com/near-examples/ft-tutorial 3. Ref Finance: https://github.com/ref-finance 4. Fungible Token on NEAR: https://docs.near.org/develop/relevant-contracts/ft # LICENSE [LICENSE](LICENSE)
kilnfi_near-validator-watcher
.github release-drafter.yml README.md main.go pkg app flags.go http.go run.go utils.go metrics metrics.go utils.go utils_test.go near block.go call_function.go client.go protocol_config.go query.go status.go testutils server.go tx.go validators.go watcher config.go utils.go utils_test.go watcher.go watcher_test.go
# Near Validator Watcher [![License](https://img.shields.io/badge/license-MIT-blue)](https://opensource.org/licenses/MIT) **Near Validator Watcher** is a Prometheus exporter to help you monitor missed blocks & chunks of your validator. ![Near Validator Watcher Grafana Dashboard (Prometheus Exporter)](assets/near-validator-watcher-grafana-dashboard.jpg) ## ✨ Usage Example on mainnet using the default RPC endpoint. ### Via compiled binary Compiled binary can be found on the [Releases page](https://github.com/kilnfi/near-validator-watcher/releases). ```bash near-validator-watcher \ --node https://rpc.mainnet.near.org \ --validator kiln-1.poolv1.near ``` ### Via Docker Latest Docker image can be found on the [Packages page](https://github.com/kilnfi/near-validator-watcher/pkgs/container/near-validator-watcher). ```bash docker run --rm ghcr.io/kilnfi/near-validator-watcher:latest \ --node https://rpc.mainnet.near.org \ --validator kiln-1.poolv1.near ``` ### Available options ``` near-validator-watcher --help NAME: near-validator-watcher - NEAR validators monitoring tool USAGE: near-validator-watcher [global options] command [command options] [arguments...] COMMANDS: help, h Shows a list of commands or help for one command GLOBAL OPTIONS: --http-addr value http server address (default: ":8080") --log-level value log level (debug, info, warn, error) (default: "info") --namespace value prefix for Prometheus metrics (default: "near_validator_watcher") --no-color disable colored output (default: false) --node value rpc node endpoint to connect to (default: "https://rpc.mainnet.near.org") --refresh-rate value how often to call the rpc endpoint (default: 10s) --validator value [ --validator value ] validator pool id to track --help, -h show help --version, -v print the version ``` ## ❇️ Endpoints - `/metrics` exposed Prometheus metrics (see next section) - `/ready` responds OK when the node is synced - `/live` responds OK as soon as server is up & running correctly ## 📊 Prometheus metrics All metrics are by default prefixed by `near_validator_watcher` but this can be changed through options. Metrics (without prefix) | Description ----------------------------|------------------------------------------------------------------------- `block_number` | The number of most recent block `chain_id` | Near chain id `current_proposals_stake` | Current proposals `epoch_length` | Near epoch length as specified in the protocol `epoch_start_height` | Near epoch start height `next_validator_stake` | The next validators `prev_epoch_kickout` | Near previous epoch kicked out validators `protocol_version` | Current protocol version deployed to the blockchain `seat_price` | Validator seat price `sync_state` | Sync state `validator_blocks_expected` | Current amount of validator expected blocks `validator_blocks_produced` | Current amount of validator produced blocks `validator_chunks_expected` | Current amount of validator expected chunks `validator_chunks_produced` | Current amount of validator produced chunks `validator_rank` | Current rank of validator based on stake `validator_slashed` | Validators slashed `validator_stake` | Current amount of validator stake `version_build` | The Near node version build ## 📃 License [MIT License](LICENSE).
Hydronio_NCD-clinhist
clinhist .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs target .rustc_info.json release .fingerprint Inflector-f13c978d1aadb31b lib-inflector.json ahash-585ee5915143711e build-script-build-script-build.json borsh-derive-4784701a84f8ce93 lib-borsh-derive.json borsh-derive-internal-2d83324de3f96453 lib-borsh-derive-internal.json borsh-schema-derive-internal-d0d27d48fe706251 lib-borsh-schema-derive-internal.json crunchy-4aea0594f90fa7a8 build-script-build-script-build.json darling-d2b8c3738fe8d009 lib-darling.json darling_core-fe18357966a85c7f lib-darling_core.json darling_macro-49f160b362a44c0c lib-darling_macro.json fnv-d8204c1b5ebe0bd7 lib-fnv.json ident_case-9ba3244996047c5d lib-ident_case.json near-sdk-macros-0df99a57ae6336a1 lib-near-sdk-macros.json proc-macro-crate-63348857fc667045 lib-proc-macro-crate.json proc-macro2-4285eee214e776e7 lib-proc-macro2.json proc-macro2-6afb81fa8313a0a6 run-build-script-build-script-build.json proc-macro2-b0db05a18fdd060a build-script-build-script-build.json quote-13a8d32fe124988e lib-quote.json quote-4f109f35fffae2b0 run-build-script-build-script-build.json quote-bf57674ebeff5b89 build-script-build-script-build.json schemars-311a02be9654297b build-script-build-script-build.json schemars_derive-6efaea56e9049e33 lib-schemars_derive.json semver-093dc8cdeff206ce build-script-build-script-build.json serde-96176862628df8f3 build-script-build-script-build.json serde-cc837aef0fe53416 run-build-script-build-script-build.json serde-e81d735e78e5bc3d build-script-build-script-build.json serde-f70e4ef7b3a68da4 lib-serde.json serde_derive-8ddcde75b6166959 build-script-build-script-build.json serde_derive-b7735e686c7a8253 lib-serde_derive.json serde_derive-de38a3d0c2369a55 run-build-script-build-script-build.json serde_derive_internals-84da1bc726ca54d0 lib-serde_derive_internals.json serde_json-b94018c5e893da14 build-script-build-script-build.json serde_with_macros-8485496771a3bfbd lib-serde_with_macros.json strsim-2717fead44a6fc9e lib-strsim.json syn-500b794bbab3a3d1 lib-syn.json syn-75f7b0828465a20e run-build-script-build-script-build.json syn-c9fd26cee76c12c8 build-script-build-script-build.json toml-a890cdb03fcdeb0b lib-toml.json unicode-ident-51be5dfdc102386a lib-unicode-ident.json version_check-28922478539c9cad lib-version_check.json wee_alloc-10c79473ba7c8522 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-c1dbdff08e52ddac lib-ahash.json ahash-e9c8d9fc5a0f9a13 run-build-script-build-script-build.json base64-d9edbd2f2dc2d956 lib-base64.json borsh-03f50d664fe418f4 lib-borsh.json bs58-9f10c4b1b3984643 lib-bs58.json byteorder-9bfc0a7b6bd12f32 lib-byteorder.json cfg-if-051471ea479febcb lib-cfg-if.json crunchy-5f68feb4877f62f7 run-build-script-build-script-build.json crunchy-e2de7fd44095dfb1 lib-crunchy.json dyn-clone-08384b4209913bac lib-dyn-clone.json hashbrown-c765772b21efb6c4 lib-hashbrown.json hello_near-00ca379cccdf6430 lib-hello_near.json hex-5d60733e3d120d80 lib-hex.json itoa-462fd4b8d8e08994 lib-itoa.json memory_units-16900eb0f3221f3f lib-memory_units.json near-abi-538006492792a634 lib-near-abi.json near-sdk-f9ce863a3b1e8188 lib-near-sdk.json near-sys-8155e02f70b6f85e lib-near-sys.json once_cell-8137368909678986 lib-once_cell.json ryu-2864b9f286b1e2ac lib-ryu.json schemars-de5d78a9b7ea4ebb run-build-script-build-script-build.json schemars-ed7e79cdeae70733 lib-schemars.json semver-d22de4968044da7f lib-semver.json semver-e9ad1a8740d679c7 run-build-script-build-script-build.json serde-bf4140719f30e552 lib-serde.json serde-c101f72d91fe9de4 run-build-script-build-script-build.json serde_json-639fda9ca6fa70f9 run-build-script-build-script-build.json serde_json-7b8fb224331123c9 lib-serde_json.json serde_with-9aefbe85788504b5 lib-serde_with.json static_assertions-d95c8c5a77238f05 lib-static_assertions.json uint-173e7aaf9357cffa lib-uint.json wee_alloc-019678edf7d788ed run-build-script-build-script-build.json wee_alloc-c5fdfac1f46cc75c lib-wee_alloc.json build crunchy-5f68feb4877f62f7 out lib.rs wee_alloc-019678edf7d788ed out wee_alloc_static_array_backend_size_bytes.txt integration-tests Cargo.toml src tests.rs package-lock.json package.json package-lock.json package.json
# Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
gpteth_influencerfi
README.md backend app.py database.py influencerfi_utils.py models.py routes.py frontend app.js investment.js nft_creation.js token_creation.js smartcontract influencer_token.rs influencerfi_lib.rs investment_contract.rs nft_contract.rs staking_contract.rs
# influencerfi
pasan1227_blockchain-voting-app
.gitpod.yml README.md contract README.md build.sh build builder.c code.h hello_near.js methods.h deploy.sh neardev dev-account.env package-lock.json package.json src contract.ts tsconfig.json frontend App.js assets global.css logo-black.svg logo-white.svg components CallToActionSection.js ErrorComponent.js FeatureSection.js Footer.js HeroSection.js NewsLetterSection.js dist fetch.165263dc.js fetch.5aa4d3e3.js fetch.ba39af06.js index.0209d837.js index.04ab1e5b.js index.0c344416.css index.1228173e.css index.1fb39fd1.js index.471187ca.css index.500dfe0b.js index.5032f967.js index.8f81d6b3.css index.ab0485ab.css index.afd967ea.js index.bc0daea6.css index.html logo-black.4514ed42.svg logo-black.54439fde.svg logo-white.605d2742.svg logo-white.a7716062.svg index.html index.js near-wallet.js package-lock.json package.json pages AboutUs.js ContactUs.js GetStarted.js Home.js NewPoll.js PollingStation.js Polls.js start.sh styles AboutUs.css FeatureSection.css Footer.css GetStarted.css ui-components.js integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json rust-toolchain.toml
near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run build Start project on localhost: npm start If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```ts @NearBindgen({}) class HelloNear { greeting: string = "Hello"; @view // This method is read-only and can be called for free get_greeting(): string { return this.greeting; } @call // This method changes the state, for which it cost gas set_greeting({ greeting }: { greeting: string }): void { // Record a log permanently to the blockchain! near.log(`Saving greeting ${greeting}`); this.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
humanman_near-sample-thanks-tutorial
.forestry front_matter templates documentation-page.yml settings.yml README.md as-pect.config.js asconfig.json data settings.json gridsome.config.js gridsome.server.js jsconfig.json netlify.toml package.json src assets img logo-bright.svg logo-dark.svg logo_near_bright.svg logo_near_dark.svg components contract-ui near-connect.js contract-api.js contract-config.js main.js static README.md manifest.json sw.js tutorials editing-in-forestry.md getting-started.md thanks.md theme-configuration.md vetur.config.js
# ![NEAR](https://github.com/humanman/near-sample-thanks-tutorial/blob/master/src/assets/img/logo_near_bright.svg) This is my base application for creating rich tutorials focused on blockchain development. Currently, I am working on a tutorial for writing Smart Contracts on the NEAR protocol. Once completed, I will start a growing list of tutorial microsites built with this theme. I hope to see you back! ## Local installation for development 1. `$ git clone https://github.com/humanman/near-sample-thanks-tutorial project-name`. 2. `$ cd project-name` 3. `$ yarn` 4. `$ gridsome develop`. ## Deploy to Netlify [![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/humanman/near-sample-thanks-tutorial) This project has been pre-configured to work with [Forestry](https://forestry.io). Any changes you make in Forestry will be committed back to your repo. ✨ ## Credits * Creds to the [Samuel Horn](https://jamdocs.samuelhorn.com/) for making an awesome Gridsome template! ## License [MIT](https://github.com/humanman/near-sample-thanks-tutorial/blob/master/LICENSE) Add static files here. Files in this directory will be copied directly to `dist` folder during build. For example, /static/robots.txt will be located at https://yoursite.com/robots.txt. This file should be deleted.
izrake_PWPEvents
README-Gitpod.md README.md apiflask requirements.txt setup.py utils.py zkdonation.py as-pect.config.js asconfig.js assembly __tests__ as-pect.d.ts guestbook.spec.ts as_types.d.ts main.ts model.ts tsconfig.json babel.config.js neardev dev-account.env shared-test-staging test.near.json shared-test test.near.json package.json src App.js components DonateWidget index.js DonationHome index.js DonationRegistration index.js DonationSingle index.js EventHome index.js EventRegistration index.js EventSingle index.js Header index.js Home index.js Modal index.js UploadEncryptionCreds index.js UserEncryptionCreds index.js UserRegistration index.js config.js config index.js hooks index.js index.html index.js services NuCypherService.js index.js tests integration App-integration.test.js ui App-ui.test.js utils index.js
<p align="center"> <img src="https://github.com/izrake/PWPEvents/blob/master/screenshots/banner.png" alt="weve showcase"> </p> # PWPEvents Provide single platform for protest organizers to create events and allow others to join the event without publishing the location. ## Why PWPEvents? It's always a challenge for the protest organizers to track how many people are willing to participate in the protest. There are several scenarios in which general public don’t feel the same way as protest organizers, that can lead to very less participation once protest starts at some specific location. PWPEvents will help protest organizers to test their protest purpose with general public. PWPEvents will also help organizers to view the number of subscriber to the event. ## What are we protecting? We are protecting the events location or protest location. If people are really interested in the cause it doesn’t matter how far the event is happening people will try to reach the location if it is within certain range. PWPEvents will ensure to show event locations only those who have subscribed to the event once a specified quorum is reached as specified by the organizer. ## Tech Stack Under the Hood ### Near Protocol & Nucypher & Flask API & ReactJs PWPEvents is using Near Protocol for user verification, smart contract and data persistent <br> Nucypher to encrypt, store location data, policy assignment and decrypting data <br> Flask API to enable communication between React Web App and Nucypher node ## PWPEvents 50000 ft Bird Eye View ![](assets/ss1.png) <br> ![](assets/saveevntflow.png) <br> ![](assets/retrieveeventflow.png) ## Steps to get started with PWPEvents - Clone PWPEvents repository in the local machine - Install [Python](%28https://docs.python-guide.org/starting/install3/osx/%29) in local machine - Install [pipenv](https://pipenv-fork.readthedocs.io/en/latest/install.html) Once installation is completed it's time to create python virtual environment for flask api to start working #### Follow these steps to activate virtual environment - Activate virual environment by executing `pipenv shell` from the apiflask root folder - Once activation is done run `pip install -e .` from the root apiflask app #### Configure Flask APP - It's time to export variables to make flask api up and running - Run `export FLASK_APP=zkdonation.py` - Run `export FLASK_ENV=development` Before running flask app, make sure ursula is up and running at localhost port `10151` ### Setup Ursula - Clone [nucypher](https://github.com/nucypher/nucypher) code repo - Activate virtual environment from nucypher root folder - Run ursula by running `nucypher ursula run --dev --federated-only` - If command fails then install nucypher by running `pip install nucypher` - Re-run step 3 command - Once command executed successfully ursula will be running on port `10151` #### Run Flask App - Run flask app by running `flask run` - Flask API will start running on port `5000` Once Flask API and Ursula starts running, it's time to run our UI #### Run React App - Navigate to PWPEvents root folder - Open command line or terminal - Run `yarn` - Run `yarn dev:start` - React app will start on localhost port `1234` ## Test it by yourself Note: Our server running cost is much so we have decided to run the server for the specific timings If you need server up ping either @rekpero#3898 or @prashantmaurya#6839 [PWPEvents](pwpevents.centralus.cloudapp.azure.com) website http://pwpevents.centralus.cloudapp.azure.com/ ## Meet PWPEvents [https://www.loom.com/share/62970bc5955f49e78f40122401c8373a)](https://www.loom.com/share/62970bc5955f49e78f40122401c8373a) ## Special Thanks IlliaAtNear and Mike Purvis for extending their helping hands when we ran into multiple NEAR protocol issue. Kprasch and maclane for making sure all active query resolution on the nucypher discord groups
kiskesis_Near-spring4
.idea modules.xml vcs.xml README.md craco.config.js package.json public index.html manifest.json robots.txt senderContract .idea modules.xml vcs.xml Cargo.toml README-Windows.md README.md build.bat build.sh flags.sh fourth_challenge Cargo.toml src lib.rs res README.md test-approval-receiver Cargo.toml src lib.rs test-token-receiver Cargo.toml src lib.rs tests sim main.rs test_approval.rs test_core.rs test_enumeration.rs utils.rs src assets logo-black.svg logo-white.svg config.js global.css index.js pages home index.css index.js mint index.css index.js
# Folder that contains wasm files # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `yarn build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) Non-fungible Token (NFT) =================== [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/NFT) This repository includes an example implementation of a [non-fungible token] contract which uses [near-contract-standards] and [simulation] tests. [non-fungible token]: https://nomicon.io/Standards/NonFungibleToken/README.html [near-contract-standards]: https://github.com/near/near-sdk-rs/tree/master/near-contract-standards [simulation]: https://github.com/near/near-sdk-rs/tree/master/near-sdk-sim Prerequisites ============= If you're using Gitpod, you can skip this step. * Make sure Rust is installed per the prerequisites in [`near-sdk-rs`](https://github.com/near/near-sdk-rs). * Make sure [near-cli](https://github.com/near/near-cli) is installed. Explore this contract ===================== The source for this contract is in `nft/src/lib.rs`. It provides methods to manage access to tokens, transfer tokens, check access, and get token owner. Note, some further exploration inside the rust macros is needed to see how the `NonFungibleToken` contract is implemented. Building this contract ====================== Run the following, and we'll build our rust project up via cargo. This will generate our WASM binaries into our `res/` directory. This is the smart contract we'll be deploying onto the NEAR blockchain later. ```bash ./build.sh ``` Testing this contract ===================== We have some tests that you can run. For example, the following will run our simple tests to verify that our contract code is working. ```bash cargo test -- --nocapture ``` The more complex simulation tests aren't run with this command, but we can find them in `tests/sim`. Using this contract =================== ### Quickest deploy You can build and deploy this smart contract to a development account. [Dev Accounts](https://docs.near.org/docs/concepts/account#dev-accounts) are auto-generated accounts to assist in developing and testing smart contracts. Please see the [Standard deploy](#standard-deploy) section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/non_fungible_token.wasm ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing a key pair to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to set the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will initialize the contract using the `new` method: ```bash near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME ``` To view the NFT metadata: ```bash near view $CONTRACT_NAME nft_metadata ``` ### Standard deploy This smart contract will get deployed to your NEAR account. For this example, please create a new NEAR account. Because NEAR allows the ability to upgrade contracts on the same account, initialization functions must be cleared. If you'd like to run this example on a NEAR account that has had prior contracts deployed, please use the `near-cli` command `near delete`, and then recreate it in Wallet. To create (or recreate) an account, please follow the directions in [Test Wallet](https://wallet.testnet.near.org) or ([NEAR Wallet](https://wallet.near.org/) if we're using `mainnet`). In the project root, log in to your newly created account with `near-cli` by following the instructions after this command. near login To make this tutorial easier to copy/paste, we're going to set an environment variable for our account id. In the below command, replace `MY_ACCOUNT_NAME` with the account name we just logged in with, including the `.testnet` (or `.near` for `mainnet`): ID=MY_ACCOUNT_NAME We can tell if the environment variable is set correctly if our command line prints the account name after this command: echo $ID Now we can deploy the compiled contract in this example to your account: near deploy --wasmFile res/non_fungible_token.wasm --accountId $ID NFT contract should be initialized before usage. More info about the metadata at [nomicon.io](https://nomicon.io/Standards/NonFungibleToken/Metadata.html). But for now, we'll initialize with the default metadata. near call $ID new_default_meta '{"owner_id": "'$ID'"}' --accountId $ID We'll be able to view our metadata right after: near view $ID nft_metadata Then, let's mint our first token. This will create a NFT based on Olympus Mons where only one copy exists: near call $ID nft_mint '{"token_id": "0", "receiver_id": "'$ID'", "token_metadata": { "title": "Olympus Mons", "description": "Tallest mountain in charted solar system", "media": "https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Olympus_Mons_alt.jpg/1024px-Olympus_Mons_alt.jpg", "copies": 1}}' --accountId $ID --deposit 0.1 Transferring our NFT ==================== Let's set up an account to transfer our freshly minted token to. This account will be a sub-account of the NEAR account we logged in with originally via `near login`. near create-account alice.$ID --masterAccount $ID --initialBalance 10 Checking Alice's account for tokens: near view $ID nft_tokens_for_owner '{"account_id": "'alice.$ID'"}' Then we'll transfer over the NFT into Alice's account. Exactly 1 yoctoNEAR of deposit should be attached: near call $ID nft_transfer '{"token_id": "0", "receiver_id": "alice.'$ID'", "memo": "transfer ownership"}' --accountId $ID --depositYocto 1 Checking Alice's account again shows us that she has the Olympus Mons token. Notes ===== * The maximum balance value is limited by U128 (2**128 - 1). * JSON calls should pass U128 as a base-10 string. E.g. "100". * This does not include escrow functionality, as ft_transfer_call provides a superior approach. An escrow system can, of course, be added as a separate contract or additional functionality within this contract. AssemblyScript ============== Currently, AssemblyScript is not supported for this example. An old version can be found in the [NEP4 example](https://github.com/near-examples/NFT/releases/tag/nep4-example), but this is not recommended as it is out of date and does not follow the standards the NEAR SDK has set currently.
irfancoder_near-frontend3
.eslintrc.js README.md babel.config.js jsconfig.json package.json postcss.config.js public index.html src layouts index.js main.js pages index.js routes index.js store index.js modules contract.js user.js utils index.js near.js tailwind.config.js vue.config.js
# near-frontend3 ## Project setup ``` yarn install ``` ### Compiles and hot-reloads for development ``` yarn serve ``` ### Compiles and minifies for production ``` yarn build ``` ### Lints and fixes files ``` yarn lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/).
mdb1710_neardemo
.gitpod.yml README.md babel.config.js contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js node_modules @as-covers assembly CONTRIBUTING.md README.md index.ts package.json tsconfig.json core CONTRIBUTING.md README.md package.json glue README.md lib index.d.ts index.js package.json transform README.md lib index.d.ts index.js util.d.ts util.js node_modules visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js toString.d.ts toString.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformRange.d.ts transformRange.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json package.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @eslint eslintrc CHANGELOG.md README.md conf config-schema.js environments.js eslint-all.js eslint-recommended.js lib cascading-config-array-factory.js config-array-factory.js config-array config-array.js config-dependency.js extracted-config.js ignore-pattern.js index.js override-tester.js flat-compat.js index.js shared ajv.js config-ops.js config-validator.js deprecation-warnings.js naming.js relative-module-resolver.js types.js node_modules ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json @humanwhocodes config-array README.md api.js package.json object-schema .eslintrc.js .travis.yml README.md package.json src index.js merge-strategy.js object-schema.js validation-strategy.js tests merge-strategy.js object-schema.js validation-strategy.js acorn-jsx README.md index.d.ts index.js package.json xhtml.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json ajv .runkit_example.js README.md dist 2019.d.ts 2019.js 2020.d.ts 2020.js ajv.d.ts ajv.js compile codegen code.d.ts code.js index.d.ts index.js scope.d.ts scope.js errors.d.ts errors.js index.d.ts index.js jtd parse.d.ts parse.js serialize.d.ts serialize.js types.d.ts types.js names.d.ts names.js ref_error.d.ts ref_error.js resolve.d.ts resolve.js rules.d.ts rules.js util.d.ts util.js validate applicability.d.ts applicability.js boolSchema.d.ts boolSchema.js dataType.d.ts dataType.js defaults.d.ts defaults.js index.d.ts index.js keyword.d.ts keyword.js subschema.d.ts subschema.js core.d.ts core.js jtd.d.ts jtd.js refs data.json json-schema-2019-09 index.d.ts index.js meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.d.ts index.js meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.d.ts jtd-schema.js runtime equal.d.ts equal.js parseJson.d.ts parseJson.js quote.d.ts quote.js timestamp.d.ts timestamp.js ucs2length.d.ts ucs2length.js validation_error.d.ts validation_error.js standalone index.d.ts index.js instance.d.ts instance.js types index.d.ts index.js json-schema.d.ts json-schema.js jtd-schema.d.ts jtd-schema.js vocabularies applicator additionalItems.d.ts additionalItems.js additionalProperties.d.ts additionalProperties.js allOf.d.ts allOf.js anyOf.d.ts anyOf.js contains.d.ts contains.js dependencies.d.ts dependencies.js dependentSchemas.d.ts dependentSchemas.js if.d.ts if.js index.d.ts index.js items.d.ts items.js items2020.d.ts items2020.js not.d.ts not.js oneOf.d.ts oneOf.js patternProperties.d.ts patternProperties.js prefixItems.d.ts prefixItems.js properties.d.ts properties.js propertyNames.d.ts propertyNames.js thenElse.d.ts thenElse.js code.d.ts code.js core id.d.ts id.js index.d.ts index.js ref.d.ts ref.js discriminator index.d.ts index.js types.d.ts types.js draft2020.d.ts draft2020.js draft7.d.ts draft7.js dynamic dynamicAnchor.d.ts dynamicAnchor.js dynamicRef.d.ts dynamicRef.js index.d.ts index.js recursiveAnchor.d.ts recursiveAnchor.js recursiveRef.d.ts recursiveRef.js errors.d.ts errors.js format format.d.ts format.js index.d.ts index.js jtd discriminator.d.ts discriminator.js elements.d.ts elements.js enum.d.ts enum.js error.d.ts error.js index.d.ts index.js metadata.d.ts metadata.js nullable.d.ts nullable.js optionalProperties.d.ts optionalProperties.js properties.d.ts properties.js ref.d.ts ref.js type.d.ts type.js union.d.ts union.js values.d.ts values.js metadata.d.ts metadata.js next.d.ts next.js unevaluated index.d.ts index.js unevaluatedItems.d.ts unevaluatedItems.js unevaluatedProperties.d.ts unevaluatedProperties.js validation const.d.ts const.js dependentRequired.d.ts dependentRequired.js enum.d.ts enum.js index.d.ts index.js limitContains.d.ts limitContains.js limitItems.d.ts limitItems.js limitLength.d.ts limitLength.js limitNumber.d.ts limitNumber.js limitProperties.d.ts limitProperties.js multipleOf.d.ts multipleOf.js pattern.d.ts pattern.js required.d.ts required.js uniqueItems.d.ts uniqueItems.js lib 2019.ts 2020.ts ajv.ts compile codegen code.ts index.ts scope.ts errors.ts index.ts jtd parse.ts serialize.ts types.ts names.ts ref_error.ts resolve.ts rules.ts util.ts validate applicability.ts boolSchema.ts dataType.ts defaults.ts index.ts keyword.ts subschema.ts core.ts jtd.ts refs data.json json-schema-2019-09 index.ts meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.ts meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.ts runtime equal.ts parseJson.ts quote.ts timestamp.ts ucs2length.ts validation_error.ts standalone index.ts instance.ts types index.ts json-schema.ts jtd-schema.ts vocabularies applicator additionalItems.ts additionalProperties.ts allOf.ts anyOf.ts contains.ts dependencies.ts dependentSchemas.ts if.ts index.ts items.ts items2020.ts not.ts oneOf.ts patternProperties.ts prefixItems.ts properties.ts propertyNames.ts thenElse.ts code.ts core id.ts index.ts ref.ts discriminator index.ts types.ts draft2020.ts draft7.ts dynamic dynamicAnchor.ts dynamicRef.ts index.ts recursiveAnchor.ts recursiveRef.ts errors.ts format format.ts index.ts jtd discriminator.ts elements.ts enum.ts error.ts index.ts metadata.ts nullable.ts optionalProperties.ts properties.ts ref.ts type.ts union.ts values.ts metadata.ts next.ts unevaluated index.ts unevaluatedItems.ts unevaluatedProperties.ts validation const.ts dependentRequired.ts enum.ts index.ts limitContains.ts limitItems.ts limitLength.ts limitNumber.ts limitProperties.ts multipleOf.ts pattern.ts required.ts uniqueItems.ts package.json ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json as-bignum README.md assembly __tests__ as-pect.d.ts i128.spec.as.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts package.json asbuild README.md dist cli.d.ts cli.js commands build.d.ts build.js fmt.d.ts fmt.js index.d.ts index.js init cmd.d.ts cmd.js files asconfigJson.d.ts asconfigJson.js aspecConfig.d.ts aspecConfig.js assembly_files.d.ts assembly_files.js eslintConfig.d.ts eslintConfig.js gitignores.d.ts gitignores.js index.d.ts index.js indexJs.d.ts indexJs.js packageJson.d.ts packageJson.js test_files.d.ts test_files.js index.d.ts index.js interfaces.d.ts interfaces.js run.d.ts run.js test.d.ts test.js index.d.ts index.js main.d.ts main.js utils.d.ts utils.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json assemblyscript-json .eslintrc.js .travis.yml README.md assembly JSON.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json temp-docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md assemblyscript-regex .eslintrc.js .github workflows benchmark.yml release.yml test.yml README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __spec_tests__ generated.spec.ts __tests__ alterations.spec.ts as-pect.d.ts boundary-assertions.spec.ts capture-group.spec.ts character-classes.spec.ts character-sets.spec.ts characters.ts empty.ts quantifiers.spec.ts range-quantifiers.spec.ts regex.spec.ts utils.ts char.ts env.ts index.ts nfa matcher.ts nfa.ts types.ts walker.ts parser node.ts parser.ts string-iterator.ts walker.ts regexp.ts tsconfig.json util.ts benchmark benchmark.js package.json spec test-generator.js ts index.ts tsconfig.json assemblyscript-temporal .github workflows node.js.yml release.yml .vscode launch.json README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __tests__ README.md as-pect.d.ts date.spec.ts duration.spec.ts empty.ts plaindate.spec.ts plaindatetime.spec.ts plainmonthday.spec.ts plaintime.spec.ts plainyearmonth.spec.ts timezone.spec.ts zoneddatetime.spec.ts constants.ts date.ts duration.ts enums.ts env.ts index.ts instant.ts now.ts plaindate.ts plaindatetime.ts plainmonthday.ts plaintime.ts plainyearmonth.ts timezone.ts tsconfig.json tz __tests__ index.spec.ts rule.spec.ts zone.spec.ts iana.ts index.ts rule.ts zone.ts utils.ts zoneddatetime.ts development.md package.json tzdb README.md iana theory.html zoneinfo2tdf.pl assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md bin rtplot.js index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json astral-regex index.d.ts index.js package.json readme.md axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js CHANGELOG.md README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json csv-stringify README.md lib browser index.js sync.js es5 index.d.ts index.js sync.d.ts sync.js index.d.ts index.js sync.d.ts sync.js package.json debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js diff CONTRIBUTING.md README.md dist diff.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js doctrine CHANGELOG.md README.md lib doctrine.js typed.js utility.js package.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js enquirer CHANGELOG.md README.md index.d.ts index.js lib ansi.js combos.js completer.js interpolate.js keypress.js placeholder.js prompt.js prompts autocomplete.js basicauth.js confirm.js editable.js form.js index.js input.js invisible.js list.js multiselect.js numeral.js password.js quiz.js scale.js select.js snippet.js sort.js survey.js text.js toggle.js render.js roles.js state.js styles.js symbols.js theme.js timer.js types array.js auth.js boolean.js index.js number.js string.js utils.js package.json env-paths index.d.ts index.js package.json readme.md escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js package.json eslint-utils README.md index.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json eslint CHANGELOG.md README.md bin eslint.js conf category-list.json config-schema.js default-cli-options.js eslint-all.js eslint-recommended.js replacements.json lib api.js cli-engine cli-engine.js file-enumerator.js formatters checkstyle.js codeframe.js compact.js html.js jslint-xml.js json-with-metadata.js json.js junit.js stylish.js table.js tap.js unix.js visualstudio.js hash.js index.js lint-result-cache.js load-rules.js xml-escape.js cli.js config default-config.js flat-config-array.js flat-config-schema.js rule-validator.js eslint eslint.js index.js init autoconfig.js config-file.js config-initializer.js config-rule.js npm-utils.js source-code-utils.js linter apply-disable-directives.js code-path-analysis code-path-analyzer.js code-path-segment.js code-path-state.js code-path.js debug-helpers.js fork-context.js id-generator.js config-comment-parser.js index.js interpolate.js linter.js node-event-generator.js report-translator.js rule-fixer.js rules.js safe-emitter.js source-code-fixer.js timing.js options.js rule-tester index.js rule-tester.js rules accessor-pairs.js array-bracket-newline.js array-bracket-spacing.js array-callback-return.js array-element-newline.js arrow-body-style.js arrow-parens.js arrow-spacing.js block-scoped-var.js block-spacing.js brace-style.js callback-return.js camelcase.js capitalized-comments.js class-methods-use-this.js comma-dangle.js comma-spacing.js comma-style.js complexity.js computed-property-spacing.js consistent-return.js consistent-this.js constructor-super.js curly.js default-case-last.js default-case.js default-param-last.js dot-location.js dot-notation.js eol-last.js eqeqeq.js for-direction.js func-call-spacing.js func-name-matching.js func-names.js func-style.js function-call-argument-newline.js function-paren-newline.js generator-star-spacing.js getter-return.js global-require.js grouped-accessor-pairs.js guard-for-in.js handle-callback-err.js id-blacklist.js id-denylist.js id-length.js id-match.js implicit-arrow-linebreak.js indent-legacy.js indent.js index.js init-declarations.js jsx-quotes.js key-spacing.js keyword-spacing.js line-comment-position.js linebreak-style.js lines-around-comment.js lines-around-directive.js lines-between-class-members.js max-classes-per-file.js max-depth.js max-len.js max-lines-per-function.js max-lines.js max-nested-callbacks.js max-params.js max-statements-per-line.js max-statements.js multiline-comment-style.js multiline-ternary.js new-cap.js new-parens.js newline-after-var.js newline-before-return.js newline-per-chained-call.js no-alert.js no-array-constructor.js no-async-promise-executor.js no-await-in-loop.js no-bitwise.js no-buffer-constructor.js no-caller.js no-case-declarations.js no-catch-shadow.js no-class-assign.js no-compare-neg-zero.js no-cond-assign.js no-confusing-arrow.js no-console.js no-const-assign.js no-constant-condition.js no-constructor-return.js no-continue.js no-control-regex.js no-debugger.js no-delete-var.js no-div-regex.js no-dupe-args.js no-dupe-class-members.js no-dupe-else-if.js no-dupe-keys.js no-duplicate-case.js no-duplicate-imports.js no-else-return.js no-empty-character-class.js no-empty-function.js no-empty-pattern.js no-empty.js no-eq-null.js no-eval.js no-ex-assign.js no-extend-native.js no-extra-bind.js no-extra-boolean-cast.js no-extra-label.js no-extra-parens.js no-extra-semi.js no-fallthrough.js no-floating-decimal.js no-func-assign.js no-global-assign.js no-implicit-coercion.js no-implicit-globals.js no-implied-eval.js no-import-assign.js no-inline-comments.js no-inner-declarations.js no-invalid-regexp.js no-invalid-this.js no-irregular-whitespace.js no-iterator.js no-label-var.js no-labels.js no-lone-blocks.js no-lonely-if.js no-loop-func.js no-loss-of-precision.js no-magic-numbers.js no-misleading-character-class.js no-mixed-operators.js no-mixed-requires.js no-mixed-spaces-and-tabs.js no-multi-assign.js no-multi-spaces.js no-multi-str.js no-multiple-empty-lines.js no-native-reassign.js no-negated-condition.js no-negated-in-lhs.js no-nested-ternary.js no-new-func.js no-new-object.js no-new-require.js no-new-symbol.js no-new-wrappers.js no-new.js no-nonoctal-decimal-escape.js no-obj-calls.js no-octal-escape.js no-octal.js no-param-reassign.js no-path-concat.js no-plusplus.js no-process-env.js no-process-exit.js no-promise-executor-return.js no-proto.js no-prototype-builtins.js no-redeclare.js no-regex-spaces.js no-restricted-exports.js no-restricted-globals.js no-restricted-imports.js no-restricted-modules.js no-restricted-properties.js no-restricted-syntax.js no-return-assign.js no-return-await.js no-script-url.js no-self-assign.js no-self-compare.js no-sequences.js no-setter-return.js no-shadow-restricted-names.js no-shadow.js no-spaced-func.js no-sparse-arrays.js no-sync.js no-tabs.js no-template-curly-in-string.js no-ternary.js no-this-before-super.js no-throw-literal.js no-trailing-spaces.js no-undef-init.js no-undef.js no-undefined.js no-underscore-dangle.js no-unexpected-multiline.js no-unmodified-loop-condition.js no-unneeded-ternary.js no-unreachable-loop.js no-unreachable.js no-unsafe-finally.js no-unsafe-negation.js no-unsafe-optional-chaining.js no-unused-expressions.js no-unused-labels.js no-unused-vars.js no-use-before-define.js no-useless-backreference.js no-useless-call.js no-useless-catch.js no-useless-computed-key.js no-useless-concat.js no-useless-constructor.js no-useless-escape.js no-useless-rename.js no-useless-return.js no-var.js no-void.js no-warning-comments.js no-whitespace-before-property.js no-with.js nonblock-statement-body-position.js object-curly-newline.js object-curly-spacing.js object-property-newline.js object-shorthand.js one-var-declaration-per-line.js one-var.js operator-assignment.js operator-linebreak.js padded-blocks.js padding-line-between-statements.js prefer-arrow-callback.js prefer-const.js prefer-destructuring.js prefer-exponentiation-operator.js prefer-named-capture-group.js prefer-numeric-literals.js prefer-object-spread.js prefer-promise-reject-errors.js prefer-reflect.js prefer-regex-literals.js prefer-rest-params.js prefer-spread.js prefer-template.js quote-props.js quotes.js radix.js require-atomic-updates.js require-await.js require-jsdoc.js require-unicode-regexp.js require-yield.js rest-spread-spacing.js semi-spacing.js semi-style.js semi.js sort-imports.js sort-keys.js sort-vars.js space-before-blocks.js space-before-function-paren.js space-in-parens.js space-infix-ops.js space-unary-ops.js spaced-comment.js strict.js switch-colon-spacing.js symbol-description.js template-curly-spacing.js template-tag-spacing.js unicode-bom.js use-isnan.js utils ast-utils.js fix-tracker.js keywords.js lazy-loading-rule-map.js patterns letters.js unicode index.js is-combining-character.js is-emoji-modifier.js is-regional-indicator-symbol.js is-surrogate-pair.js valid-jsdoc.js valid-typeof.js vars-on-top.js wrap-iife.js wrap-regex.js yield-star-spacing.js yoda.js shared ajv.js ast-utils.js config-validator.js deprecation-warnings.js logging.js relative-module-resolver.js runtime-info.js string-utils.js traverser.js types.js source-code index.js source-code.js token-store backward-token-comment-cursor.js backward-token-cursor.js cursor.js cursors.js decorative-cursor.js filter-cursor.js forward-token-comment-cursor.js forward-token-cursor.js index.js limit-cursor.js padded-token-cursor.js skip-cursor.js utils.js messages all-files-ignored.js extend-config-missing.js failed-to-read-json.js file-not-found.js no-config-found.js plugin-conflict.js plugin-invalid.js plugin-missing.js print-config-with-directory-path.js whitespace-found.js node_modules ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json espree CHANGELOG.md README.md espree.js lib ast-node-types.js espree.js features.js options.js token-translator.js visitor-keys.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esquery README.md dist esquery.esm.js esquery.esm.min.js esquery.js esquery.lite.js esquery.lite.min.js esquery.min.js license.txt node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json parser.js esrecurse README.md esrecurse.js gulpfile.babel.js node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json estraverse README.md estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-deep-equal README.md es6 index.d.ts index.js react.d.ts react.js index.d.ts index.js package.json react.d.ts react.js fast-json-stable-stringify .eslintrc.yml .github FUNDING.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.d.ts index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json file-entry-cache README.md cache.js changelog.md package.json find-up index.d.ts index.js package.json readme.md flat-cache README.md changelog.md package.json src cache.js del.js utils.js flatted .github FUNDING.yml README.md SPECS.md cjs index.js package.json es.js esm index.js index.js min.js package.json php flatted.php types.d.ts follow-redirects README.md http.js https.js index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js ms index.js license.md package.json readme.md package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js functional-red-black-tree README.md bench test.js package.json rbtree.js test test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globals globals.json index.d.ts index.js package.json readme.md has-flag index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hasurl README.md index.js package.json ignore CHANGELOG.md README.md index.d.ts index.js legacy.js package.json import-fresh index.d.ts index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json interpret README.md index.js mjs-stub.js package.json is-core-module CHANGELOG.md README.md core.json index.js package.json test index.js is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.js package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json js-tokens CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-schema-traverse .eslintrc.yml .github FUNDING.yml workflows build.yml publish.yml README.md index.d.ts index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-stable-stringify-without-jsonify .travis.yml example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js replacer.js space.js str.js to-json.js levn README.md lib cast.js index.js parse-string.js package.json line-column README.md lib line-column.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.merge README.md index.js package.json lodash.sortby README.md index.js package.json lodash.truncate README.md index.js package.json long README.md dist long.js index.js package.json src long.js lru-cache README.md index.js package.json minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md natural-compare README.md index.js package.json near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt empty.ts generic.ts includeBytes.spec.ts main.ts max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts json.lib.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts maxHeap.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts datetime.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ empty.ts exportAs.ts model.ts sentences.ts singleton copy.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md parent-module index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-key index.d.ts index.js package.json readme.md path-parse README.md index.js package.json prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json rechoir .travis.yml README.md index.js lib extension.js normalize.js register.js package.json regexpp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json require-from-string index.js package.json readme.md require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve-from index.js package.json readme.md resolve SECURITY.md appveyor.yml example async.js sync.js index.js lib async.js caller.js core.js core.json is-core.js node-modules-paths.js normalize-options.js sync.js package.json test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json semver CHANGELOG.md README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md shelljs CHANGELOG.md README.md commands.js global.js make.js package.json plugin.js shell.js src cat.js cd.js chmod.js common.js cp.js dirs.js echo.js error.js exec-child.js exec.js find.js grep.js head.js ln.js ls.js mkdir.js mv.js popd.js pushd.js pwd.js rm.js sed.js set.js sort.js tail.js tempdir.js test.js to.js toEnd.js touch.js uniq.js which.js slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md table README.md dist alignString.d.ts alignString.js alignTableData.d.ts alignTableData.js calculateCellHeight.d.ts calculateCellHeight.js calculateCellWidths.d.ts calculateCellWidths.js calculateColumnWidths.d.ts calculateColumnWidths.js calculateRowHeights.d.ts calculateRowHeights.js createStream.d.ts createStream.js drawBorder.d.ts drawBorder.js drawContent.d.ts drawContent.js drawHeader.d.ts drawHeader.js drawRow.d.ts drawRow.js drawTable.d.ts drawTable.js generated validators.d.ts validators.js getBorderCharacters.d.ts getBorderCharacters.js index.d.ts index.js makeStreamConfig.d.ts makeStreamConfig.js makeTableConfig.d.ts makeTableConfig.js mapDataUsingRowHeights.d.ts mapDataUsingRowHeights.js padTableData.d.ts padTableData.js stringifyTableData.d.ts stringifyTableData.js table.d.ts table.js truncateTableData.d.ts truncateTableData.js types api.d.ts api.js internal.d.ts internal.js utils.d.ts utils.js validateConfig.d.ts validateConfig.js validateTableData.d.ts validateTableData.js wrapCell.d.ts wrapCell.js wrapString.d.ts wrapString.js wrapWord.d.ts wrapWord.js package.json tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json text-table .travis.yml example align.js center.js dotalign.js doubledot.js table.js index.js package.json test align.js ansi-colors.js center.js dotalign.js doubledot.js table.js tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json type-check README.md lib check.js index.js parse-type.js package.json type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts universal-url README.md browser.js index.js package.json uri-js README.md dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js ws.d.ts ws.js wss.d.ts wss.js uri.d.ts uri.js util.d.ts util.js package.json v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js word-wrap README.md index.d.ts index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json package-lock.json package.json | features not yet implemented issues with the tests differences between PCRE and JS regex | | | package.json src App.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
# type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) <a name="type-check" /> `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). npm install type-check ## Quick Examples ```js // Basic types: var typeCheck = require('type-check').typeCheck; typeCheck('Number', 1); // true typeCheck('Number', 'str'); // false typeCheck('Error', new Error); // true typeCheck('Undefined', undefined); // true // Comment typeCheck('count::Number', 1); // true // One type OR another type: typeCheck('Number | String', 2); // true typeCheck('Number | String', 'str'); // true // Wildcard, matches all types: typeCheck('*', 2) // true // Array, all elements of a single type: typeCheck('[Number]', [1, 2, 3]); // true typeCheck('[Number]', [1, 'str', 3]); // false // Tuples, or fixed length arrays with elements of different types: typeCheck('(String, Number)', ['str', 2]); // true typeCheck('(String, Number)', ['str']); // false typeCheck('(String, Number)', ['str', 2, 5]); // false // Object properties: typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true typeCheck('{x: Number, y: Boolean}', {x: 2}); // false typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true // A particular type AND object properties: typeCheck('RegExp{source: String, ...}', /re/i); // true typeCheck('RegExp{source: String, ...}', {source: 're'}); // false // Custom types: var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; typeCheck('Even', 2, opt); // true // Nested: var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true ``` Check out the [type syntax format](#syntax) and [guide](#guide). ## Usage `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. ```js // typeCheck(type, input, options); typeCheck('Number', 2); // true // parseType(type); var parsedType = parseType('Number'); // object // parsedTypeCheck(parsedType, input, options); parsedTypeCheck(parsedType, 2); // true ``` ### typeCheck(type, input, options) `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js typeCheck('Number', 2); // true ``` ### parseType(type) `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to parse ##### returns `Object` - an object in the parsed type format representing the parsed type ##### example ```js parseType('Number'); // [{type: 'Number'}] ``` ### parsedTypeCheck(parsedType, input, options) `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js parsedTypeCheck([{type: 'Number'}], 2); // true var parsedType = parseType('String'); parsedTypeCheck(parsedType, 'str'); // true ``` <a name="type-format" /> ## Type Format ### Syntax White space is ignored. The root node is a __Types__. * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` ### Guide `type-check` uses `Object.toString` to find out the basic type of a value. Specifically, ```js {}.toString.call(VALUE).slice(8, -1) {}.toString.call(true).slice(8, -1) // 'Boolean' ``` A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. The wildcard `*` matches all types. There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. ## Options Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. <a name="custom-types" /> ### Custom Types __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; } } } }; typeCheck('Even', 2, options); // true typeCheck('Even', 3, options); // false ``` `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. ## Technical About `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 10.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. # Optionator <a name="optionator" /> Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). [About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format) ## Why? The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. $ cmd --halp Invalid option '--halp' - perhaps you meant '--help'? $ cmd --count str Invalid value for option 'count' - expected type Int, received value: str. Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. ## About Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. MIT license. Version 0.9.1 npm install optionator For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. ## Usage `require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. ```js var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` ### parse(input, parseOptions) `parse` processes the `input` according to your settings, and returns an object with the results. ##### arguments * input - `[String] | Object | String` - the input you wish to parse * parseOptions - `{slice: Int}` - all options optional - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) ##### returns `Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. ##### example ```js parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} parse('--count 2 positional'); // {count: 2, _: ['positional']} parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} ``` ### parseArgv(input) `parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. ##### arguments * input - `[String]` - the input you wish to parse ##### returns See "returns" section in "parse" ##### example ```js parseArgv(process.argv); ``` ### generateHelp(helpOptions) `generateHelp` produces help text based on your settings. ##### arguments * helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` ##### returns `String` - the generated help text ##### example ```js generateHelp(); /* "Usage: cmd [options] positional -h, --help displays help -c, --count Int number of things Version 1.0.0 "*/ ``` ### generateHelpForOption(optionName) `generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. ##### arguments * optionName - `String` - the name of the option to display ##### returns `String` - the generated help text for the option ##### example ```js generateHelpForOption('count'); /* "-c, --count Int description: number of things example: cmd --count 2 "*/ ``` ## Settings Format When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: { prepend: String, append: String, options: [{heading: String} | { option: String, alias: [String] | String, type: String, enum: [String], default: String, restPositional: Boolean, required: Boolean, overrideRequired: Boolean, dependsOn: [String] | String, concatRepeatedArrays: Boolean | (Boolean, Object), mergeRepeatedObjects: Boolean, description: String, longDescription: String, example: [String] | String }], helpStyle: { aliasSeparator: String, typeSeparator: String, descriptionSeparator: String, initialIndent: Int, secondaryIndent: Int, maxPadFactor: Number }, mutuallyExclusive: [[String | [String]]], concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object mergeRepeatedObjects: Boolean, // deprecated, set in defaults object positionalAnywhere: Boolean, typeAliases: Object, defaults: Object } All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. ### Top Level Properties * `prepend` is an optional string to be placed before the options in the help text * `append` is an optional string to be placed after the options in the help text * `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified * `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text * `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present * `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` * `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` * `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property #### Heading Properties * `heading` a required string, the name of the heading #### Option Properties * `option` the required name of the option - use dash-case, without the leading dashes * `alias` is an optional string or array of strings which specify any aliases for the option * `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it * `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` * `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` * `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument * `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined * `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags * `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. * `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` * `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set * `description` is an optional string, which will be displayed next to the option in the help text * `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used * `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used #### Help Style Properties * `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' * `typeSeparator` is an optional string, separates the type from the names - default: ' ' * `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' * `initialIndent` is an optional int - the amount of indent for options - default: 2 * `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 * `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 ## Argument Format At the highest level there are two types of arguments: named, and positional. Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. Everything after an `--` is positional, even if it looks like a named argument. You may optionally use `=` to separate option names from values, for example: `--count=2`. If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. If duplicate named arguments are present, the last one will be taken. ## Technical About `optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value = <JSON.Value>valueOrNull; // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let innerString = (<JSON.Str>value).valueOf(); let jsonString = (<JSON.Str>value).stringify(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: string = encoder.stringify(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i64): void { // Handle field } setFloat(name: string, value: f64): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. <h1 align="center">Enquirer</h1> <p align="center"> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version"> </a> <a href="https://travis-ci.org/enquirer/enquirer"> <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis"> </a> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br> <sub>>_ Prompts should be more like conversations than inquisitions▌</sub> </p> <br> <p align="center"> <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br> <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br> <a href="#built-in-prompts"><strong>See more prompt examples</strong></a> </p> <br> <br> Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases. * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_) * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb). * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement. * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos. * **Intuitive** - Keypress combos are available to simplify usage. * **Flexible** - All prompts can be used standalone or chained together. * **Stylish** - Easily override semantic styles and symbols for any part of the prompt. * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts). * **Pluggable** - Add advanced features to Enquirer using plugins. * **Validation** - Optionally validate user input with any prompt. * **Well tested** - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values. * **Examples** - There are numerous [examples](examples) available to help you get started. If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks! <br> <p align="center"> <b>>_ Ready to start making prompts your users will love? ▌</b><br> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750"> </p> <br> <br> ## ❯ Getting started Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts. * [Install](#-install) * [Usage](#-usage) * [Enquirer](#-enquirer) * [Prompts](#-prompts) - [Built-in Prompts](#-prompts) - [Custom Prompts](#-custom-prompts) * [Key Bindings](#-key-bindings) * [Options](#-options) * [Release History](#-release-history) * [Performance](#-performance) * [About](#-about) <br> ## ❯ Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install enquirer --save ``` Install with [yarn](https://yarnpkg.com/en/): ```sh $ yarn add enquirer ``` <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750"> </p> _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_ <br> ## ❯ Usage ### Single prompt The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method. ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); // { username: 'jonschlinkert' } ``` _(Examples with `await` need to be run inside an `async` function)_ ### Multiple prompts Pass an array of ["question" objects](#prompt-options) to run a series of prompts. ```js const response = await prompt([ { type: 'input', name: 'name', message: 'What is your name?' }, { type: 'input', name: 'username', message: 'What is your username?' } ]); console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' } ``` ### Different ways to run enquirer #### 1. By importing the specific `built-in prompt` ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Did you like enquirer?' }); prompt.run() .then(answer => console.log('Answer:', answer)); ``` #### 2. By passing the options to `prompt` ```js const { prompt } = require('enquirer'); prompt({ type: 'confirm', name: 'question', message: 'Did you like enquirer?' }) .then(answer => console.log('Answer:', answer)); ``` **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings) <br> ## ❯ Enquirer **Enquirer is a prompt runner** Add Enquirer to your JavaScript project with following line of code. ```js const Enquirer = require('enquirer'); ``` The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts. ```js const { prompt } = require('enquirer'); const question = [ { type: 'input', name: 'username', message: 'What is your username?' }, { type: 'password', name: 'password', message: 'What is your password?' } ]; let answers = await prompt(question); console.log(answers); ``` **Prompts control how values are rendered and returned** Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application. **How can I customize prompts?** Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt. All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`. Use this approach if you need to modify a prompt instance, or listen for events on the prompt. **Example** ```js const { Input } = require('enquirer'); const prompt = new Input({ name: 'username', message: 'What is your username?' }); prompt.run() .then(answer => console.log('Username:', answer)) .catch(console.error); ``` ### [Enquirer](index.js#L20) Create an instance of `Enquirer`. **Params** * `options` **{Object}**: (optional) Options to use with all prompts. * `answers` **{Object}**: (optional) Answers object to initialize with. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` ### [register()](index.js#L42) Register a custom prompt type. **Params** * `type` **{String}** * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class. * `returns` **{Object}**: Returns the Enquirer instance **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); enquirer.register('customType', require('./custom-prompt')); ``` ### [prompt()](index.js#L78) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const response = await enquirer.prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` ### [use()](index.js#L160) Use an enquirer plugin. **Params** * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer. * `returns` **{Object}**: Returns the Enquirer instance. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const plugin = enquirer => { // do stuff to enquire instance }; enquirer.use(plugin); ``` ### [Enquirer#prompt](index.js#L210) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` <br> ## ❯ Prompts This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept. **Getting started with Enquirer's prompts** * [Prompt](#prompt) - The base `Prompt` class used by other prompts - [Prompt Options](#prompt-options) * [Built-in prompts](#built-in-prompts) * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts * [Custom prompts](#%E2%9D%AF-custom-prompts) - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use. ### Prompt The base `Prompt` class is used to create all other prompts. ```js const { Prompt } = require('enquirer'); class MyCustomPrompt extends Prompt {} ``` See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works. #### Prompt Options Each prompt takes an options object (aka "question" object), that implements the following interface: ```js { // required type: string | function, name: string | function, message: string | function | async function, // optional skip: boolean | function | async function, initial: string | function | async function, format: function | async function, result: function | async function, validate: function | async function, } ``` Each property of the options object is described below: | **Property** | **Required?** | **Type** | **Description** | | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. | | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. | | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. | | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. | | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. | | `format` | no | `function` | Function to format user input in the terminal. | | `result` | no | `function` | Function to format the final submitted value before it's returned. | | `validate` | no | `function` | Function to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message. | **Example usage** ```js const { prompt } = require('enquirer'); const question = { type: 'input', name: 'username', message: 'What is your username?' }; prompt(question) .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` <br> ### Built-in prompts * [AutoComplete Prompt](#autocomplete-prompt) * [BasicAuth Prompt](#basicauth-prompt) * [Confirm Prompt](#confirm-prompt) * [Form Prompt](#form-prompt) * [Input Prompt](#input-prompt) * [Invisible Prompt](#invisible-prompt) * [List Prompt](#list-prompt) * [MultiSelect Prompt](#multiselect-prompt) * [Numeral Prompt](#numeral-prompt) * [Password Prompt](#password-prompt) * [Quiz Prompt](#quiz-prompt) * [Survey Prompt](#survey-prompt) * [Scale Prompt](#scale-prompt) * [Select Prompt](#select-prompt) * [Sort Prompt](#sort-prompt) * [Snippet Prompt](#snippet-prompt) * [Toggle Prompt](#toggle-prompt) ### AutoComplete Prompt Prompt that auto-completes as the user types, and returns the selected value as a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750"> </p> **Example Usage** ```js const { AutoComplete } = require('enquirer'); const prompt = new AutoComplete({ name: 'flavor', message: 'Pick your favorite flavor', limit: 10, initial: 2, choices: [ 'Almond', 'Apple', 'Banana', 'Blackberry', 'Blueberry', 'Cherry', 'Chocolate', 'Cinnamon', 'Coconut', 'Cranberry', 'Grape', 'Nougat', 'Orange', 'Pear', 'Pineapple', 'Raspberry', 'Strawberry', 'Vanilla', 'Watermelon', 'Wintergreen' ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **AutoComplete Options** | Option | Type | Default | Description | | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. | | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. | | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. | | `initial` | `number` | 0 | Preselected item in the list of choices. | | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) | **Related prompts** * [Select](#select-prompt) * [MultiSelect](#multiselect-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### BasicAuth Prompt Prompt that asks for username and password to authenticate the user. The default implementation of `authenticate` function in `BasicAuth` prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the `authenticate` function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750"> </p> **Example Usage** ```js const { BasicAuth } = require('enquirer'); const prompt = new BasicAuth({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '123', showPassword: true }); prompt .run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Confirm Prompt Prompt that returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750"> </p> **Example Usage** ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Want to answer?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Form Prompt Prompt that allows the user to enter and submit multiple values on a single terminal screen. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750"> </p> **Example Usage** ```js const { Form } = require('enquirer'); const prompt = new Form({ name: 'user', message: 'Please provide the following information:', choices: [ { name: 'firstname', message: 'First Name', initial: 'Jon' }, { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' }, { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' } ] }); prompt.run() .then(value => console.log('Answer:', value)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Input Prompt Prompt that takes user input and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750"> </p> **Example Usage** ```js const { Input } = require('enquirer'); const prompt = new Input({ message: 'What is your username?', initial: 'jonschlinkert' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.log); ``` You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)). **Related prompts** * [Confirm](#confirm-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Invisible Prompt Prompt that takes user input, hides it from the terminal, and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750"> </p> **Example Usage** ```js const { Invisible } = require('enquirer'); const prompt = new Invisible({ name: 'secret', message: 'What is your secret?' }); prompt.run() .then(answer => console.log('Answer:', { secret: answer })) .catch(console.error); ``` **Related prompts** * [Password](#password-prompt) * [Input](#input-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### List Prompt Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750"> </p> **Example Usage** ```js const { List } = require('enquirer'); const prompt = new List({ name: 'keywords', message: 'Type comma-separated keywords' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Sort](#sort-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### MultiSelect Prompt Prompt that allows the user to select multiple items from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750"> </p> **Example Usage** ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: ['aqua', 'blue', 'fuchsia'] ``` **Example key-value pairs** Optionally, pass a `result` function and use the `.map` method to return an object of key-value pairs of the selected names and values: [example](./examples/multiselect/option-result.js) ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ], result(names) { return this.map(names); } }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' } ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Numeral Prompt Prompt that takes a number as input. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750"> </p> **Example Usage** ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ name: 'number', message: 'Please enter a number' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Confirm](#confirm-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Password Prompt Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt) <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750"> </p> **Example Usage** ```js const { Password } = require('enquirer'); const prompt = new Password({ name: 'password', message: 'What is your password?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Invisible](#invisible-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Quiz Prompt Prompt that allows the user to play multiple-choice quiz questions. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750"> </p> **Example Usage** ```js const { Quiz } = require('enquirer'); const prompt = new Quiz({ name: 'countries', message: 'How many countries are there in the world?', choices: ['165', '175', '185', '195', '205'], correctChoice: 3 }); prompt .run() .then(answer => { if (answer.correct) { console.log('Correct!'); } else { console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); } }) .catch(console.error); ``` **Quiz Options** | Option | Type | Required | Description | | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | | `choices` | `array` | Yes | The list of possible answers to the quiz question. | | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. | **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Survey Prompt Prompt that allows the user to provide feedback for a list of questions. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"> </p> **Example Usage** ```js const { Survey } = require('enquirer'); const prompt = new Survey({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.' }, { name: 'navigation', message: 'The website is easy to navigate.' }, { name: 'images', message: 'The website usually has good images.' }, { name: 'upload', message: 'The website makes it easy to upload images.' }, { name: 'colors', message: 'The website has a pleasing color palette.' } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [Scale](#scale-prompt) * [Snippet](#snippet-prompt) * [Select](#select-prompt) *** ### Scale Prompt A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale). <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750"> </p> **Example Usage** ```js const { Scale } = require('enquirer'); const prompt = new Scale({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.', initial: 2 }, { name: 'navigation', message: 'The website is easy to navigate.', initial: 2 }, { name: 'images', message: 'The website usually has good images.', initial: 2 }, { name: 'upload', message: 'The website makes it easy to upload images.', initial: 2 }, { name: 'colors', message: 'The website has a pleasing color palette.', initial: 2 } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Select Prompt Prompt that allows the user to select from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750"> </p> **Example Usage** ```js const { Select } = require('enquirer'); const prompt = new Select({ name: 'color', message: 'Pick a flavor', choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [MultiSelect](#multiselect-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Sort Prompt Prompt that allows the user to sort items in a list. **Example** In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750"> </p> **Example Usage** ```js const colors = require('ansi-colors'); const { Sort } = require('enquirer'); const prompt = new Sort({ name: 'colors', message: 'Sort the colors in order of preference', hint: 'Top is best, bottom is worst', numbered: true, choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ name: n, message: colors[n](n) })) }); prompt.run() .then(function(answer = []) { console.log(answer); console.log('Your preferred order of colors is:'); console.log(answer.map(key => colors[key](key)).join('\n')); }) .catch(console.error); ``` **Related prompts** * [List](#list-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Snippet Prompt Prompt that allows the user to replace placeholders in a snippet of code or text. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750"> </p> **Example Usage** ```js const semver = require('semver'); const { Snippet } = require('enquirer'); const prompt = new Snippet({ name: 'username', message: 'Fill out the fields in package.json', required: true, fields: [ { name: 'author_name', message: 'Author Name' }, { name: 'version', validate(value, state, item, index) { if (item && item.name === 'version' && !semver.valid(value)) { return prompt.styles.danger('version should be a valid semver value'); } return true; } } ], template: `{ "name": "\${name}", "description": "\${description}", "version": "\${version}", "homepage": "https://github.com/\${username}/\${name}", "author": "\${author_name} (https://github.com/\${username})", "repository": "\${username}/\${name}", "license": "\${license:ISC}" } ` }); prompt.run() .then(answer => console.log('Answer:', answer.result)) .catch(console.error); ``` **Related prompts** * [Survey](#survey-prompt) * [AutoComplete](#autocomplete-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Toggle Prompt Prompt that allows the user to toggle between two values then returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750"> </p> **Example Usage** ```js const { Toggle } = require('enquirer'); const prompt = new Toggle({ message: 'Want to answer?', enabled: 'Yep', disabled: 'Nope' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Confirm](#confirm-prompt) * [Input](#input-prompt) * [Sort](#sort-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Prompt Types There are 5 (soon to be 6!) type classes: * [ArrayPrompt](#arrayprompt) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [Choices](#choices) - [Defining choices](#defining-choices) - [Choice properties](#choice-properties) - [Related prompts](#related-prompts) * [AuthPrompt](#authprompt) * [BooleanPrompt](#booleanprompt) * DatePrompt (Coming Soon!) * [NumberPrompt](#numberprompt) * [StringPrompt](#stringprompt) Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how. ### ArrayPrompt The `ArrayPrompt` class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the [Select](#select) and [Survey](#survey) prompts. #### Options In addition to the [options](#options) available to all prompts, Array prompts also support the following options. | **Option** | **Required?** | **Type** | **Description** | | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | | | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. | | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. | | | #### Properties Array prompts have the following instance properties and getters. | **Property name** | **Type** | **Description** | | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. | | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. | | `enabled` | `array` | Returns an array of enabled choices. | | `focused` | `array` | Returns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is _focused_, the list will scroll to the focused choice and re-render. | | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. | | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. | | `limit` | `number` | The number of choices to display on-screen. | | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. | | `visible` | `string` | | #### Methods | **Method** | **Description** | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pointer()` | Returns the visual symbol to use to identify the choice that currently has focus. The `❯` symbol is often used for this. The pointer is not always visible, as with the `autocomplete` prompt. | | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. | | `focus()` | Sets focus on a choice, if it can be focused. | #### Choices Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal. **Type**: `string|object` **Example** ```js const { prompt } = require('enquirer'); const questions = [{ type: 'select', name: 'color', message: 'Favorite color?', initial: 1, choices: [ { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object ] }]; let answers = await prompt(questions); console.log('Answer:', answers.color); ``` #### Defining choices Whether defined as a string or object, choices are normalized to the following interface: ```js { name: string; message: string | undefined; value: string | undefined; hint: string | undefined; disabled: boolean | string | undefined; } ``` **Example** ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: ['Apple', 'Orange', 'Raspberry'] }; ``` Normalizes to the following when the prompt is run: ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: [ { name: 'Apple', message: 'Apple', value: 'Apple' }, { name: 'Orange', message: 'Orange', value: 'Orange' }, { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } ] }; ``` #### Choice properties The following properties are supported on `choice` objects. | **Option** | **Type** | **Description** | | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The unique key to identify a choice | | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. | | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. | | `choices` | `array` | Array of "child" choices. | | `hint` | `string` | Help message to display next to a choice. | | `role` | `string` | Determines how the choice will be displayed. Currently the only role supported is `separator`. Additional roles may be added in the future (like `heading`, etc). Please create a [feature request] | | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). | | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. | | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). | #### Related prompts * [AutoComplete](#autocomplete-prompt) * [Form](#form-prompt) * [MultiSelect](#multiselect-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) *** ### AuthPrompt The `AuthPrompt` is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the [BasicAuth Prompt](#basicauth-prompt). You can also find prompt examples in `examples/auth/` folder that utilizes `AuthPrompt` to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others. `AuthPrompt` has a factory function that creates an instance of `AuthPrompt` class and it expects an `authenticate` function, as an argument, which overrides the `authenticate` function of the `AuthPrompt` class. #### Methods | **Method** | **Description** | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticate()` | Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default `authenticate` function throws an error if no other function is provided. | #### Choices Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt). **Example** ```js const { AuthPrompt } = require('enquirer'); function authenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } const CustomAuthPrompt = AuthPrompt.create(authenticate); const prompt = new CustomAuthPrompt({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '1234567', choices: [ { name: 'username', message: 'username' }, { name: 'password', message: 'password' } ] }); prompt .run() .then(answer => console.log('Authenticated?', answer)) .catch(console.error); ``` #### Related prompts * [BasicAuth Prompt](#basicauth-prompt) *** ### BooleanPrompt The `BooleanPrompt` class is used for creating prompts that display and return a boolean value. ```js const { BooleanPrompt } = require('enquirer'); const prompt = new BooleanPrompt({ header: '========================', message: 'Do you love enquirer?', footer: '========================', }); prompt.run() .then(answer => console.log('Selected:', answer)) .catch(console.error); ``` **Returns**: `boolean` *** ### NumberPrompt The `NumberPrompt` class is used for creating prompts that display and return a numerical value. ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ header: '************************', message: 'Input the Numbers:', footer: '************************', }); prompt.run() .then(answer => console.log('Numbers are:', answer)) .catch(console.error); ``` **Returns**: `string|number` (number, or number formatted as a string) *** ### StringPrompt The `StringPrompt` class is used for creating prompts that display and return a string value. ```js const { StringPrompt } = require('enquirer'); const prompt = new StringPrompt({ header: '************************', message: 'Input the String:', footer: '************************' }); prompt.run() .then(answer => console.log('String is:', answer)) .catch(console.error); ``` **Returns**: `string` <br> ## ❯ Custom prompts With Enquirer 2.0, custom prompts are easier than ever to create and use. **How do I create a custom prompt?** Custom prompts are created by extending either: * Enquirer's `Prompt` class * one of the built-in [prompts](#-prompts), or * low-level [types](#-types). <!-- Example: HaiKarate Custom Prompt --> ```js const { Prompt } = require('enquirer'); class HaiKarate extends Prompt { constructor(options = {}) { super(options); this.value = options.initial || 0; this.cursorHide(); } up() { this.value++; this.render(); } down() { this.value--; this.render(); } render() { this.clear(); // clear previously rendered prompt from the terminal this.write(`${this.state.message}: ${this.value}`); } } // Use the prompt by creating an instance of your custom prompt class. const prompt = new HaiKarate({ message: 'How many sprays do you want?', initial: 10 }); prompt.run() .then(answer => console.log('Sprays:', answer)) .catch(console.error); ``` If you want to be able to specify your prompt by `type` so that it may be used alongside other prompts, you will need to first create an instance of `Enquirer`. ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` Then use the `.register()` method to add your custom prompt. ```js enquirer.register('haikarate', HaiKarate); ``` Now you can do the following when defining "questions". ```js let spritzer = require('cologne-drone'); let answers = await enquirer.prompt([ { type: 'haikarate', name: 'cologne', message: 'How many sprays do you need?', initial: 10, async onSubmit(name, value) { await spritzer.activate(value); //<= activate drone return value; } } ]); ``` <br> ## ❯ Key Bindings ### All prompts These key combinations may be used with all prompts. | **command** | **description** | | -------------------------------- | -------------------------------------- | | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. | | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. | <br> ### Move cursor These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>left</kbd> | Move the cursor back one character. | | <kbd>right</kbd> | Move the cursor forward one character. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> ### Edit Input These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> | **command (Mac)** | **command (Windows)** | **description** | | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. | | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. | | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | ### Select choices These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true. | **command** | **description** | | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. | | <kbd>i</kbd> | Invert the current selection of choices. | | <kbd>g</kbd> | Toggle the current choice group. | <br> ### Hide/show choices | **command** | **description** | | ------------------------------- | ---------------------------------------------- | | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. | | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. | <br> ### Move/lock Pointer | **command** | **description** | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>up</kbd> | Move the pointer up. | | <kbd>down</kbd> | Move the pointer down. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. | | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). | | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). | <br> | **command (Mac)** | **command (Windows)** | **description** | | -------------------------------- | --------------------- | ---------------------------------------------------------- | | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. | | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. | <br> ## ❯ Release History Please see [CHANGELOG.md](CHANGELOG.md). ## ❯ Performance ### System specs MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB. ### Load time Time it takes for the module to load the first time (average of 3 runs): ``` enquirer: 4.013ms inquirer: 286.717ms ``` <br> ## ❯ About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Todo We're currently working on documentation for the following items. Please star and watch the repository for updates! * [ ] Customizing symbols * [ ] Customizing styles (palette) * [ ] Customizing rendered input * [ ] Customizing returned values * [ ] Customizing key bindings * [ ] Question validation * [ ] Choice validation * [ ] Skipping questions * [ ] Async choices * [ ] Async timers: loaders, spinners and other animations * [ ] Links to examples </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ```sh $ yarn && yarn test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> #### Contributors | **Commits** | **Contributor** | | --- | --- | | 283 | [jonschlinkert](https://github.com/jonschlinkert) | | 82 | [doowb](https://github.com/doowb) | | 32 | [rajat-sr](https://github.com/rajat-sr) | | 20 | [318097](https://github.com/318097) | | 15 | [g-plane](https://github.com/g-plane) | | 12 | [pixelass](https://github.com/pixelass) | | 5 | [adityavyas611](https://github.com/adityavyas611) | | 5 | [satotake](https://github.com/satotake) | | 3 | [tunnckoCore](https://github.com/tunnckoCore) | | 3 | [Ovyerus](https://github.com/Ovyerus) | | 3 | [sw-yx](https://github.com/sw-yx) | | 2 | [DanielRuf](https://github.com/DanielRuf) | | 2 | [GabeL7r](https://github.com/GabeL7r) | | 1 | [AlCalzone](https://github.com/AlCalzone) | | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) | | 1 | [danieldelcore](https://github.com/danieldelcore) | | 1 | [ImgBotApp](https://github.com/ImgBotApp) | | 1 | [jsonkao](https://github.com/jsonkao) | | 1 | [knpwrs](https://github.com/knpwrs) | | 1 | [yeskunall](https://github.com/yeskunall) | | 1 | [mischah](https://github.com/mischah) | | 1 | [renarsvilnis](https://github.com/renarsvilnis) | | 1 | [sbugert](https://github.com/sbugert) | | 1 | [stephencweiss](https://github.com/stephencweiss) | | 1 | [skellock](https://github.com/skellock) | | 1 | [whxaxes](https://github.com/whxaxes) | #### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) #### Credit Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts. #### License Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv v7 beta is released [Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: - to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. - to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. - to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. - schemas are compiled to ES6 code (ES5 code generation is supported with an option). - to improve reliability and maintainability the code is migrated to TypeScript. **Please note**: - the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). - all formats are separated to ajv-formats package - they have to be explicitely added if you use them. See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. To install the new version: ```bash npm install ajv@beta ``` See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. ## Mozilla MOSS grant and OpenJS Foundation [<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js const rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # `asbuild` [![Stars](https://img.shields.io/github/stars/AssemblyScript/asbuild.svg?style=social&maxAge=3600&label=Star)](https://github.com/AssemblyScript/asbuild/stargazers) *A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.* ## 🚩 Table of Contents - [Installing](#-installing) - [Usage](#-usage) - [`asb init`](#asb-init---create-an-empty-project) - [`asb test`](#asb-test---run-as-pect-tests) - [`asb fmt`](#asb-fmt---format-as-files-using-eslint) - [`asb run`](#asb-run---run-a-wasi-binary) - [`asb build`](#asb-build---compile-the-project-using-asc) - [Background](#-background) ## 🔧 Installing Install it globally ``` npm install -g asbuild ``` Or, locally as dev dependencies ``` npm install --save-dev asbuild ``` ## 💡 Usage ``` Build tool for AssemblyScript projects. Usage: asb [command] [options] Commands: asb Alias of build command, to maintain back-ward compatibility [default] asb build Compile a local package and all of its dependencies [aliases: compile, make] asb init [baseDir] Create a new AS package in an given directory asb test Run as-pect tests asb fmt [paths..] This utility formats current module using eslint. [aliases: format, lint] Options: --version Show version number [boolean] --help Show help [boolean] ``` ### `asb init` - Create an empty project ``` asb init [baseDir] Create a new AS package in an given directory Positionals: baseDir Create a sample AS project in this directory [string] [default: "."] Options: --version Show version number [boolean] --help Show help [boolean] --yes Skip the interactive prompt [boolean] [default: false] ``` ### `asb test` - Run as-pect tests ``` asb test Run as-pect tests USAGE: asb test [options] -- [aspect_options] Options: --version Show version number [boolean] --help Show help [boolean] --verbose, --vv Print out arguments passed to as-pect [boolean] [default: false] ``` ### `asb fmt` - Format AS files using ESlint ``` asb fmt [paths..] This utility formats current module using eslint. Positionals: paths Paths to format [array] [default: ["."]] Initialisation: --init Generates recommended eslint config for AS Projects [boolean] Miscellaneous --lint, --dry-run Tries to fix problems without saving the changes to the file system [boolean] [default: false] Options: --version Show version number [boolean] --help Show help ``` ### `asb run` - Run a WASI binary ``` asb run Run a WASI binary USAGE: asb run [options] [binary path] -- [binary options] Positionals: binary path to Wasm binary [string] [required] Options: --version Show version number [boolean] --help Show help [boolean] --preopen, -p comma separated list of directories to open. [default: "."] ``` ### `asb build` - Compile the project using asc ``` asb build Compile a local package and all of its dependencies USAGE: asb build [entry_file] [options] -- [asc_options] Options: --version Show version number [boolean] --help Show help [boolean] --baseDir, -d Base directory of project. [string] [default: "."] --config, -c Path to asconfig file [string] [default: "./asconfig.json"] --wat Output wat file to outDir [boolean] [default: false] --outDir Directory to place built binaries. Default "./build/<target>/" [string] --target Target for compilation [string] [default: "release"] --verbose Print out arguments passed to asc [boolean] [default: false] Examples: asb build Build release of 'assembly/index.ts to build/release/packageName.wasm asb build --target release Build a release binary asb build -- --measure Pass argument to 'asc' ``` #### Defaults ##### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ##### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./tests/build_test) ## 📖 Background Asbuild started as wrapper around `asc` to provide an easier CLI interface and now has been extened to support other commands like `init`, `test` and `fmt` just like `cargo` to become a one stop build tool for AS Projects. ## 📜 License This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/). # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 66 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP/HTTPS Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true ### WS/WSS Support URI.parse("wss://example.com/foo?bar=baz"); //returns: //{ // scheme : "wss", // host: "example.com", // resourceName: "/foo?bar=baz", // secure: true, //} URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "uuid", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: npm install uri-js # OR yarn add uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.mjs': '/absolute/path/to/interpret/mjs-stub.js', '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', 'sucrase/register/ts', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', 'sucrase/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>. See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. You can install via npm `npm install prelude-ls` ### Development `make test` to test `make build` to build `lib` from `src` `make build-browser` to build browser versions # lodash.truncate v4.4.2 The [lodash](https://lodash.com/) method `_.truncate` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.truncate ``` In Node.js: ```js var truncate = require('lodash.truncate'); ``` See the [documentation](https://lodash.com/docs#truncate) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.truncate) for more details. cartoonvote Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. # lodash.merge v4.6.2 The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.merge ``` In Node.js: ```js var merge = require('lodash.merge'); ``` See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # regexpp [![npm version](https://img.shields.io/npm/v/regexpp.svg)](https://www.npmjs.com/package/regexpp) [![Downloads/month](https://img.shields.io/npm/dm/regexpp.svg)](http://www.npmtrends.com/regexpp) [![Build Status](https://github.com/mysticatea/regexpp/workflows/CI/badge.svg)](https://github.com/mysticatea/regexpp/actions) [![codecov](https://codecov.io/gh/mysticatea/regexpp/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/regexpp) [![Dependency Status](https://david-dm.org/mysticatea/regexpp.svg)](https://david-dm.org/mysticatea/regexpp) A regular expression parser for ECMAScript. ## 💿 Installation ```bash $ npm install regexpp ``` - require Node.js 8 or newer. ## 📖 Usage ```ts import { AST, RegExpParser, RegExpValidator, RegExpVisitor, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST } from "regexpp" ``` ### parseRegExpLiteral(source, options?) Parse a given regular expression literal then make AST object. This is equivalent to `new RegExpParser(options).parseLiteral(source)`. - **Parameters:** - `source` (`string | RegExp`) The source code to parse. - `options?` ([`RegExpParser.Options`]) The options to parse. - **Return:** - The AST of the regular expression. ### validateRegExpLiteral(source, options?) Validate a given regular expression literal. This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. - **Parameters:** - `source` (`string`) The source code to validate. - `options?` ([`RegExpValidator.Options`]) The options to validate. ### visitRegExpAST(ast, handlers) Visit each node of a given AST. This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. ### RegExpParser #### new RegExpParser(options?) - **Parameters:** - `options?` ([`RegExpParser.Options`]) The options to parse. #### parser.parseLiteral(source, start?, end?) Parse a regular expression literal. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression. #### parser.parsePattern(source, start?, end?, uFlag?) Parse a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"abc"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. - **Return:** - The AST of the regular expression pattern. #### parser.parseFlags(source, start?, end?) Parse a regular expression flags. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"gim"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression flags. ### RegExpValidator #### new RegExpValidator(options) - **Parameters:** - `options` ([`RegExpValidator.Options`]) The options to validate. #### validator.validateLiteral(source, start, end) Validate a regular expression literal. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. #### validator.validatePattern(source, start, end, uFlag) Validate a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. #### validator.validateFlags(source, start, end) Validate a regular expression flags. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. ### RegExpVisitor #### new RegExpVisitor(handlers) - **Parameters:** - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. #### visitor.visit(ast) Validate a regular expression literal. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. ## 📰 Changelog - [GitHub Releases](https://github.com/mysticatea/regexpp/releases) ## 🍻 Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. - `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. - `npm run lint` runs ESLint. - `npm run update:test` updates test fixtures. - `npm run update:ids` updates `src/unicode/ids.ts`. - `npm run watch` runs tests with `--watch` option. [`AST.Node`]: src/ast.ts#L4 [`RegExpParser.Options`]: src/parser.ts#L539 [`RegExpValidator.Options`]: src/validator.ts#L127 [`RegExpVisitor.Handlers`]: src/visitor.ts#L204 # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png [1]: https://travis-ci.org/litejs/natural-compare-lite [2]: https://coveralls.io/r/litejs/natural-compare-lite [npm package]: https://npmjs.org/package/natural-compare-lite [GitHub repo]: https://github.com/litejs/natural-compare-lite @version 1.4.0 @date 2015-10-26 @stability 3 - Stable Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2] =============== Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering". ```text Standard sorting: Natural order sorting: img1.png img1.png img10.png img2.png img12.png img10.png img2.png img12.png ``` String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function. ### Installation - In browser ```html <script src=min.natural-compare.js></script> ``` - In node.js: `npm install natural-compare-lite` ```javascript require("natural-compare-lite") ``` ### Usage ```javascript // Simple case sensitive example var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; a.sort(String.naturalCompare); // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] // Use wrapper function for case insensitivity a.sort(function(a, b){ return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); }) // In most cases we want to sort an array of objects var a = [ {"street":"350 5th Ave", "room":"A-1021"} , {"street":"350 5th Ave", "room":"A-21046-b"} ]; // sort by street, then by room a.sort(function(a, b){ return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); }) // When text transformation is needed (eg toLowerCase()), // it is best for performance to keep // transformed key in that object. // There are no need to do text transformation // on each comparision when sorting. var a = [ {"make":"Audi", "model":"A6"} , {"make":"Kia", "model":"Rio"} ]; // sort by make, then by model a.map(function(car){ car.sort_key = (car.make + " " + car.model).toLowerCase(); }) a.sort(function(a, b){ return String.naturalCompare(a.sort_key, b.sort_key); }) ``` - Works well with dates in ISO format eg "Rev 2012-07-26.doc". ### Custom alphabet It is possible to configure a custom alphabet to achieve a desired order. ```javascript // Estonian alphabet String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" ["t", "z", "x", "õ"].sort(String.naturalCompare) // ["z", "t", "õ", "x"] // Russian alphabet String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" ["Ё", "А", "Б"].sort(String.naturalCompare) // ["А", "Б", "Ё"] ``` External links -------------- - [GitHub repo][https://github.com/litejs/natural-compare-lite] - [jsperf test](http://jsperf.com/natural-sort-2/12) Licence ------- Copyright (c) 2012-2015 Lauri Rooden &lt;[email protected]&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore). Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module. ##### Tested on - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - [Guide for 2.x -> 3.x](#upgrade-2x---3x) - [Guide for 3.x -> 4.x](#upgrade-3x---4x) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array<Pathname>): Array<Pathname> ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory. ```js // WRONG ig.ignores('./abc') // WRONG, for it will never happen. // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js ig.add('config/') // `ig` does NOT know if 'config' is a normal file, directory or something ig.ignores('config') // And it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` **** # Upgrade Guide ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Aliases Create custom aliases for styles. ```js const colors = require('ansi-colors'); colors.alias('primary', colors.yellow); colors.alias('secondary', colors.bold); console.log(colors.primary.secondary('Foo')); ``` ## Themes A theme is an object of custom aliases. ```js const colors = require('ansi-colors'); colors.theme({ danger: colors.red, dark: colors.dim.gray, disabled: colors.gray, em: colors.italic, heading: colors.bold.underline, info: colors.cyan, muted: colors.dim, primary: colors.blue, strong: colors.bold, success: colors.green, underline: colors.underline, warning: colors.yellow }); // Now, we can use our custom styles alongside the built-in styles! console.log(colors.danger.strong.em('Error!')); console.log(colors.warning('Heads up!')); console.log(colors.info('Did you know...')); console.log(colors.success.bold('It worked!')); ``` ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 48 | [jonschlinkert](https://github.com/jonschlinkert) | | 42 | [doowb](https://github.com/doowb) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._ # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind ## assemblyscript-temporal An implementation of temporal within AssemblyScript, with an initial focus on non-timezone-aware classes and functionality. ### Why? AssemblyScript has minimal `Date` support, however, the JS Date API itself is terrible and people tend not to use it that often. As a result libraries like moment / luxon have become staple replacements. However, there is now a [relatively mature TC39 proposal](https://github.com/tc39/proposal-temporal) that adds greatly improved date support to JS. The goal of this project is to implement Temporal for AssemblyScript. ### Usage This library currently supports the following types: #### `PlainDateTime` A `PlainDateTime` represents a calendar date and wall-clock time that does not carry time zone information, e.g. December 7th, 1995 at 3:00 PM (in the Gregorian calendar). For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindatetime.html), this implementation follows the specification as closely as possible. You can create a `PlainDateTime` from individual components, a string or an object literal: ```javascript datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.year; // 2019; datetime.month; // 11; // ... datetime.nanosecond; // 789; datetime = PlainDateTime.from("1976-11-18T12:34:56"); datetime.toString(); // "1976-11-18T12:34:56" datetime = PlainDateTime.from({ year: 1966, month: 3, day: 3 }); datetime.toString(); // "1966-03-03T00:00:00" ``` There are various ways you can manipulate a date: ```javascript // use 'with' to copy a date but with various property values overriden datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.with({ year: 2019 }).toString(); // "2019-11-18T15:23:30.123456789" // use 'add' or 'substract' to add / subtract a duration datetime = PlainDateTime.from("2020-01-12T15:00"); datetime.add({ months: 1 }).toString(); // "2020-02-12T15:00:00"); // add / subtract support Duration objects or object literals datetime.add(new Duration(1)).toString(); // "2021-01-12T15:00:00"); ``` You can compare dates and check for equality ```javascript dt1 = PlainDateTime.from("1976-11-18"); dt2 = PlainDateTime.from("2019-10-29"); PlainDateTime.compare(dt1, dt1); // 0 PlainDateTime.compare(dt1, dt2); // -1 dt1.equals(dt1); // true ``` Currently `PlainDateTime` only supports the ISO 8601 (Gregorian) calendar. #### `PlainDate` A `PlainDate` object represents a calendar date that is not associated with a particular time or time zone, e.g. August 24th, 2006. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindate.html), this implementation follows the specification as closely as possible. The `PlainDate` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainTime` A `PlainTime` object represents a wall-clock time that is not associated with a particular date or time zone, e.g. 7:39 PM. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaintime.html), this implementation follows the specification as closely as possible. The `PlainTime` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainMonthDay` A date without a year component. This is useful to express things like "Bastille Day is on the 14th of July". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainmonthday.html) , this implementation follows the specification as closely as possible. ```javascript const monthDay = PlainMonthDay.from({ month: 7, day: 14 }); // => 07-14 const date = monthDay.toPlainDate({ year: 2030 }); // => 2030-07-14 date.dayOfWeek; // => 7 ``` The `PlainMonthDay` API is almost identical to `PlainDateTime`, so see above for more API usage examples. #### `PlainYearMonth` A date without a day component. This is useful to express things like "the October 2020 meeting". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainyearmonth.html) , this implementation follows the specification as closely as possible. The `PlainYearMonth` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `now` The `now` object has several methods which give information about the current time and date. ```javascript dateTime = now.plainDateTimeISO(); dateTime.toString(); // 2021-04-01T12:05:47.357 ``` ## Contributing This project is open source, MIT licensed and your contributions are very much welcomed. There is a [brief document that outlines implementation progress and priorities](./development.md). # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). # flatted [![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) ![snow flake](./flatted.jpg) <sup>**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**</sup> A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). Now available also for **[PHP](./php/flatted.php)**. ```js npm i flatted ``` Usable via [CDN](https://unpkg.com/flatted) or as regular module. ```js // ESM import {parse, stringify, toJSON, fromJSON} from 'flatted'; // CJS const {parse, stringify, toJSON, fromJSON} = require('flatted'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}] ``` ## toJSON and from JSON If you'd like to implicitly survive JSON serialization, these two helpers helps: ```js import {toJSON, fromJSON} from 'flatted'; class RecursiveMap extends Map { static fromJSON(any) { return new this(fromJSON(any)); } toJSON() { return toJSON([...this.entries()]); } } const recursive = new RecursiveMap; const same = {}; same.same = same; recursive.set('same', same); const asString = JSON.stringify(recursive); const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); asMap.get('same') === asMap.get('same').same; // true ``` ## Flatted VS JSON As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. ### New in V1: Exact same JSON API * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. ### Compatibility All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. ### How does it work ? While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` Once parsed, all indexes will be replaced through the flattened collection. <sup><sub>`*` represented as string to avoid conflicts with numbers</sub></sup> ```js // logic example var a = [{one: 1}, {two: '2'}]; a[0].a = a; // a is the main object, will be at index '0' // {one: 1} is the second object, index '1' // {two: '2'} the third, in '2', and it has a string // which will be found at index '3' Flatted.stringify(a); // [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] // a[one,two] {one: 1, a} {two: '2'} '2' ``` # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config # assemblyscript-regex A regex engine for AssemblyScript. [AssemblyScript](https://www.assemblyscript.org/) is a new language, based on TypeScript, that runs on WebAssembly. AssemblyScript has a lightweight standard library, but lacks support for Regular Expression. The project fills that gap! This project exposes an API that mirrors the JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class: ```javascript const regex = new RegExp("fo*", "g"); const str = "table football, foul"; let match: Match | null = regex.exec(str); while (match != null) { // first iteration // match.index = 6 // match.matches[0] = "foo" // second iteration // match.index = 16 // match.matches[0] = "fo" match = regex.exec(str); } ``` ## Project status The initial focus of this implementation has been feature support and functionality over performance. It currently supports a sufficient number of regex features to be considered useful, including most character classes, common assertions, groups, alternations, capturing groups and quantifiers. The next phase of development will focussed on more extensive testing and performance. The project currently has reasonable unit test coverage, focussed on positive and negative test cases on a per-feature basis. It also includes a more exhaustive test suite with test cases borrowed from another regex library. ### Feature support Based on the classfication within the [MDN cheatsheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) **Character sets** - [x] . - [x] \d - [x] \D - [x] \w - [x] \W - [x] \s - [x] \S - [x] \t - [x] \r - [x] \n - [x] \v - [x] \f - [ ] [\b] - [ ] \0 - [ ] \cX - [x] \xhh - [x] \uhhhh - [ ] \u{hhhh} or \u{hhhhh} - [x] \ **Assertions** - [x] ^ - [x] $ - [ ] \b - [ ] \B **Other assertions** - [ ] x(?=y) Lookahead assertion - [ ] x(?!y) Negative lookahead assertion - [ ] (?<=y)x Lookbehind assertion - [ ] (?<!y)x Negative lookbehind assertion **Groups and ranges** - [x] x|y - [x] [xyz][a-c] - [x] [^xyz][^a-c] - [x] (x) capturing group - [ ] \n back reference - [ ] (?<Name>x) named capturing group - [x] (?:x) Non-capturing group **Quantifiers** - [x] x\* - [x] x+ - [x] x? - [x] x{n} - [x] x{n,} - [x] x{n,m} - [ ] x\*? / x+? / ... **RegExp** - [x] global - [ ] sticky - [x] case insensitive - [x] multiline - [x] dotAll - [ ] unicode ### Development This project is open source, MIT licenced and your contributions are very much welcomed. To get started, check out the repository and install dependencies: ``` $ npm install ``` A few general points about the tools and processes this project uses: - This project uses prettier for code formatting and eslint to provide additional syntactic checks. These are both run on `npm test` and as part of the CI build. - The unit tests are executed using [as-pect](https://github.com/jtenner/as-pect) - a native AssemblyScript test runner - The specification tests are within the `spec` folder. The `npm run test:generate` target transforms these tests into as-pect tests which execute as part of the standard build / test cycle - In order to support improved debugging you can execute this library as TypeScript (rather than WebAssembly), via the `npm run tsrun` target. # ShellJS - Unix shell commands for Node.js [![Travis](https://img.shields.io/travis/shelljs/shelljs/master.svg?style=flat-square&label=unix)](https://travis-ci.org/shelljs/shelljs) [![AppVeyor](https://img.shields.io/appveyor/ci/shelljs/shelljs/master.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/shelljs/shelljs/branch/master) [![Codecov](https://img.shields.io/codecov/c/github/shelljs/shelljs/master.svg?style=flat-square&label=coverage)](https://codecov.io/gh/shelljs/shelljs) [![npm version](https://img.shields.io/npm/v/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) [![npm downloads](https://img.shields.io/npm/dm/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! ShellJS is proudly tested on every node release since `v4`! The project is [unit-tested](http://travis-ci.org/shelljs/shelljs) and battle-tested in projects like: + [Firebug](http://getfirebug.com/) - Firefox's infamous debugger + [JSHint](http://jshint.com) & [ESLint](http://eslint.org/) - popular JavaScript linters + [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers + [Yeoman](http://yeoman.io/) - Web application stack and development tool + [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + And [many more](https://npmjs.org/browse/depended/shelljs). If you have feedback, suggestions, or need help, feel free to post in our [issue tracker](https://github.com/shelljs/shelljs/issues). Think ShellJS is cool? Check out some related projects in our [Wiki page](https://github.com/shelljs/shelljs/wiki)! Upgrading from an older version? Check out our [breaking changes](https://github.com/shelljs/shelljs/wiki/Breaking-Changes) page to see what changes to watch out for while upgrading. ## Command line use If you just want cross platform UNIX commands, checkout our new project [shelljs/shx](https://github.com/shelljs/shx), a utility to expose `shelljs` to the command line. For example: ``` $ shx mkdir -p foo $ shx touch foo/bar.txt $ shx rm -rf foo ``` ## Plugin API ShellJS now supports third-party plugins! You can learn more about using plugins and writing your own ShellJS commands in [the wiki](https://github.com/shelljs/shelljs/wiki/Using-ShellJS-Plugins). ## A quick note about the docs For documentation on all the latest features, check out our [README](https://github.com/shelljs/shelljs). To read docs that are consistent with the latest release, check out [the npm page](https://www.npmjs.com/package/shelljs) or [shelljs.org](http://documentup.com/shelljs/shelljs). ## Installing Via npm: ```bash $ npm install [-g] shelljs ``` ## Examples ```javascript var shell = require('shelljs'); if (!shell.which('git')) { shell.echo('Sorry, this script requires git'); shell.exit(1); } // Copy files to release dir shell.rm('-rf', 'out/Release'); shell.cp('-R', 'stuff/', 'out/Release'); // Replace macros in each .js file shell.cd('lib'); shell.ls('*.js').forEach(function (file) { shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file); shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); shell.cd('..'); // Run external tool synchronously if (shell.exec('git commit -am "Auto-commit"').code !== 0) { shell.echo('Error: Git commit failed'); shell.exit(1); } ``` ## Exclude options If you need to pass a parameter that looks like an option, you can do so like: ```js shell.grep('--', '-v', 'path/to/file'); // Search for "-v", no grep options shell.cp('-R', '-dir', 'outdir'); // If already using an option, you're done ``` ## Global vs. Local We no longer recommend using a global-import for ShellJS (i.e. `require('shelljs/global')`). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution. Instead, we recommend a local import (standard for npm packages): ```javascript var shell = require('shelljs'); shell.echo('hello world'); ``` <!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED --> ## Command reference All commands run synchronously, unless otherwise stated. All commands accept standard bash globbing characters (`*`, `?`, etc.), compatible with the [node `glob` module](https://github.com/isaacs/node-glob). For less-commonly used commands and features, please check out our [wiki page](https://github.com/shelljs/shelljs/wiki). ### cat([options,] file [, file ...]) ### cat([options,] file_array) Available options: + `-n`: number all output lines Examples: ```javascript var str = cat('file*.txt'); var str = cat('file1', 'file2'); var str = cat(['file1', 'file2']); // same as above ``` Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). ### cd([dir]) Changes to directory `dir` for the duration of the script. Changes to home directory if no argument is supplied. ### chmod([options,] octal_mode || octal_string, file) ### chmod([options,] symbolic_mode, file) Available options: + `-v`: output a diagnostic for every file processed + `-c`: like verbose, but report only when a change is made + `-R`: change files and directories recursively Examples: ```javascript chmod(755, '/Users/brandon'); chmod('755', '/Users/brandon'); // same as above chmod('u+x', '/Users/brandon'); chmod('-R', 'a-w', '/Users/brandon'); ``` Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + In symbolic modes, `a-r` and `-r` are identical. No consideration is given to the `umask`. + There is no "quiet" option, since default behavior is to run silent. ### cp([options,] source [, source ...], dest) ### cp([options,] source_array, dest) Available options: + `-f`: force (default behavior) + `-n`: no-clobber + `-u`: only copy if `source` is newer than `dest` + `-r`, `-R`: recursive + `-L`: follow symlinks + `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` Copies files. ### pushd([options,] [dir | '-N' | '+N']) Available options: + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. Examples: ```javascript // process.cwd() === '/usr' pushd('/etc'); // Returns /etc /usr pushd('+1'); // Returns /usr /etc ``` Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. ### popd([options,] ['-N' | '+N']) Available options: + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. Examples: ```javascript echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(); // '/usr' echo(process.cwd()); // '/usr' ``` When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. ### dirs([options | '+N' | '-N']) Available options: + `-c`: Clears the directory stack by deleting all of the elements. + `-q`: Supresses output to the console. Arguments: + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. See also: `pushd`, `popd` ### echo([options,] string [, string ...]) Available options: + `-e`: interpret backslash escapes (default) + `-n`: remove trailing newline from output Examples: ```javascript echo('hello world'); var str = echo('hello world'); echo('-n', 'no newline at end'); ``` Prints `string` to stdout, and returns string with additional utility methods like `.to()`. ### exec(command [, options] [, callback]) Available options: + `async`: Asynchronous execution. If a callback is provided, it will be set to `true`, regardless of the passed value (default: `false`). + `silent`: Do not echo program output to console (default: `false`). + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and what is written to stdout and stderr when not in silent mode (default: `'utf8'`). + and any option available to Node.js's [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) Examples: ```javascript var version = exec('node --version', {silent:true}).stdout; var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... do something with data ... */ }); exec('some_long_running_process', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); }); ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process object, and the `callback` receives the arguments `(code, stdout, stderr)`. Not seeing the behavior you want? `exec()` runs everything through `sh` by default (or `cmd.exe` on Windows), which differs from `bash`. If you need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. ### find(path [, path ...]) ### find(path_array) Examples: ```javascript find('src', 'lib'); find(['src', 'lib']); // same as above find('.').filter(function(file) { return file.match(/\.js$/); }); ``` Returns array of all files (however deep) in the given paths. The main difference from `ls('-R', path)` is that the resulting file names include the base directories (e.g., `lib/resources/file1` instead of just `file1`). ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Invert `regex_filter` (only print non-matching lines). + `-l`: Print only filenames of matching files. + `-i`: Ignore case. Examples: ```javascript grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the file that match the given `regex_filter`. ### head([{'-n': \<num\>},] file [, file ...]) ### head([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the first `<num>` lines of the files Examples: ```javascript var str = head({'-n': 1}, 'file*.txt'); var str = head('file1', 'file2'); var str = head(['file1', 'file2']); // same as above ``` Read the start of a file. ### ln([options,] source, dest) Available options: + `-s`: symlink + `-f`: force Examples: ```javascript ln('file', 'newlink'); ln('-sf', 'file', 'existing'); ``` Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. ### ls([options,] [path, ...]) ### ls([options,] path_array) Available options: + `-R`: recursive + `-A`: all files (include files beginning with `.`, except for `.` and `..`) + `-L`: follow symlinks + `-d`: list directories themselves, not their contents + `-l`: list objects representing each file, each with fields containing `ls -l` output fields. See [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) for more info Examples: ```javascript ls('projs/*.js'); ls('-R', '/users/me', '/tmp'); ls('-R', ['/users/me', '/tmp']); // same as above ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} ``` Returns array of files in the given `path`, or files in the current directory if no `path` is provided. ### mkdir([options,] dir [, dir ...]) ### mkdir([options,] dir_array) Available options: + `-p`: full path (and create intermediate directories, if necessary) Examples: ```javascript mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above ``` Creates directories. ### mv([options ,] source [, source ...], dest') ### mv([options ,] source_array, dest') Available options: + `-f`: force (default behavior) + `-n`: no-clobber Examples: ```javascript mv('-n', 'file', 'dir/'); mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` Moves `source` file(s) to `dest`. ### pwd() Returns the current directory. ### rm([options,] file [, file ...]) ### rm([options,] file_array) Available options: + `-f`: force + `-r, -R`: recursive Examples: ```javascript rm('-rf', '/tmp/*'); rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` Removes files. ### sed([options,] search_regex, replacement, file [, file ...]) ### sed([options,] search_regex, replacement, file_array) Available options: + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ Examples: ```javascript sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); ``` Reads an input string from `file`s, and performs a JavaScript `replace()` on the input using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. Note: Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified using the `$n` syntax: ```javascript sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); ``` ### set(options) Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) + `+/-f`: disable filename expansion (globbing) Examples: ```javascript set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" ``` Sets global configuration variables. ### sort([options,] file [, file ...]) ### sort([options,] file_array) Available options: + `-r`: Reverse the results + `-n`: Compare according to numerical value Examples: ```javascript sort('foo.txt', 'bar.txt'); sort('-r', 'foo.txt'); ``` Return the contents of the `file`s, sorted line-by-line. Sorting multiple files mixes their content (just as unix `sort` does). ### tail([{'-n': \<num\>},] file [, file ...]) ### tail([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the last `<num>` lines of `file`s Examples: ```javascript var str = tail({'-n': 1}, 'file*.txt'); var str = tail('file1', 'file2'); var str = tail(['file1', 'file2']); // same as above ``` Read the end of a `file`. ### tempdir() Examples: ```javascript var tmp = tempdir(); // "/tmp" for most *nix platforms ``` Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). ### test(expression) Available expression primaries: + `'-b', 'path'`: true if path is a block device + `'-c', 'path'`: true if path is a character device + `'-d', 'path'`: true if path is a directory + `'-e', 'path'`: true if path exists + `'-f', 'path'`: true if path is a regular file + `'-L', 'path'`: true if path is a symbolic link + `'-p', 'path'`: true if path is a pipe (FIFO) + `'-S', 'path'`: true if path is a socket Examples: ```javascript if (test('-d', path)) { /* do something with dir */ }; if (!test('-f', path)) continue; // skip if it's a regular file ``` Evaluates `expression` using the available primaries and returns corresponding value. ### ShellString.prototype.to(file) Examples: ```javascript cat('input.txt').to('output.txt'); ``` Analogous to the redirection operator `>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix redirections, `to()` will overwrite any existing file!_ ### ShellString.prototype.toEnd(file) Examples: ```javascript cat('input.txt').toEnd('output.txt'); ``` Analogous to the redirect-and-append operator `>>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). ### touch([options,] file [, file ...]) ### touch([options,] file_array) Available options: + `-a`: Change only the access time + `-c`: Do not create any files + `-m`: Change only the modification time + `-d DATE`: Parse `DATE` and use it instead of current time + `-r FILE`: Use `FILE`'s times instead of current time Examples: ```javascript touch('source.js'); touch('-c', '/path/to/some/dir/source.js'); touch({ '-r': FILE }, '/path/to/some/dir/source.js'); ``` Update the access and modification times of each `FILE` to the current time. A `FILE` argument that does not exist is created empty, unless `-c` is supplied. This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). ### uniq([options,] [input, [output]]) Available options: + `-i`: Ignore case while comparing + `-c`: Prefix lines by the number of occurrences + `-d`: Only print duplicate lines, one for each group of identical lines Examples: ```javascript uniq('foo.txt'); uniq('-i', 'foo.txt'); uniq('-cd', 'foo.txt', 'bar.txt'); ``` Filter adjacent matching lines from `input`. ### which(command) Examples: ```javascript var nodeExec = which('node'); ``` Searches for `command` in the system's `PATH`. On Windows, this uses the `PATHEXT` variable to append the extension if it's not already executable. Returns string containing the absolute path to `command`. ### exit(code) Exits the current process with the given exit `code`. ### error() Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise. **Note**: do not rely on the return value to be an error message. If you need the last error message, use the `.stderr` attribute from the last command's return value instead. ### ShellString(str) Examples: ```javascript var foo = ShellString('hello world'); ``` Turns a regular string into a string-like object similar to what each command returns. This has special methods, like `.to()` and `.toEnd()`. ### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to `process.env`. ### Pipes Examples: ```javascript grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); echo('files with o\'s in the name:\n' + ls().grep('o')); cat('test.js').exec('node'); // pipe to exec() call ``` Commands can send their output to another command in a pipe-like fashion. `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand side of a pipe. Pipes can be chained. ## Configuration ### config.silent Example: ```javascript var sh = require('shelljs'); var silentState = sh.config.silent; // save old silent state sh.config.silent = true; /* ... */ sh.config.silent = silentState; // restore old silent state ``` Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` If `true`, the script will throw a Javascript error when any shell.js command encounters an error. Default is `false`. This is analogous to Bash's `set -e`. ### config.verbose Example: ```javascript config.verbose = true; // or set('-v'); cd('dir/'); rm('-rf', 'foo.txt', 'bar.txt'); exec('echo hello'); ``` Will print each command as follows: ``` cd dir/ rm -rf foo.txt bar.txt exec echo hello ``` ### config.globOptions Example: ```javascript config.globOptions = {nodir: true}; ``` Use this value for calls to `glob.sync()` instead of the default options. ### config.reset() Example: ```javascript var shell = require('shelljs'); // Make changes to shell.config, and do stuff... /* ... */ shell.config.reset(); // reset to original state // Do more stuff, but with original settings /* ... */ ``` Reset `shell.config` to the defaults: ```javascript { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, } ``` ## Team | [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Brandon Freitag](https://avatars1.githubusercontent.com/u/5988055?v=3&s=130)](http://github.com/freitagbr) | |:---:|:---:| | [Nate Fischer](https://github.com/nfischer) | [Brandon Freitag](http://github.com/freitagbr) | # flat-cache > A stupidly simple key/value storage using files to persist the data [![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) [![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache) ## install ```bash npm i --save flat-cache ``` ## Usage ```js var flatCache = require('flat-cache') // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var cache = flatCache.load('cacheId'); // sets a key on the cache cache.setKey('key', { foo: 'var' }); // get a key from the cache cache.getKey('key') // { foo: 'var' } // fetch the entire persisted object cache.all() // { 'key': { foo: 'var' } } // remove a key cache.removeKey('key'); // removes a key from the cache // save it to disk cache.save(); // very important, if you don't save no changes will be persisted. // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys // loads the cache from a given directory, if one does // not exists for the given Id a new one will be prepared to be created var cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); // The following methods are useful to clear the cache // delete a given cache flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists. // delete all cache flatCache.clearAll(); // remove the cache directory ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` storage was needed and Bam! this module was born. ## Important notes - If no directory is especified when the `load` method is called, a folder named `.cache` will be created inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you might want to ignore the default `.cache` folder, or specify a custom directory. - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references - All the changes to the cache state are done to memory - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module intentionally dumb and simple - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call like: `cache.save( true /* noPrune */ )`. ## License MIT ## Changelog [changelog](./changelog.md) [![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> cartoonvote ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `cartoonvote.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `cartoonvote.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account cartoonvote.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'cartoonvote.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages functional-red-black-tree ========================= A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. # Install npm install functional-red-black-tree # Example Here is an example of some basic usage: ```javascript //Load the library var createTree = require("functional-red-black-tree") //Create a tree var t1 = createTree() //Insert some items into the tree var t2 = t1.insert(1, "foo") var t3 = t2.insert(2, "bar") //Remove something var t4 = t3.remove(1) ``` # API ```javascript var createTree = require("functional-red-black-tree") ``` ## Overview - [Tree methods](#tree-methods) - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) - [`tree.keys`](#treekeys) - [`tree.values`](#treevalues) - [`tree.length`](#treelength) - [`tree.get(key)`](#treegetkey) - [`tree.insert(key, value)`](#treeinsertkey-value) - [`tree.remove(key)`](#treeremovekey) - [`tree.find(key)`](#treefindkey) - [`tree.ge(key)`](#treegekey) - [`tree.gt(key)`](#treegtkey) - [`tree.lt(key)`](#treeltkey) - [`tree.le(key)`](#treelekey) - [`tree.at(position)`](#treeatposition) - [`tree.begin`](#treebegin) - [`tree.end`](#treeend) - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) - [`tree.root`](#treeroot) - [Node properties](#node-properties) - [`node.key`](#nodekey) - [`node.value`](#nodevalue) - [`node.left`](#nodeleft) - [`node.right`](#noderight) - [Iterator methods](#iterator-methods) - [`iter.key`](#iterkey) - [`iter.value`](#itervalue) - [`iter.node`](#iternode) - [`iter.tree`](#itertree) - [`iter.index`](#iterindex) - [`iter.valid`](#itervalid) - [`iter.clone()`](#iterclone) - [`iter.remove()`](#iterremove) - [`iter.update(value)`](#iterupdatevalue) - [`iter.next()`](#iternext) - [`iter.prev()`](#iterprev) - [`iter.hasNext`](#iterhasnext) - [`iter.hasPrev`](#iterhasprev) ## Tree methods ### `var tree = createTree([compare])` Creates an empty functional tree * `compare` is an optional comparison function, same semantics as array.sort() **Returns** An empty tree ordered by `compare` ### `tree.keys` A sorted array of all the keys in the tree ### `tree.values` An array array of all the values in the tree ### `tree.length` The number of items in the tree ### `tree.get(key)` Retrieves the value associated to the given key * `key` is the key of the item to look up **Returns** The value of the first node associated to `key` ### `tree.insert(key, value)` Creates a new tree with the new pair inserted. * `key` is the key of the item to insert * `value` is the value of the item to insert **Returns** A new tree with `key` and `value` inserted ### `tree.remove(key)` Removes the first item with `key` in the tree * `key` is the key of the item to remove **Returns** A new tree with the given item removed if it exists ### `tree.find(key)` Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. ### `tree.ge(key)` Find the first item in the tree whose key is `>= key` * `key` is the key to search for **Returns** An iterator at the given element. ### `tree.gt(key)` Finds the first item in the tree whose key is `> key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.lt(key)` Finds the last item in the tree whose key is `< key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.le(key)` Finds the last item in the tree whose key is `<= key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.at(position)` Finds an iterator starting at the given element * `position` is the index at which the iterator gets created **Returns** An iterator starting at position ### `tree.begin` An iterator pointing to the first element in the tree ### `tree.end` An iterator pointing to the last element in the tree ### `tree.forEach(visitor(key,value)[, lo[, hi]])` Walks a visitor function over the nodes of the tree in order. * `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. * `lo` is an optional start of the range to visit (inclusive) * `hi` is an optional end of the range to visit (non-inclusive) **Returns** The last value returned by the callback ### `tree.root` Returns the root node of the tree ## Node properties Each node of the tree has the following properties: ### `node.key` The key associated to the node ### `node.value` The value associated to the node ### `node.left` The left subtree of the node ### `node.right` The right subtree of the node ## Iterator methods ### `iter.key` The key of the item referenced by the iterator ### `iter.value` The value of the item referenced by the iterator ### `iter.node` The value of the node at the iterator's current position. `null` is iterator is node valid. ### `iter.tree` The tree associated to the iterator ### `iter.index` Returns the position of this iterator in the sequence. ### `iter.valid` Checks if the iterator is valid ### `iter.clone()` Makes a copy of the iterator ### `iter.remove()` Removes the item at the position of the iterator **Returns** A new binary search tree with `iter`'s item removed ### `iter.update(value)` Updates the value of the node in the tree at this iterator **Returns** A new binary search tree with the corresponding node updated ### `iter.next()` Advances the iterator to the next position ### `iter.prev()` Moves the iterator backward one element ### `iter.hasNext` If true, then the iterator is not at the end of the sequence ### `iter.hasPrev` If true, then the iterator is not at the beginning of the sequence # Credits (c) 2013 Mikola Lysenko. MIT License # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/eslint/doctrine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/doctrine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Doctrine Doctrine is a [JSDoc](http://usejsdoc.org) parser that parses documentation comments from JavaScript (you need to pass in the comment, not a whole JavaScript file). ## Installation You can install Doctrine using [npm](https://npmjs.com): ``` $ npm install doctrine --save-dev ``` Doctrine can also be used in web browsers using [Browserify](http://browserify.org). ## Usage Require doctrine inside of your JavaScript: ```js var doctrine = require("doctrine"); ``` ### parse() The primary method is `parse()`, which accepts two arguments: the JSDoc comment to parse and an optional options object. The available options are: * `unwrap` - set to `true` to delete the leading `/**`, any `*` that begins a line, and the trailing `*/` from the source text. Default: `false`. * `tags` - an array of tags to return. When specified, Doctrine returns only tags in this array. For example, if `tags` is `["param"]`, then only `@param` tags will be returned. Default: `null`. * `recoverable` - set to `true` to keep parsing even when syntax errors occur. Default: `false`. * `sloppy` - set to `true` to allow optional parameters to be specified in brackets (`@param {string} [foo]`). Default: `false`. * `lineNumbers` - set to `true` to add `lineNumber` to each node, specifying the line on which the node is found in the source. Default: `false`. * `range` - set to `true` to add `range` to each node, specifying the start and end index of the node in the original comment. Default: `false`. Here's a simple example: ```js var ast = doctrine.parse( [ "/**", " * This function comment is parsed by doctrine", " * @param {{ok:String}} userName", "*/" ].join('\n'), { unwrap: true }); ``` This example returns the following AST: { "description": "This function comment is parsed by doctrine", "tags": [ { "title": "param", "description": null, "type": { "type": "RecordType", "fields": [ { "type": "FieldType", "key": "ok", "value": { "type": "NameExpression", "name": "String" } } ] }, "name": "userName" } ] } See the [demo page](http://eslint.org/doctrine/demo/) more detail. ## Team These folks keep the project moving and are resources for help: * Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) - project lead * Yusuke Suzuki ([@constellation](https://github.com/constellation)) - reviewer ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/doctrine/issues). ## Frequently Asked Questions ### Can I pass a whole JavaScript file to Doctrine? No. Doctrine can only parse JSDoc comments, so you'll need to pass just the JSDoc comment to Doctrine in order to work. ### License #### doctrine Copyright JS Foundation and other contributors, https://js.foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #### esprima some of functions is derived from esprima Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #### closure-compiler some of extensions is derived from closure-compiler Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ ### Where to ask for help? Join our [Chatroom](https://gitter.im/eslint/doctrine) [npm-image]: https://img.shields.io/npm/v/doctrine.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/doctrine [travis-image]: https://img.shields.io/travis/eslint/doctrine/master.svg?style=flat-square [travis-url]: https://travis-ci.org/eslint/doctrine [coveralls-image]: https://img.shields.io/coveralls/eslint/doctrine/master.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/eslint/doctrine?branch=master [downloads-image]: http://img.shields.io/npm/dm/doctrine.svg?style=flat-square [downloads-url]: https://www.npmjs.com/package/doctrine The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation Node.js version 8 and up: `$ npm install cross-spawn` Node.js version 7 and under: `$ npm install cross-spawn@6` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). # minimatch A minimal matching utility. [![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) <a name="table"></a> # Table > Produces a string that represents array data in a text table. [![Travis build status](http://img.shields.io/travis/gajus/table/master.svg?style=flat-square)](https://travis-ci.org/gajus/table) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) [![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical) [![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas) * [Table](#table) * [Features](#table-features) * [Install](#table-install) * [Usage](#table-usage) * [API](#table-api) * [table](#table-api-table-1) * [createStream](#table-api-createstream) * [getBorderCharacters](#table-api-getbordercharacters) ![Demo of table displaying a list of missions to the Moon.](./.README/demo.png) <a name="table-features"></a> ## Features * Works with strings containing [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) characters. * Works with strings containing [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). * Configurable border characters. * Configurable content alignment per column. * Configurable content padding per column. * Configurable column width. * Text wrapping. <a name="table-install"></a> ## Install ```bash npm install table ``` [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) [![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) <a name="table-usage"></a> ## Usage ```js import { table } from 'table'; // Using commonjs? // const { table } = require('table'); const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; console.log(table(data)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ ``` <a name="table-api"></a> ## API <a name="table-api-table-1"></a> ### table Returns the string in the table format **Parameters:** - **_data_:** The data to display - Type: `any[][]` - Required: `true` - **_config_:** Table configuration - Type: `object` - Required: `false` <a name="table-api-table-1-config-border"></a> ##### config.border Type: `{ [type: string]: string }`\ Default: `honeywell` [template](#getbordercharacters) Custom borders. The keys are any of: - `topLeft`, `topRight`, `topBody`,`topJoin` - `bottomLeft`, `bottomRight`, `bottomBody`, `bottomJoin` - `joinLeft`, `joinRight`, `joinBody`, `joinJoin` - `bodyLeft`, `bodyRight`, `bodyJoin` - `headerJoin` ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: { topBody: `─`, topJoin: `┬`, topLeft: `┌`, topRight: `┐`, bottomBody: `─`, bottomJoin: `┴`, bottomLeft: `└`, bottomRight: `┘`, bodyLeft: `│`, bodyRight: `│`, bodyJoin: `│`, joinBody: `─`, joinLeft: `├`, joinRight: `┤`, joinJoin: `┼` } }; console.log(table(data, config)); ``` ``` ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ ``` <a name="table-api-table-1-config-drawverticalline"></a> ##### config.drawVerticalLine Type: `(lineIndex: number, columnCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a vertical line. This callback is called for each vertical border of the table. If the table has `n` columns, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawVerticalLine: (lineIndex, columnCount) => { return lineIndex === 0 || lineIndex === columnCount; } }; console.log(table(data, config)); ``` ``` ╔════════════╗ ║ 0A 0B 0C ║ ╟────────────╢ ║ 1A 1B 1C ║ ╟────────────╢ ║ 2A 2B 2C ║ ╟────────────╢ ║ 3A 3B 3C ║ ╟────────────╢ ║ 4A 4B 4C ║ ╚════════════╝ ``` <a name="table-api-table-1-config-drawhorizontalline"></a> ##### config.drawHorizontalLine Type: `(lineIndex: number, rowCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a horizontal line. This callback is called for each horizontal border of the table. If the table has `n` rows, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. If the table has `n` rows and contains the header, then the range will be `[0, n+1]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawHorizontalLine: (lineIndex, rowCount) => { return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount - 1 || lineIndex === rowCount; } }; console.log(table(data, config)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ║ 2A │ 2B │ 2C ║ ║ 3A │ 3B │ 3C ║ ╟────┼────┼────╢ ║ 4A │ 4B │ 4C ║ ╚════╧════╧════╝ ``` <a name="table-api-table-1-config-singleline"></a> ##### config.singleLine Type: `boolean`\ Default: `false` If `true`, horizontal lines inside the table are not drawn. This option also overrides the `config.drawHorizontalLine` if specified. ```js const data = [ ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], ]; const config = { singleLine: true }; console.log(table(data, config)); ``` ``` ╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ ║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ ║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ ║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ ║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ ║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ ║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ ╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ ``` <a name="table-api-table-1-config-columns"></a> ##### config.columns Type: `Column[] | { [columnIndex: number]: Column }` Column specific configurations. <a name="table-api-table-1-config-columns-config-columns-width"></a> ###### config.columns[*].width Type: `number`\ Default: the maximum cell widths of the column Column width (excluding the paddings). ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: { 1: { width: 10 } } }; console.log(table(data, config)); ``` ``` ╔════╤════════════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────────────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────────────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════════════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-alignment"></a> ###### config.columns[*].alignment Type: `'center' | 'justify' | 'left' | 'right'`\ Default: `'left'` Cell content horizontal alignment ```js const data = [ ['0A', '0B', '0C', '0D 0E 0F'], ['1A', '1B', '1C', '1D 1E 1F'], ['2A', '2B', '2C', '2D 2E 2F'], ]; const config = { columnDefault: { width: 10, }, columns: [ { alignment: 'left' }, { alignment: 'center' }, { alignment: 'right' }, { alignment: 'justify' } ], }; console.log(table(data, config)); ``` ``` ╔════════════╤════════════╤════════════╤════════════╗ ║ 0A │ 0B │ 0C │ 0D 0E 0F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C │ 1D 1E 1F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C │ 2D 2E 2F ║ ╚════════════╧════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-verticalalignment"></a> ###### config.columns[*].verticalAlignment Type: `'top' | 'middle' | 'bottom'`\ Default: `'top'` Cell content vertical alignment ```js const data = [ ['A', 'B', 'C', 'DEF'], ]; const config = { columnDefault: { width: 1, }, columns: [ { verticalAlignment: 'top' }, { verticalAlignment: 'middle' }, { verticalAlignment: 'bottom' }, ], }; console.log(table(data, config)); ``` ``` ╔═══╤═══╤═══╤═══╗ ║ A │ │ │ D ║ ║ │ B │ │ E ║ ║ │ │ C │ F ║ ╚═══╧═══╧═══╧═══╝ ``` <a name="table-api-table-1-config-columns-config-columns-paddingleft"></a> ###### config.columns[*].paddingLeft Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the left. <a name="table-api-table-1-config-columns-config-columns-paddingright"></a> ###### config.columns[*].paddingRight Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the right. The `paddingLeft` and `paddingRight` options do not count on the column width. So the column has `width = 5`, `paddingLeft = 2` and `paddingRight = 2` will have the total width is `9`. ```js const data = [ ['0A', 'AABBCC', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: [ { paddingLeft: 3 }, { width: 2, paddingRight: 3 } ] }; console.log(table(data, config)); ``` ``` ╔══════╤══════╤════╗ ║ 0A │ AA │ 0C ║ ║ │ BB │ ║ ║ │ CC │ ║ ╟──────┼──────┼────╢ ║ 1A │ 1B │ 1C ║ ╟──────┼──────┼────╢ ║ 2A │ 2B │ 2C ║ ╚══════╧══════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-truncate"></a> ###### config.columns[*].truncate Type: `number`\ Default: `Infinity` The number of characters is which the content will be truncated. To handle a content that overflows the container width, `table` package implements [text wrapping](#config.columns[*].wrapWord). However, sometimes you may want to truncate content that is too long to be displayed in the table. ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20, truncate: 100 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convall… ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-wrapword"></a> ###### config.columns[*].wrapWord Type: `boolean`\ Default: `false` The `table` package implements auto text wrapping, i.e., text that has the width greater than the container width will be separated into multiple lines at the nearest space or one of the special characters: `\|/_.,;-`. When `wrapWord` is `false`: ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convallis ║ ║ dapibus. Nunc venena ║ ║ tis tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` When `wrapWord` is `true`: ``` ╔══════════════════════╗ ║ Lorem ipsum dolor ║ ║ sit amet, ║ ║ consectetur ║ ║ adipiscing elit. ║ ║ Phasellus pulvinar ║ ║ nibh sed mauris ║ ║ convallis dapibus. ║ ║ Nunc venenatis ║ ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columndefault"></a> ##### config.columnDefault Type: `Column`\ Default: `{}` The default configuration for all columns. Column-specific settings will overwrite the default values. <a name="table-api-table-1-config-header"></a> ##### config.header Type: `object` Header configuration. The header configuration inherits the most of the column's, except: - `content` **{string}**: the header content. - `width:` calculate based on the content width automatically. - `alignment:` `center` be default. - `verticalAlignment:` is not supported. - `config.border.topJoin` will be `config.border.topBody` for prettier. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ]; const config = { columnDefault: { width: 10, }, header: { alignment: 'center', content: 'THE HEADER\nThis is the table about something', }, } console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════╗ ║ THE HEADER ║ ║ This is the table about something ║ ╟────────────┬────────────┬────────────╢ ║ 0A │ 0B │ 0C ║ ╟────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C ║ ╟────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C ║ ╚════════════╧════════════╧════════════╝ ``` <a name="table-api-createstream"></a> ### createStream `table` package exports `createStream` function used to draw a table and append rows. **Parameter:** - _**config:**_ the same as `table`'s, except `config.columnDefault.width` and `config.columnCount` must be provided. ```js import { createStream } from 'table'; const config = { columnDefault: { width: 50 }, columnCount: 1 }; const stream = createStream(config); setInterval(() => { stream.write([new Date()]); }, 500); ``` ![Streaming current date.](./.README/api/stream/streaming.gif) `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { createStream } from 'table'; import _ from 'lodash'; const config = { columnDefault: { width: 50 }, columnCount: 3, columns: [ { width: 10, alignment: 'right' }, { alignment: 'center' }, { width: 10 } ] }; const stream = createStream(config); let i = 0; setInterval(() => { let random; random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/api/stream/streaming-random.gif) <a name="table-api-getbordercharacters"></a> ### getBorderCharacters **Parameter:** - **_template_** - Type: `'honeywell' | 'norc' | 'ramac' | 'void'` - Required: `true` You can load one of the predefined border templates using `getBorderCharacters` function. ```js import { table, getBorderCharacters } from 'table'; const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: getBorderCharacters(`name of the template`) }; console.log(table(data, config)); ``` ``` # honeywell ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ # norc ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ # ramac (ASCII; for use in terminals that do not support Unicode characters) +----+----+----+ | 0A | 0B | 0C | |----|----|----| | 1A | 1B | 1C | |----|----|----| | 2A | 2B | 2C | +----+----+----+ # void (no borders; see "borderless table" section of the documentation) 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` Raise [an issue](https://github.com/gajus/table/issues) if you'd like to contribute a new border template. <a name="table-api-getbordercharacters-borderless-table"></a> #### Borderless Table Simply using `void` border character template creates a table with a lot of unnecessary spacing. To create a more pleasant to the eye table, reset the padding and remove the joining rows, e.g. ```js const output = table(data, { border: getBorderCharacters('void'), columnDefault: { paddingLeft: 0, paddingRight: 1 }, drawHorizontalLine: () => false } ); console.log(output); ``` ``` 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg"> &nbsp; # Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). [![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Platinum sponsors [<img src="https://ajv.js.org/img/mozilla.svg" width="45%">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="8%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv) ## Ajv online event - May 20, 10am PT / 6pm UK We will talk about: - new features of Ajv version 8. - the improvements sponsored by Mozilla's MOSS grant. - how Ajv is used in JavaScript applications. Speakers: - [Evgeny Poberezkin](https://github.com/epoberezkin), the creator of Ajv. - [Mehan Jayasuriya](https://github.com/mehan), Program Officer at Mozilla Foundation, leading the [MOSS](https://www.mozilla.org/en-US/moss/) and other programs investing in the open source and community ecosystems. - [Matteo Collina](https://github.com/mcollina), Technical Director at NearForm and Node.js Technical Steering Committee member, creator of Fastify web framework. - [Kin Lane](https://github.com/kinlane), Chief Evangelist at Postman. Studying the tech, business & politics of APIs since 2010. Presidential Innovation Fellow during the Obama administration. - [Ulysse Carion](https://github.com/ucarion), the creator of JSON Type Definition specification. [Gajus Kuizinas](https://github.com/gajus) will host the event. Please [register here](https://us02web.zoom.us/webinar/register/2716192553618/WN_erJ_t4ICTHOnGC1SOybNnw). ## Contributing More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). ## Documentation All documentation is available on the [Ajv website](https://ajv.js.org). Some useful site links: - [Getting started](https://ajv.js.org/guide/getting-started.html) - [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) - [API reference](https://ajv.js.org/api.html) - [Strict mode](https://ajv.js.org/strict-mode.html) - [Standalone validation code](https://ajv.js.org/standalone.html) - [Security considerations](https://ajv.js.org/security.html) - [Command line interface](https://ajv.js.org/packages/ajv-cli.html) - [Frequently Asked Questions](https://ajv.js.org/faq.html) ## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Performance Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus&#x2F;schemasafe|is-my-json-valid|djv|@cfworker&#x2F;json-schema|jsonschema&chd=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) - support of recursive references between schemas - correct string lengths for strings with unicode pairs - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) - NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) - meta-schema for JTD schemas - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) - supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current - [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) - [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) - [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items - [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords - [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) - additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords ## Install To install version 8: ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://runkit.com/npm/ajv In JavaScript: ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false, } const data = { foo: 1, bar: "abc" } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) ## Changes history See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) **Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) [Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](./LICENSE) # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 (2020, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 10. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) [![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## Enterprise support json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) Shims used when bundling asc for browser usage. Like `chown -R`. Takes the same arguments as `fs.chown()` Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0,4.1,4.2?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) [![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) This package is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy to use and powerful. It was first released in 2010 and is tested against big data sets by a large community. ## Documentation * [Project homepage](http://csv.js.org/stringify/) * [API](http://csv.js.org/stringify/api/) * [Options](http://csv.js.org/stringify/options/) * [Examples](http://csv.js.org/stringify/examples/) ## Main features * Follow the Node.js streaming API * Simplicity with the optional callback API * Support for custom formatters, delimiters, quotes, escape characters and header * Support big datasets * Complete test coverage and samples for inspiration * Only 1 external dependency * to be used conjointly with `csv-generate`, `csv-parse` and `stream-transform` * MIT License ## Usage The module is built on the Node.js Stream API. For the sake of simplicity, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: ```javascript const stringify = require('csv-stringify') const assert = require('assert') // import stringify from 'csv-stringify' // import assert from 'assert/strict' const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] stringify(input, function(err, output) { const expected = '1,2,3,4\na,b,c,d\n' assert.strictEqual(output, expected, `output.should.eql ${expected}`) console.log("Passed.", output) }) ``` ## Development Tests are executed with mocha. To install it, run `npm install` followed by `npm test`. It will install mocha and its dependencies in your project "node_modules" directory and run the test suite. The tests run against the CoffeeScript source files. To generate the JavaScript files, run `npm run build`. The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node-csv-stringify). See the [Travis definition file](https://github.com/adaltas/node-csv-stringify/blob/master/.travis.yml) to view the tested Node.js version. ## Contributors * David Worms: <https://github.com/wdavidw> [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform [examples]: http://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` ## Enterprise support fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) # is-core-module <sup>[![Version Badge][2]][1]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module [codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module [actions-url]: https://github.com/inspect-js/is-core-module/actions bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # line-column [![Build Status](https://travis-ci.org/io-monad/line-column.svg?branch=master)](https://travis-ci.org/io-monad/line-column) [![Coverage Status](https://coveralls.io/repos/github/io-monad/line-column/badge.svg?branch=master)](https://coveralls.io/github/io-monad/line-column?branch=master) [![npm version](https://badge.fury.io/js/line-column.svg)](https://badge.fury.io/js/line-column) Node module to convert efficiently index to/from line-column in a string. ## Install npm install line-column ## Usage ### lineColumn(str, options = {}) Returns a `LineColumnFinder` instance for given string `str`. #### Options | Key | Description | Default | | ------- | ----------- | ------- | | `origin` | The origin value of line number and column number | `1` | ### lineColumn(str, index) This is just a shorthand for `lineColumn(str).fromIndex(index)`. ### LineColumnFinder#fromIndex(index) Find line and column from index in the string. Parameters: - `index` - `number` Index in the string. (0-origin) Returns: - `{ line: x, col: y }` Found line number and column number. - `null` if the given index is out of range. ### LineColumnFinder#toIndex(line, column) Find index from line and column in the string. Parameters: - `line` - `number` Line number in the string. - `column` - `number` Column number in the string. or - `{ line: x, col: y }` - `Object` line and column numbers in the string.<br>A key name `column` can be used instead of `col`. or - `[ line, col ]` - `Array` line and column numbers in the string. Returns: - `number` Found index in the string. - `-1` if the given line or column is out of range. ## Example ```js var lineColumn = require("line-column"); var testString = [ "ABCDEFG\n", // line:0, index:0 "HIJKLMNOPQRSTU\n", // line:1, index:8 "VWXYZ\n", // line:2, index:23 "日本語の文字\n", // line:3, index:29 "English words" // line:4, index:36 ].join(""); // length:49 lineColumn(testString).fromIndex(3) // { line: 1, col: 4 } lineColumn(testString).fromIndex(33) // { line: 4, col: 5 } lineColumn(testString).toIndex(1, 4) // 3 lineColumn(testString).toIndex(4, 5) // 33 // Shorthand of .fromIndex (compatible with find-line-column) lineColumn(testString, 33) // { line:4, col: 5 } // Object or Array is also acceptable lineColumn(testString).toIndex({ line: 4, col: 5 }) // 33 lineColumn(testString).toIndex({ line: 4, column: 5 }) // 33 lineColumn(testString).toIndex([4, 5]) // 33 // You can cache it for the same string. It is so efficient. (See benchmark) var finder = lineColumn(testString); finder.fromIndex(33) // { line: 4, column: 5 } finder.toIndex(4, 5) // 33 // For 0-origin line and column numbers var oneOrigin = lineColumn(testString, { origin: 0 }); oneOrigin.fromIndex(33) // { line: 3, column: 4 } oneOrigin.toIndex(3, 4) // 33 ``` ## Testing npm test ## Benchmark The popular package [find-line-column](https://www.npmjs.com/package/find-line-column) provides the same "index to line-column" feature. Here is some benchmarking on `line-column` vs `find-line-column`. You can run this benchmark by `npm run benchmark`. See [benchmark/](benchmark/) for the source code. ``` long text + line-column (not cached) x 72,989 ops/sec ±0.83% (89 runs sampled) long text + line-column (cached) x 13,074,242 ops/sec ±0.32% (89 runs sampled) long text + find-line-column x 33,887 ops/sec ±0.54% (84 runs sampled) short text + line-column (not cached) x 1,636,766 ops/sec ±0.77% (82 runs sampled) short text + line-column (cached) x 21,699,686 ops/sec ±1.04% (82 runs sampled) short text + find-line-column x 382,145 ops/sec ±1.04% (85 runs sampled) ``` As you might have noticed, even not cached version of `line-column` is 2x - 4x faster than `find-line-column`, and cached version of `line-column` is remarkable 50x - 380x faster. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT (See LICENSE) # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" /> __Light ECMAScript (JavaScript) Value Notation__ Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. __How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. npm install levn For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). ## Quick Examples ```js var parse = require('levn').parse; parse('Number', '2'); // 2 parse('String', '2'); // '2' parse('String', 'levn'); // 'levn' parse('String', 'a b'); // 'a b' parse('Boolean', 'true'); // true parse('Date', '#2011-11-11#'); // (Date object) parse('Date', '2011-11-11'); // (Date object) parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi parse('RegExp', 're'); // /re/ parse('Int', '2'); // 2 parse('Number | String', 'str'); // 'str' parse('Number | String', '2'); // 2 parse('[Number]', '[1,2,3]'); // [1,2,3] parse('(String, Boolean)', '(hi, false)'); // ['hi', false] parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} // at the top level, you can ommit surrounding delimiters parse('[Number]', '1,2,3'); // [1,2,3] parse('(String, Boolean)', 'hi, false'); // ['hi', false] parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} // wildcard - auto choose type parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] ``` ## Usage `require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. ```js // parse(type, input, options); parse('[Number]', '1,2,3'); // [1, 2, 3] // parsedTypeParse(parsedType, input, options); var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ### parse(type, input, options) `parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. ##### arguments * type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js parse('[Number]', '1,2,3'); // [1, 2, 3] ``` ### parsedTypeParse(parsedType, input, options) `parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ## Levn Format Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). * `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` * `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` * `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` * `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents * `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. * `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). * `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. * Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: * If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. * If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. * If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. * If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. * If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). * If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. Whitespace between special characters and elements is inconsequential. ## Options Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. ### Explicit A `Boolean`. By default it is `false`. __Example:__ ```js parse('RegExp', 're', {explicit: false}); // /re/ parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... parse('RegExp | String', 're', {explicit: true}); // 're' ``` `explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. ### customTypes An `Object`. Empty `{}` by default. __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function (x) { return x % 2 === 0; }, cast: function (x) { return {type: 'Just', value: parseInt(x)}; } } } } parse('Even', '2', options); // 2 parse('Even', '3', options); // Error: Value: "3" does not type check... ``` __Another Example:__ ```js function Person(name, age){ this.name = name; this.age = age; } var options = { customTypes: { Person: { typeOf: 'Object', validate: function (x) { x instanceof Person; }, cast: function (value, options, typesCast) { var name, age; if ({}.toString.call(value).slice(8, -1) !== 'Object') { return {type: 'Nothing'}; } name = typesCast(value.name, [{type: 'String'}], options); age = typesCast(value.age, [{type: 'Numger'}], options); return {type: 'Just', value: new Person(name, age)}; } } } parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} ``` `customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. `cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. ## Technical About `levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. [![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) [![Build Status](https://travis-ci.org/eslint/espree.svg?branch=master)](https://travis-ci.org/eslint/espree) [![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) # Espree Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. ## Usage Install: ``` npm i espree ``` And in your Node.js code: ```javascript const espree = require("espree"); const ast = espree.parse(code); ``` ## API ### `parse()` `parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). ```javascript const espree = require("espree"); const ast = espree.parse(code, options); ``` **Example :** ```js const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); console.log(ast); ``` <details><summary>Output</summary> <p> ``` Node { type: 'Program', start: 0, end: 15, body: [ Node { type: 'VariableDeclaration', start: 0, end: 15, declarations: [Array], kind: 'let' } ], sourceType: 'script' } ``` </p> </details> ### `tokenize()` `tokenize` returns the tokens of a given code. It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array **Example :** ```js const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); console.log(tokens); ``` <details><summary>Output</summary> <p> ``` Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, Token { type: 'String', value: '"bar"', start: 10, end: 15 } ``` </p> </details> ### `version` Returns the current `espree` version ### `VisitorKeys` Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) ### `latestEcmaVersion` Returns the latest ECMAScript supported by `espree` ### `supportedEcmaVersions` Returns an array of all supported ECMAScript versions ## Options ```js const options = { // attach range information to each node range: false, // attach line/column location information to each node loc: false, // create a top-level comments array containing all comments comment: false, // create a top-level tokens array containing all tokens tokens: false, // Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming. ecmaVersion: 5, // specify which type of script you're parsing ("script" or "module") sourceType: "script", // specify additional language features ecmaFeatures: { // enable JSX parsing jsx: false, // enable return in global scope globalReturn: false, // enable implied strict mode (if ecmaVersion >= 5) impliedStrict: false } } ``` ## Esprima Compatibility Going Forward The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. Espree may also deviate from Esprima in the interface it exposes. ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). Espree is licensed under a permissive BSD 2-clause license. ## Security Policy We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting * `npm run browserify` - creates a version of Espree that is usable in a browser ## Differences from Espree 2.x * The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. * Trailing whitespace no longer is counted as part of a node. * `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. * The `esparse` and `esvalidate` binary scripts have been removed. * There is no `tolerant` option. We will investigate adding this back in the future. ## Known Incompatibilities In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. ### Esprima 1.2.2 * Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. * Espree does not parse `let` and `const` declarations by default. * Error messages returned for parsing errors are different. * There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. ### Esprima 2.x * Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. ## Frequently Asked Questions ### Why another parser [ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. ### Have you tried working with Esprima? Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. ### Why don't you just use Acorn? Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. ### What ECMAScript features do you support? Espree supports all ECMAScript 2020 features and partially supports ECMAScript 2021 features. Because ECMAScript 2021 is still under development, we are implementing features as they are finalized. Currently, Espree supports: * [Logical Assignment Operators](https://github.com/tc39/proposal-logical-assignment) * [Numeric Separators](https://github.com/tc39/proposal-numeric-separator) See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. ### How do you determine which experimental features to support? In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ``` [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) ### Status: Work in progress Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ [![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) [![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) [![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) <br /> [![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) [![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) [![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) # ESLint [Website](https://eslint.org) | [Configuring](https://eslint.org/docs/user-guide/configuring) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | [Code of Conduct](https://eslint.org/conduct) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://eslint.org/chat) ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. ## Table of Contents 1. [Installation and Usage](#installation-and-usage) 2. [Configuration](#configuration) 3. [Code of Conduct](#code-of-conduct) 4. [Filing Issues](#filing-issues) 5. [Frequently Asked Questions](#faq) 6. [Releases](#releases) 7. [Security Policy](#security-policy) 8. [Semantic Versioning Policy](#semantic-versioning-policy) 9. [Stylistic Rule Updates](#stylistic-rule-updates) 10. [License](#license) 11. [Team](#team) 12. [Sponsors](#sponsors) 13. [Technology Sponsors](#technology-sponsors) ## <a name="installation-and-usage"></a>Installation and Usage Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install ESLint using npm: ``` $ npm install eslint --save-dev ``` You should then set up a configuration file: ``` $ ./node_modules/.bin/eslint --init ``` After that, you can run ESLint on any file or directory like this: ``` $ ./node_modules/.bin/eslint yourfile.js ``` ## <a name="configuration"></a>Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: ```json { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). ## <a name="code-of-conduct"></a>Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://eslint.org/conduct). ## <a name="filing-issues"></a>Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: * [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) * [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) ## <a name="faq"></a>Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. ### Why can't ESLint find my plugins? * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. * Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. ### What ECMAScript versions does ESLint support? ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). ### What about experimental features? ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). ### Why doesn't ESLint lock dependency versions? Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. ## <a name="releases"></a>Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. ## <a name="security-policy"></a>Security Policy ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## <a name="semantic-versioning-policy"></a>Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: * Patch release (intended to not break your lint build) * A bug fix in a rule that results in ESLint reporting fewer linting errors. * A bug fix to the CLI or core (including formatters). * Improvements to documentation. * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). * Minor release (might break your lint build) * A bug fix in a rule that results in ESLint reporting more linting errors. * A new rule is created. * A new option to an existing rule that does not result in ESLint reporting more linting errors by default. * A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. * An existing rule is deprecated. * A new CLI capability is created. * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). * A new formatter is created. * `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). * Major release (likely to break your lint build) * `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). * A new option to an existing rule that results in ESLint reporting more linting errors by default. * An existing formatter is removed. * Part of the public API is removed or changed in an incompatible way. The public API includes: * Rule schemas * Configuration schema * Command-line options * Node.js API * Rule, formatter, parser, plugin APIs According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. ## <a name="stylistic-rule-updates"></a>Stylistic Rule Updates Stylistic rules are frozen according to [our policy](https://eslint.org/blog/2020/05/changes-to-rules-policies) on how we evaluate new rules and rule changes. This means: * **Bug fixes**: We will still fix bugs in stylistic rules. * **New ECMAScript features**: We will also make sure stylistic rules are compatible with new ECMAScript features. * **New options**: We will **not** add any new options to stylistic rules unless an option is the only way to fix a bug or support a newly-added ECMAScript feature. ## <a name="license"></a>License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) ## <a name="team"></a>Team These folks keep the project moving and are resources for help. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--teamstart--> ### Technical Steering Committee (TSC) The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/nzakas"> <img src="https://github.com/nzakas.png?s=75" width="75" height="75"><br /> Nicholas C. Zakas </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/btmills"> <img src="https://github.com/btmills.png?s=75" width="75" height="75"><br /> Brandon Mills </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/mdjermanovic"> <img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br /> Milos Djermanovic </a> </td></tr></tbody></table> ### Reviewers The people who review and implement new features. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/mysticatea"> <img src="https://github.com/mysticatea.png?s=75" width="75" height="75"><br /> Toru Nagashima </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/aladdin-add"> <img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br /> 薛定谔的猫 </a> </td></tr></tbody></table> ### Committers The people who review and fix bugs and help triage issues. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/brettz9"> <img src="https://github.com/brettz9.png?s=75" width="75" height="75"><br /> Brett Zamir </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/bmish"> <img src="https://github.com/bmish.png?s=75" width="75" height="75"><br /> Bryan Mishkin </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/g-plane"> <img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br /> Pig Fang </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/anikethsaha"> <img src="https://github.com/anikethsaha.png?s=75" width="75" height="75"><br /> Anix </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/yeonjuan"> <img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br /> YeonJuan </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/snitin315"> <img src="https://github.com/snitin315.png?s=75" width="75" height="75"><br /> Nitin Kumar </a> </td></tr></tbody></table> <!--teamend--> ## <a name="sponsors"></a>Sponsors The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--sponsorsstart--> <h3>Platinum Sponsors</h3> <p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3> <p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p> <!--sponsorsend--> ## <a name="technology-sponsors"></a>Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) * Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) * Password management is sponsored by [1Password](https://www.1password.com) # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # eslint-utils [![npm version](https://img.shields.io/npm/v/eslint-utils.svg)](https://www.npmjs.com/package/eslint-utils) [![Downloads/month](https://img.shields.io/npm/dm/eslint-utils.svg)](http://www.npmtrends.com/eslint-utils) [![Build Status](https://github.com/mysticatea/eslint-utils/workflows/CI/badge.svg)](https://github.com/mysticatea/eslint-utils/actions) [![Coverage Status](https://codecov.io/gh/mysticatea/eslint-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-utils) [![Dependency Status](https://david-dm.org/mysticatea/eslint-utils.svg)](https://david-dm.org/mysticatea/eslint-utils) ## 🏁 Goal This package provides utility functions and classes for make ESLint custom rules. For examples: - [getStaticValue](https://eslint-utils.mysticatea.dev/api/ast-utils.html#getstaticvalue) evaluates static value on AST. - [ReferenceTracker](https://eslint-utils.mysticatea.dev/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. ## 📖 Usage See [documentation](https://eslint-utils.mysticatea.dev/). ## 📰 Changelog See [releases](https://github.com/mysticatea/eslint-utils/releases). ## ❤️ Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run clean` removes the coverage result of `npm test` command. - `npm run coverage` shows the coverage result of the last `npm test` command. - `npm run lint` runs ESLint. - `npm run watch` runs tests on each file change. ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` ## Test Strategy - tests are copied from the [polyfill implementation](https://github.com/tc39/proposal-temporal/tree/main/polyfill/test) - tests should be removed if they relate to features that do not make sense for TS/AS, i.e. tests that validate the shape of an object do not make sense in a language with compile-time type checking - tests that fail because a feature has not been implemented yet should be left as failures. binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(low: `number`, high: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT # rechoir [![Build Status](https://secure.travis-ci.org/tkellen/js-rechoir.png)](http://travis-ci.org/tkellen/js-rechoir) > Require any supported file as a node module. [![NPM](https://nodei.co/npm/rechoir.png)](https://nodei.co/npm/rechoir/) ## What is it? This module, in conjunction with [interpret]-like objects can register any file type the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. ## API ### prepare(config, filepath, requireFrom) Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). `config` An [interpret]-like configuration object. `filepath` A file whose type you'd like to register a module loader for. `requireFrom` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. If calling this method is successful (aka: it doesn't throw), you can now require files of the type you requested natively. An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. If a loader is already registered, this will simply return `true`. **Note:** While rechoir will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. #### Usage ```js const config = require('interpret').extensions; const rechoir = require('rechoir'); rechoir.prepare(config, './test/fixtures/test.coffee'); rechoir.prepare(config, './test/fixtures/test.csv'); rechoir.prepare(config, './test/fixtures/test.toml'); console.log(require('./test/fixtures/test.coffee')); console.log(require('./test/fixtures/test.csv')); console.log(require('./test/fixtures/test.toml')); ``` [interpret]: http://github.com/tkellen/js-interpret [Liftoff]: http://github.com/tkellen/js-liftoff # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. [![build status](https://app.travis-ci.com/dankogai/js-base64.svg)](https://app.travis-ci.com/github/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.encode(latin, true)); // ZGFua29nYWk skips padding Base64.encodeURI(latin)); // ZGFua29nYWk Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.decode( 'ZGFua29nYWk'); // dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend Uint8Array.prototype Base64.extendUint8Array(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IEs before 11. Do the following in your shell. ```shell $ make base64.es5.js ``` ## Brief History * Since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. * Since version 3.7 `base64.js` is ES5-compatible again (hence IE11-compabile). * Since 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above) # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) ## Timezone support In order to provide support for timezones, without relying on the JavaScript host or any other time-zone aware environment, this library makes use of teh IANA Timezone Database directly: https://www.iana.org/time-zones The database files are parsed by the scripts in this folder, which emit AssemblyScript code which is used to process the various rules at runtime. <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # Acorn-JSX [![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) [![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. ## Transpiler Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. ## Usage Requiring this module provides you with an Acorn plugin that you can use like this: ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');"); ``` Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `[email protected]`. If you still want to opt-in to support of such constructions, you can pass the following option: ```javascript acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) ``` Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: ```javascript acorn.Parser.extend(jsx({ allowNamespaces: false })) ``` Note that by default `allowNamespaces` is enabled for spec compliancy. ## License This plugin is issued under the [MIT license](./LICENSE). # word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: [demo](https://estools.github.io/esquery/) The following selectors are supported: * AST node type: `ForStatement` * [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` * [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` * [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` * attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` * attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` * nested attribute: `[attr.level2="foo"]` * field: `FunctionDeclaration > Identifier.id` * [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` * [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` * [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` * [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` * [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` * [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` * [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` * [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` * [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)` * [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` * [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` * class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` [![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # file-entry-cache > Super simple cache for file metadata, useful for process that work o a given series of files > and that only need to repeat the job on the changed ones since the previous run of the process — Edit [![NPM Version](http://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) [![Build Status](http://img.shields.io/travis/royriojas/file-entry-cache.svg?style=flat)](https://travis-ci.org/royriojas/file-entry-cache) ## install ```bash npm i --save file-entry-cache ``` ## Usage The module exposes two functions `create` and `createFromFile`. ## `create(cacheName, [directory, useCheckSum])` - **cacheName**: the name of the cache to be created - **directory**: Optional the directory to load the cache from - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ## `createFromFile(pathToCache, [useCheckSum])` - **pathToCache**: the path to the cache file (this combines the cache name and directory) - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ```js // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var fileEntryCache = require('file-entry-cache'); var cache = fileEntryCache.create('testCache'); var files = expand('../fixtures/*.txt'); // the first time this method is called, will return all the files var oFiles = cache.getUpdatedFiles(files); // this will persist this to disk checking each file stats and // updating the meta attributes `size` and `mtime`. // custom fields could also be added to the meta object and will be persisted // in order to retrieve them later cache.reconcile(); // use this if you want the non visited file entries to be kept in the cache // for more than one execution // // cache.reconcile( true /* noPrune */) // on a second run var cache2 = fileEntryCache.create('testCache'); // will return now only the files that were modified or none // if no files were modified previous to the execution of this function var oFiles = cache.getUpdatedFiles(files); // if you want to prevent a file from being considered non modified // something useful if a file failed some sort of validation // you can then remove the entry from the cache doing cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` // that will effectively make the file to appear again as modified until the validation is passed. In that // case you should not remove it from the cache // if you need all the files, so you can determine what to do with the changed ones // you can call var oFiles = cache.normalizeEntries(files); // oFiles will be an array of objects like the following entry = { key: 'some/name/file', the path to the file changed: true, // if the file was changed since previous run meta: { size: 3242, // the size of the file mtime: 231231231, // the modification time of the file data: {} // some extra field stored for this file (useful to save the result of a transformation on the file } } ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with optional file persistance. The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, then store the new state of the files. The next time this module request for `getChangedFiles` will return only the files that were modified. Making the process to end faster. This module could also be used by processes that modify the files applying a transform, in that case the result of the transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed the transformed stored data could be used instead of actually applying the transformation, saving time in case of only a few files changed. In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. ## Important notes - The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values - All the changes to the cache state are done to memory first and only persisted after reconcile. ## License MIT
GigameshGarages_MezzooNet
DixxNet AnonymousVoting .circleci config.yml README.md circuits jest.config.js package-lock.json package.json scripts build_snarks.sh checksum_snarks.sh download_snarks.sh runTestsInCircleCi.sh ts __tests__ blake2s Blake2s.test.ts Uint32.test.ts bin2hex.ts hex2bin.ts index.ts tsconfig.json config package-lock.json package.json ts index.ts tsconfig.json contracts jest.config.js package-lock.json package.json scripts compileSol.sh runGanache.sh runTestsInCircleCi.sh ts __tests__ FixedVerifier.test.ts IncrementalMerkleTree.test.ts Semaphore.test.ts buildMiMC.ts index.ts tsconfig.json docs FontAwesome css font-awesome.css fonts fontawesome-webfont.svg about.html api.html audit.html ayu-highlight.css book.js clipboard.min.js creditsandresources.html css chrome.css general.css print.css variables.css elasticlunr.min.js highlight.css highlight.js howitworks.html index.html libsemaphore.html mark.min.js print.html quickstart.html searcher.js searchindex.js searchindex.json tomorrow-night.css trustedsetup.html usage.html docs_src build.sh serve.sh src SUMMARY.md about.md api.md audit.md creditsandresources.md howitworks.md libsemaphore.md quickstart.md trustedsetup.md usage.md lerna.json package-lock.json package.json tsconfig.json QuadraticVoting .eslintrc.js .travis.yml README.md circuits README.md jest.config.js package-lock.json package.json scripts buildBatchUpdateStateTreeSnark.sh buildQuadVoteTallySnark.sh buildSnarksSmall.sh checksumSnarks.sh installZkutil.sh runTestsInCircleCi.sh ts __tests__ BatchUpdateStateTree.test.ts CalculateTotal.test.ts Decrypt.test.ts Ecdh.test.ts Hasher.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts PublicKey.test.ts QuadVoteTally.test.ts QuinGeneratePathIndices.test.ts QuinSelector.test.ts ResultCommitmentVerifier.test.ts Splicer.test.ts UpdateStateTree.test.ts VerifySignature.test.ts utils.ts buildSnarks.ts genVerifier.ts index.ts tsconfig.json cli README.md jest.config.js package-lock.json package.json ts create.ts defaults.ts genMaciKeypair.ts genMaciPubkey.ts index.ts process.ts publish.ts signUp.ts tally.ts utils.ts verify.ts tsconfig.json config package-lock.json package.json ts index.ts tsconfig.json contracts README.md jest.config.js package-lock.json package.json scripts compileSol.sh runGanache.sh runTestsInCircleCi.sh sol .solhint.json ts __tests__ BatchProcessMessageAndQuadVoteTally.test.ts Hasher.test.ts HasherBenchmarks.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts PublishMessage.test.ts SignUp.test.ts VerifyTally.test.ts utils.ts accounts.ts buildPoseidon.ts deploy.ts index.ts utils.ts tsconfig.json core README.md jest.config.js package-lock.json package.json ts MaciState.ts User.ts __tests__ MaciState.test.ts ProcessMessage.test.ts User.test.ts index.ts tsconfig.json crypto README.md jest.config.js package-lock.json package.json ts IncrementalQuinTree.ts __tests__ Crypto.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts index.ts tsconfig.json domainobjs README.md jest.config.js package-lock.json package.json ts __tests__ DomainObjs.test.ts index.ts tsconfig.json integrationTests README.md jest.config.js package-lock.json package.json scripts runTestsInCircleCi.sh ts __tests__ cli-create.test.ts cli-genMaciKeypair.test.ts cli-genMaciPubkey.test.ts cli-processTallyVerify.test.ts cli-signupAndPublish.test.ts params.ts suites.test.ts suites.ts suites suite0_happy.json suite1_small.json suite2_bribe.json utils.ts tsconfig.json lerna.json package-lock.json package.json specs 01_introduction.md 02_contract.md 03_circuits.md 04_state_root_transition_circuit.md 05_quadratic_vote_tallying_circuit.md faq.md package-lock.json package.json tsconfig.json README.md | GixxNet .github ISSUE_TEMPLATE.md PULL_REQUEST_TEMPLATE.md workflows audit.yml ci.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md Cargo.toml NEWS.md README.md chain arweave Cargo.toml src adapter.rs lib.rs ethereum Cargo.toml src block_ingestor.rs block_stream.rs config.rs ethereum_adapter.rs lib.rs network_indexer block_writer.rs convert.rs metrics.rs mod.rs network_indexer.rs subgraph.rs transport.rs tests network_indexer.rs core Cargo.toml src lib.rs link_resolver.rs metrics mod.rs registry.rs subgraph instance.rs instance_manager.rs loader.rs mod.rs provider.rs registrar.rs three_box.rs tests interfaces.rs docker README.md build.sh docker-compose.yml setup.sh tag.sh docs environment-variables.md ethereum-config.md getting-started.md implementation README.md schema-generation.md sql-query-generation.md time-travel.md sharding.md subgraph-manifest.md graph Cargo.toml examples stress.rs src cheap_clone.rs components arweave adapter.rs mod.rs ethereum adapter.rs listener.rs mod.rs network.rs stream.rs types.rs graphql.rs link_resolver.rs metrics aggregate.rs mod.rs stopwatch.rs mod.rs server admin.rs index_node.rs metrics.rs mod.rs query.rs subscription.rs store.rs subgraph host.rs instance.rs instance_manager.rs mod.rs proof_of_indexing event.rs mod.rs online.rs reference.rs provider.rs registrar.rs validation mod.rs three_box.rs data graphql effort.rs ext.rs mod.rs object_macro.rs object_or_interface.rs serialization.rs shape_hash.rs values.rs mod.rs query cache_status.rs error.rs mod.rs query.rs result.rs schema.rs store ethereum.rs mod.rs scalar.rs subgraph data_source.rs mod.rs schema.rs status.rs subscription error.rs mod.rs result.rs subscription.rs ext futures.rs mod.rs ipfs_client.rs lib.rs log codes.rs elastic.rs factory.rs mod.rs split.rs task_spawn.rs util cache_weight.rs error.rs ethereum.rs futures.rs jobs.rs lfu_cache.rs mod.rs security.rs stats.rs timed_rw_lock.rs tests entity_cache.rs manifest.rs graphql Cargo.toml examples schema.rs src execution cache.rs execution.rs mod.rs query.rs resolver.rs introspection mod.rs resolver.rs schema.rs lib.rs query ast.rs ext.rs mod.rs runner.rs schema api.rs ast.rs mod.rs store mod.rs prefetch.rs query.rs resolver.rs subscription mod.rs values coercion.rs mod.rs tests introspection.rs query.rs mock Cargo.toml src block_stream.rs lib.rs metrics_registry.rs store.rs node Cargo.toml src bin manager.rs config.rs lib.rs main.rs manager catalog.rs commands assign.rs config.rs info.rs listen.rs mod.rs remove.rs txn_speed.rs unused_deployments.rs deployment.rs display.rs mod.rs opt.rs store_builder.rs tests cli.rs resources construction.svg runtime derive Cargo.toml src lib.rs wasm Cargo.toml src asc_abi asc_ptr.rs class.rs mod.rs error.rs host.rs host_exports.rs lib.rs mapping.rs module into_wasm_ret.rs mod.rs stopwatch.rs test.rs test abi.rs to_from external.rs mod.rs wasm_test abi_classes.ts abi_store_value.ts abi_token.ts abort.ts big_int_arithmetic.ts big_int_to_hex.ts big_int_to_string.ts bytes_to_base58.ts contract_calls.ts crypto.ts data_source_create.ts ens_name_by_hash.ts ipfs_cat.ts ipfs_map.ts json_parsing.ts non_terminating.ts store.ts string_to_number.ts server http Cargo.toml assets graphiql.css graphiql.min.js index.html src lib.rs request.rs server.rs service.rs test_utils.rs tests response.rs server.rs index-node Cargo.toml assets graphiql.css graphiql.min.js index.html src explorer.rs lib.rs request.rs resolver.rs schema.rs server.rs service.rs json-rpc Cargo.toml src lib.rs metrics Cargo.toml src lib.rs websocket Cargo.toml src connection.rs lib.rs server.rs store postgres Cargo.toml examples layout.rs migrations 2018-07-10-061642_create_entities_table down.sql up.sql 2018-07-10-061659_create_history_tables down.sql up.sql 2018-07-10-062717_create_history_triggers down.sql up.sql 2018-07-10-062730_create_revert_procedures down.sql up.sql 2018-08-16-143800_create_entity_change_triggers down.sql up.sql 2018-08-22-130000_create_blockchain_tables down.sql up.sql 2018-08-22-140000_create_chain_head_update_procedure down.sql up.sql 2018-08-29-120000_create_subgraphs_table down.sql up.sql 2018-09-07-220000_create_ancestor_lookup_procedure down.sql up.sql 2018-09-18-180000_add_ethereum_network_identifiers down.sql up.sql 2018-12-02-114100_create_subgraph_deployments_table down.sql up.sql 2018-12-03-150000_add_subgraph_cost down.sql up.sql 2018-12-21-003727_create_attribute_indexing_procedure down.sql up.sql 2019-01-07-120000_remove_subgraphs_deployments_tables down.sql up.sql 2019-01-18-195346_update_history_triggers down.sql up.sql 2019-01-18-195526_update_revert_procedures down.sql up.sql 2019-02-01-045927_add_entities_indexes down.sql up.sql 2019-02-04-114900_remove_entity_change_triggers down.sql up.sql 2019-02-25-182843_add_pg_stat_statements down.sql up.sql 2019-02-26-182914_remove_unassigned_deployment_indexes_procedure down.sql up.sql 2019-02-26-183156_cleanup_unassigned_deployment_indexes down.sql up.sql 2019-02-27-035443_create_large_notifications down.sql up.sql 2019-02-28-190800_update_chain_head_update_procedure down.sql up.sql 2019-03-04-235349_empty-ethereum-network-chain-head-update-fix down.sql up.sql 2019-03-07-171355_update_history_storage down.sql up.sql 2019-03-28-004319_drop_entities_id_indexes down.sql up.sql 2019-03-31-010824_short_chain_head_update down.sql up.sql 2019-04-19-171709_split_entities down.sql up.sql 2019-04-22-190022_remove_unneeded_stored_procs down.sql up.sql 2019-05-03-164052_store_entity_count down.sql up.sql 2019-05-09-135900_create_subgraphs_entity_history_table down.sql up.sql 2019-05-09-232642_ens_names down.sql up.sql 2019-05-14-200255_event_meta_data_source_index down.sql up.sql 2019-05-15-215022_migrate_entities down.sql up.sql 2019-06-05-214320_uncled_chain_head_update down.sql up.sql 2019-06-26-164405_index_dynamic_ethereum_contract_data_source_deployment down.sql up.sql 2019-07-20-195916_remove_subgraph down.sql up.sql 2019-08-02-001120_short_chain_head_update down.sql up.sql 2019-09-01-135850_relational_schema down.sql up.sql 2019-09-02-230613_create_btree_extension down.sql up.sql 2019-10-01-173616_create_eth_call_cache down.sql up.sql 2020-01-14-235608_relational_metadata_views down.sql up.sql 2020-01-17-013633_remove_unused_procs down.sql up.sql 2020-01-24-065338_add_reduce_dim down.sql up.sql 2020-03-06-020253_relational-metadata down.sql up.sql 2020-03-11-162100_add_data_source_context down.sql up.sql 2020-03-25-170527_deployment_graft_base down.sql up.sql 2020-04-04-002817_change_deployment_state down.sql up.sql 2020-04-10-111111_add_deployment_errors down.sql up.sql 2020-05-16-225611_add_deployment_detail_view down.sql up.sql 2020-07-07-002933_add_deployment_reorg_counts down.sql up.sql 2020-07-31-162138_meta-views down.sql up.sql 2020-10-31-150000_deterministic_errors down.sql up.sql 2020-11-03-170839_subgraph_name_unique down.sql up.sql 2020-11-10-100000_last_healthy_block down.sql up.sql 2020-12-11-142000_subgraph_manifest_features down.sql up.sql 2020-12-12-000001_remove_migrationg_flag down.sql up.sql 2020-12-12-000002_add_shard_to_deployment_schemas down.sql up.sql 2020-12-12-000003_remove_deployment_schemas_state down.sql up.sql 2020-12-12-000004_sharded_deployment_detail down.sql up.sql 2020-12-12-000005_remove_metadata_subgraph down.sql up.sql 2020-12-15-000000_remove_nested_templates down.sql up.sql 2020-12-7-190800_subgraph_error_changes down.sql up.sql 2021-01-07-004939_create_unused_deployments down.sql up.sql 2021-01-14-175654_add_network_to_deployment_schemas down.sql up.sql 2021-01-14-193022_deployment_schemas_network_not_null down.sql up.sql 2021-01-15-013524_drop_deployment_detail down.sql up.sql 2021-01-19-033749_add_chains down.sql up.sql 2021-01-26-044443_drop_attempt_chain_head_update down.sql up.sql 2021-01-26-172953_drop_lookup_ancestor_block down.sql up.sql 2021-01-26-173710_add_chains_namespace down.sql up.sql 2021-01-26-204036_ethereum_networks_net_ident_not_null down.sql up.sql 2021-02-17-205502_simplify_metadata down.sql up.sql 2021-02-18-000721_dds_embed_source down.sql up.sql 2021-02-18-171423_dds_remove_ethereum_contract_source down.sql up.sql 2021-02-24-051050_dds_remove_unused_columns down.sql up.sql 2021-02-25-233156_dds_remove_id_block_range down.sql up.sql 2021-03-11-010830_fdw down.sql up.sql 2021-03-11-231340_subgraph_deployment_changes down.sql up.sql 2021-03-12-014815_subgraph_deployment_pkey down.sql up.sql src block_range.rs block_store.rs catalog.rs chain_head_listener.rs chain_store.rs connection_pool.rs deployment.rs deployment_store.rs detail.rs dynds.rs functions.rs jobs.rs jsonb.rs lib.rs notification_listener.rs primary.rs query_store.rs relational.rs relational_queries.rs sql_value.rs store.rs store_events.rs subgraph_store.rs tests chain_head.rs graft.rs relational.rs relational_bytes.rs store.rs subgraph.rs test-store Cargo.toml config.simple.toml src block_store.rs lib.rs store.rs tests Cargo.toml integration-tests arweave-and-3box package.json src mapping.ts test test.js truffle.js big-decimal package.json src mapping.ts test test.js truffle.js common 1_initial_migration.js 2_deploy_contracts.js build-contracts.sh data-source-context package.json src dynamic_mapping.ts mapping.ts test test.js truffle.js data-source-revert package.json src mapping.ts test test.js truffle.js fatal-error package.json src mapping.ts test test.js truffle.js ganache-reverts migrations 1_initial_migration.js 2_deploy_contracts.js package.json src mapping.ts test test.js truffle.js non-fatal-errors package.json src mapping.ts test test.js truffle.js overloaded-contract-functions migrations 1_initial_migration.js 2_deploy_contracts.js package.json src mapping.ts test test.js truffle.js package.json remove-then-update package.json src mapping.ts test test.js truffle.js value-roundtrip package.json src mapping.ts test test.js truffle.js tests common docker.rs helpers.rs mod.rs parallel_tests.rs MixxNet README.md auction core .circleci config.yml README.md addresses 1.json 4.json hardhat.config.ts index.ts package.json scripts deploy.ts index.ts mediaInfo.ts mint.ts watch.ts test Market.test.ts Media.test.ts utils.ts tsconfig.json utils Blockchain.ts Decimal.ts generatedWallets.ts index.ts core build contracts AccessControl.json AccessControlEnumerable.json AccessControlEnumerableMock.json AccessControlMock.json Address.json AddressImpl.json Arrays.json ArraysImpl.json BadBeaconNoImpl.json BadBeaconNotContract.json BancorFormula.json BeaconProxy.json CallReceiverMock.json ClashingImplementation.json Clones.json ClonesMock.json ConditionalEscrow.json ConditionalEscrowMock.json Context.json ContextMock.json ContextMockCaller.json Counters.json CountersImpl.json Create2.json Create2Impl.json DummyImplementation.json DummyImplementationV2.json ECDSA.json ECDSAMock.json EIP712.json EIP712External.json ERC1155Burnable.json ERC1155BurnableMock.json ERC1155Holder.json ERC1155Pausable.json ERC1155Receiver.json ERC1155ReceiverMock.json ERC165.json ERC165Checker.json ERC165CheckerMock.json ERC165InterfacesSupported.json ERC165MissingData.json ERC165Mock.json ERC165NotSupported.json ERC165Storage.json ERC165StorageMock.json ERC1820Implementer.json ERC1820ImplementerMock.json ERC1967Proxy.json ERC20.json ERC20Burnable.json ERC20BurnableMock.json ERC20Capped.json ERC20CappedMock.json ERC20DecimalsMock.json ERC20Mock.json ERC20NoReturnMock.json ERC20Pausable.json ERC20PausableMock.json ERC20Permit.json ERC20PermitMock.json ERC20PresetFixedSupply.json ERC20PresetMinterPauser.json ERC20ReturnFalseMock.json ERC20ReturnTrueMock.json ERC20Snapshot.json ERC20SnapshotMock.json ERC2771Context.json ERC2771ContextMock.json ERC721Burnable.json ERC721BurnableMock.json ERC721Enumerable.json ERC721EnumerableMock.json ERC721Holder.json ERC721Mock.json ERC721Pausable.json ERC721PausableMock.json ERC721ReceiverMock.json ERC721URIStorage.json ERC721URIStorageMock.json ERC777PresetFixedSupply.json ERC777SenderRecipientMock.json EddyBuddy.json EnumerableAddressSetMock.json EnumerableBytes32SetMock.json EnumerableMap.json EnumerableMapMock.json EnumerableSet.json EnumerableUintSetMock.json Escrow.json EtherReceiverMock.json IAccessControl.json IAccessControlEnumerable.json IBeacon.json IBeaconContract.json IBondingCurve.json IERC1155.json IERC1155MetadataURI.json IERC1155Receiver.json IERC1620.json IERC165.json IERC1820Implementer.json IERC1820Registry.json IERC20.json IERC20Metadata.json IERC20Permit.json IERC721.json IERC721Enumerable.json IERC721Metadata.json IERC721Receiver.json IERC777.json IERC777Recipient.json IERC777Sender.json Impl.json Implementation1.json Implementation2.json Implementation3.json Implementation4.json Initializable.json InitializableMock.json Math.json MathMock.json MerkleProof.json MerkleProofWrapper.json MigratableMockV1.json MigratableMockV2.json MigratableMockV3.json MinimalForwarder.json Ownable.json OwnableMock.json Pausable.json PausableMock.json PaymentSplitter.json Proxy.json ProxyAdmin.json PullPayment.json PullPaymentMock.json ReentrancyAttack.json ReentrancyGuard.json ReentrancyMock.json RefundEscrow.json SafeCast.json SafeCastMock.json SafeERC20.json SafeERC20Wrapper.json SafeMath.json SafeMathMock.json SampleChild.json SampleFather.json SampleGramps.json SampleHuman.json SampleMother.json SignedSafeMath.json SignedSafeMathMock.json Strings.json StringsMock.json SupportsInterfaceWithLookupMock.json TokenTimelock.json TransparentUpgradeableProxy.json UpgradeableBeacon.json Utils.json ZkDeposit.json ZkMMRInclusion.json ZkMimblewimble.json ZkRangeProof.json ZkRollUp1.json ZkRollUp128.json ZkRollUp16.json ZkRollUp2.json ZkRollUp32.json ZkRollUp4.json ZkRollUp64.json ZkRollUp8.json ZkWithdraw.json migrations 1_initial_migration.js truffle-config.js deployments rainbow-bridge .buildkite contracts-eth.yml contracts-near.yml npm-package.yml pipeline.yml CHANGELOG.md CODE_OF_CONDUCT.md CONTRIBUTING.md MIGRATION.md README.md SPEC.md cli commands clean.js danger-deploy-myerc20.js danger-submit-invalid-near-block.js eth-dump.js near-dump.js prepare.js start address-watcher.js eth2near-relay.js ganache.js helpers.js near.js near2eth-relay.js watchdog.js status.js stop process.js index.js init eth-contracts.js index.js near-contracts.js near-token-factory.js package.json codechecks.yml contracts eth CHANGELOG.md build_all.sh ci test_verify_near_headers.sh test_verify_near_proofs.sh dist.sh nearbridge .solcover.js .soliumrc.json README.md dist.sh hardhat.config.js package.json test 181.json 244.json 304.json 308.json 368.json 369.json NearBridge.js NearBridge2.js block_120998.json block_121498.json block_121998.json block_12640118.json block_12640218.json block_15178713.json block_15178760.json block_15204402.json block_15248583.json block_9580503.json block_9580534.json block_9580624.json block_9605.json block_9610.json ed25519-test-cases.json ed25519-test.js init_validators_12640118.json init_validators_15178713.json truffle.js nearprover .solcover.js .soliumrc.json README.md dist.sh hardhat.config.js package.json test NearProver.js proof2.json proof3.json proof4.json proof5.json proof6.json truffle.js utils utils.js package.json near .buildkite pipeline.yml Cargo.toml admin-controlled Cargo.toml src lib.rs macros.rs build_all.sh ci test_verify_eth_headers.sh test_verify_eth_proofs.sh eth-client Cargo.toml README.md build.sh src data 10234001.json 10234002.json 10234003.json 10234004.json 10234005.json 10234006.json 10234007.json 10234008.json 10234009.json 10234010.json 10234011.json 2.json 3.json 400000.json 400001.json 8996776.json 8996777.json dag_merkle_roots.json lib.rs tests.rs test.sh eth-prover Cargo.toml build.sh src lib.rs tests.rs test.sh tests spec.rs utils.rs eth-types Cargo.toml src lib.rs mintable-fungible-token build.sh package.json docker-compose-dev.yml docker-compose-prod.yml docker-compose.yml docs README.md address-watcher.md workflows eth2near-fun-transfer.md eth2near eth2near-block-relay dag_merkle_roots.json eth-on-near-client.js eth-on-near-prover.js eth-proof-extractor.js index.js package.json near2eth near2eth-block-relay index.js package.json watchdog index.js package.json package.json testing adapter index.js ci e2e.sh e2e_ci_prepare_env.sh e2e_ci_prepare_log.sh e2e_deploy_contract.sh test_challenge.sh test_ethrelay_catchup.sh test_npm_package.sh index.js package.json transfer-eth-erc20 deploy-token.js from-near.js index.js near-mintable-token.js to-near.js vendor ganache package.json utils address-watcher.js borsh.js borshify-proof.js config config.json index.js get-config.js helpers.js http-prometheus.js index.js package.json robust.js scripts clean_start.sh prepare.sh start_ganache.sh utils.js minty README.md config default.js end-to-end-tutorial.md hardhat.config.js package-lock.json package.json src deploy.js index.js minty.js start-local-environment.sh test sample-test.js recipes EddyNet_SampleRecipe.txt Kochi_Kulukki_Video_Hash.txt ui-apps pinata-party-frontend README.md package.json public index.html manifest.json robots.txt src App.css App.js App.test.js UploadFile.js index.css index.js logo.svg reportWebVitals.js setupTests.js NixxNet README.md build contracts Address.json BancorFormula.json Context.json ERC20.json IBeaconContract.json IBondingCurve.json IERC1620.json IERC20.json Initializable.json MiMCpe7_generated.json Ownable.json ReentrancyGuard.json SafeMath.json SiddhiCurve.json Utils.json ZkDeposit.json ZkMMRInclusion.json ZkMimblewimble.json ZkRangeProof.json ZkRollUp1.json ZkRollUp128.json ZkRollUp16.json ZkRollUp2.json ZkRollUp32.json ZkRollUp4.json ZkRollUp64.json ZkRollUp8.json ZkWithdraw.json migrations 1_initial_migration.js 2_deploy_migrations.js package-lock.json package.json truffle-config.js README.md RixxNet ArbitrationNetwork AnonymousVoting .circleci config.yml README.md circuits jest.config.js package-lock.json package.json scripts build_snarks.sh checksum_snarks.sh download_snarks.sh runTestsInCircleCi.sh ts __tests__ blake2s Blake2s.test.ts Uint32.test.ts bin2hex.ts hex2bin.ts index.ts tsconfig.json config package-lock.json package.json ts index.ts tsconfig.json contracts jest.config.js package-lock.json package.json scripts compileSol.sh runGanache.sh runTestsInCircleCi.sh ts __tests__ FixedVerifier.test.ts IncrementalMerkleTree.test.ts Semaphore.test.ts buildMiMC.ts index.ts tsconfig.json docs FontAwesome css font-awesome.css fonts fontawesome-webfont.svg about.html api.html audit.html ayu-highlight.css book.js clipboard.min.js creditsandresources.html css chrome.css general.css print.css variables.css elasticlunr.min.js highlight.css highlight.js howitworks.html index.html libsemaphore.html mark.min.js print.html quickstart.html searcher.js searchindex.js searchindex.json tomorrow-night.css trustedsetup.html usage.html docs_src build.sh serve.sh src SUMMARY.md about.md api.md audit.md creditsandresources.md howitworks.md libsemaphore.md quickstart.md trustedsetup.md usage.md lerna.json package-lock.json package.json tsconfig.json QuadraticVoting .eslintrc.js .travis.yml README.md circuits README.md jest.config.js package-lock.json package.json scripts buildBatchUpdateStateTreeSnark.sh buildQuadVoteTallySnark.sh buildSnarksSmall.sh checksumSnarks.sh installZkutil.sh runTestsInCircleCi.sh ts __tests__ BatchUpdateStateTree.test.ts CalculateTotal.test.ts Decrypt.test.ts Ecdh.test.ts Hasher.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts PublicKey.test.ts QuadVoteTally.test.ts QuinGeneratePathIndices.test.ts QuinSelector.test.ts ResultCommitmentVerifier.test.ts Splicer.test.ts UpdateStateTree.test.ts VerifySignature.test.ts utils.ts buildSnarks.ts genVerifier.ts index.ts tsconfig.json cli README.md jest.config.js package-lock.json package.json ts create.ts defaults.ts genMaciKeypair.ts genMaciPubkey.ts index.ts process.ts publish.ts signUp.ts tally.ts utils.ts verify.ts tsconfig.json config package-lock.json package.json ts index.ts tsconfig.json contracts README.md jest.config.js package-lock.json package.json scripts compileSol.sh runGanache.sh runTestsInCircleCi.sh sol .solhint.json ts __tests__ BatchProcessMessageAndQuadVoteTally.test.ts Hasher.test.ts HasherBenchmarks.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts PublishMessage.test.ts SignUp.test.ts VerifyTally.test.ts utils.ts accounts.ts buildPoseidon.ts deploy.ts index.ts utils.ts tsconfig.json core README.md jest.config.js package-lock.json package.json ts MaciState.ts User.ts __tests__ MaciState.test.ts ProcessMessage.test.ts User.test.ts index.ts tsconfig.json crypto README.md jest.config.js package-lock.json package.json ts IncrementalQuinTree.ts __tests__ Crypto.test.ts IncrementalMerkleTree.test.ts IncrementalQuinTree.test.ts index.ts tsconfig.json domainobjs README.md jest.config.js package-lock.json package.json ts __tests__ DomainObjs.test.ts index.ts tsconfig.json integrationTests README.md jest.config.js package-lock.json package.json scripts runTestsInCircleCi.sh ts __tests__ cli-create.test.ts cli-genMaciKeypair.test.ts cli-genMaciPubkey.test.ts cli-processTallyVerify.test.ts cli-signupAndPublish.test.ts params.ts suites.test.ts suites.ts suites suite0_happy.json suite1_small.json suite2_bribe.json utils.ts tsconfig.json lerna.json package-lock.json package.json specs 01_introduction.md 02_contract.md 03_circuits.md 04_state_root_transition_circuit.md 05_quadratic_vote_tallying_circuit.md faq.md package-lock.json package.json tsconfig.json README.md FileNetwork ipfsExternalAdapter README.md app.js file_uploads patrick.json index.js package.json test index_test.js response.json test.json GraphNetwork contracts external contracts package.json LegalNetwork contracts OpenCourt README.md build contracts Migrations.json external contracts package.json migrations 1_initial_migration.js truffle-config.js web-apps package-lock.json package.json src index.html OracleNetwork contracts external contracts package.json migrations 1_initial_migration.js package-lock.json package.json truffle-config.js PolygonNetwork .eslintrc.js .soliumrc.json README.md contracts external contracts package.json package-lock.json package.json scripts eventSignatures.js process-templates.js run-test.sh stake.js wallet.js truffle-config.js README.md TradeNetwork contracts external contracts package.json YieldNetwork contracts external contracts package.json migrations 1_initial_migration.js truffle-config.js YixxNet .solcover.js README.md coverage.json hardhat.config.js package-lock.json package.json scripts arguments.js deploy_ALC.js deploy_Alchemy.js deploy_alchemy_governor.js deploy_alchemy_timelock.js deploy_router.js deploy_stakingpool.js verify.js test test_alchemy_functions.js test_alchemy_functions_init_multiple.js test_array_add.js test_array_addtransfer.js test_custom_call.js test_nft_addandtransfer.js test_nft_buyout.js test_nft_buyout_with_before_single_nft_buy.js test_return_owner_function.js
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `yarn start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `yarn test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `yarn build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `yarn eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `yarn build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) # NearBridge TruffleFramework template with travis-ci.org and coveralls.io configured [![Build Status](https://travis-ci.org/nearprotocol/bridge.svg?branch=master)](https://travis-ci.org/nearprotocol/bridge) [![Coverage Status](https://coveralls.io/repos/github/nearprotocol/bridge/badge.svg?branch=master)](https://coveralls.io/github/nearprotocol/bridge?branch=master) # `maci-contracts` This submodule contains all the Ethereum contracts and tests for MACI. # Rainbow Bridge This documentation is about design, usage, maintenance, and testing of the NEAR-ETH bridge. * [Overview of the components](./components.md) * [Standard workflows](./workflows/README.md) * [Transferring Ethereum ERC20 to Near](./workflows/eth2near-fun-transfer.md) To see the explanation of each individual CLI please use `--help`. # maci-domainobjs This module implements domain objects. A domain object is: > a logical container of purely domain information, usually represents a > logical entity in the problem domain space https://wiki.c2.com/?DomainObject In effect, domain objects are representations of objects shared between other modules in this codebase. They also encapsulate helper functions which make it easy to use them with said modules. ## `Command` The `Command` domain object represents a request by a user to cast a vote and/or change one's public key. ## `Message` The `Message` domain object is an encrypted `Command` and signature. That is, a `Message` is a `Ciphertext` (defined in [`maci-crypto`](../crypto/README.md)) which is the encrypted `Command` and its `Signature` (also defined in `maci-crypto`). In other terms: ``` Message = Encrypt([Command, Signature], Key) ``` ## `VoteOptionTreeLeaf` ## `StateLeaf` # Semaphore Semaphore is a zero-knowledge gadget which allows users to prove their membership of a set without revealing their original identity. At the same time, it allows users to signal their endorsement of an arbitrary string. It is designed to be a simple and generic privacy layer for Ethereum dApps. Use cases include private voting, whistleblowing, mixers, and anonymous authentication. For more information, refer to the [documentation](https://appliedzkp.github.io/semaphore/). Join the [Telegram group](https://t.me/joinchat/B-PQx1U3GtAh--Z4Fwo56A) to discuss. # maci-cli ## Subcommands | Role | Action | Subcommand | |-|-|-| | User | Generate MACI keypair | `genMaciKeypair` | | User | Generate MACI public key | `genMaciPubkey` | | Coordinator | Create election | `create `| | User | Sign up | `signup` | | User | Change key / vote | `publish` | | Coordinator | Process one batch or all remaining batches of messages | `process` | | Coordinator | Tally one batch or all remaining batches of state leaves | `tally` | ## Public and private key format MACI uses private keys in the BabyJub field for operations which occur within zk-SNARKs, such as decrypting messages or signing commands. As MACI is deployed on Ethereum, we seek to avoid confusing BabyJub private keys with Ethereum private keys. To that end, users should pass serialized formats of public and private keys to this CLI. We use `maci-domainobj`'s `PrivKey.serialize` and `PubKey.serialize` functions to do so. Examples of serialized public and private keys: ``` Private key: macisk.2422e5e9b8eb7c3ca5865168bf52480bb90b44df50070881c99a4e4f0d79a815 Public key: macipk.9643c94d5a2c918cab49a476feeab82eeec61ead9625e901c340c71aecdeb282 ``` ### Coordinator: Create election This command deploys an instance of a MACI contract. Note that all the example commands default to a local Ethereum testnet at `http://localhost:8545`. For testing purposes, you can run one using: ```bash # in maci/contracts npm run ganache ``` Fields that the coordinator has to set: `node build/index.js create <options>` Example usage: ``` $ node build/index.js create -sk macisk.23d007423d56475d7e39dcd5053c5aa98f57a69ee85bc7813ccbf4c5e688307 -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 -u 15 -m 15 ``` Example output: ``` MACI: 0xE28158eCFde143e2536761c3254C7C31efd97271 ``` | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to an Ethereum provider. Default: `http://localhost:8545` | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the coordinator to input their MACI private key | | Deployer's Ethereum private key | `-d` or `--deployer-privkey` | A private key of the Ethereum account to use to deploy the MACI contract | | Prompt for the deployer's Ethereum private key | `-dp` or `--prompt-for-deployer-privkey` | If specified, ignores `-d / --deployer-privkey` and prompts the coordinator to input their Ethereum private key | | Maximum number of users | `-u` or `--max-users` | Default: 15 | | Maximum number of messages | `-m` or `--max-messages` | Default: 15 | | Maximum number of vote options | `-v` or `--max-vote-options` | Default: 25 | | Sign-up duration | `-s` or `--signup-duration` | The sign-up duration, in seconds. Default: 3600. | | Voting duration | `-o` or `--voting-duration` | The voting duration, in seconds. Default: 3600. | | Initial voice credits | `-c` or `--initial-voice-credits` | Default: 100 | | Initial voice credit proxy contract | `-i` or `--initial-vc-proxy` | If specified, deploys the MACI contract with this address as the initial voice credit proxy constructor argument. Otherwise, deploys a ConstantInitialVoiceCreditProxy contract with the above-specified value. | | Signup gatekeeper contract | `-g` or `--signup-gatekeeper` | If specified, deploys the MACI contract with this address as the signup gatekeeper constructor argument. Otherwise, deploys a gatekeeper contract which allows any address to sign up. | | Batch size for processing messages | `-bm` or `--message-batch-size` | Default: 4 | | Batch size for tallying votes | `-bv` or `--tally-batch-size` | Default: 4 | ### Coordinator: Process, tally and verify outcome These three commands share the same option flags. `node build/index.js process <options>` `node build/index.js tally <options>` `node build/index.js verify <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | See above | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform the transaction | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | As message processing and vote tallying occurs in batches, this command should automatically resume a job halfway done. ### User: Generate MACI keypair `node build/index.js genMaciKeypair <options>` The output of this command is a serialised private key and serialised public key. ### User: Generate MACI public key `node build/index.js genMaciPubkey <options>` | Option | Flags | About | |-|-|-| | Private key | `-sk` or `--privKey` | A serialised private key | The output of this command is a serialised public key derived from the given private key. ### User: Sign up `node build/index.js signup <options>` Fields that the user has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | The user's MACI public key | `-p` or `--pubkey` | This should not be an Ethereum public key. Instead, it should be the user's serialised BabyJub public key (where the x and y values have been concatenated. | | User's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to sign up | | Prompt for the user's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the user to input their Ethereum private key | | Signup gatekeeper proxy data | `-s` or `--sg-data` | A hex string to pass to the sign-up gatekeeper proxy contract which may use it to determine whether to allow the user to sign up. Default: an empty bytestring. | | Initial voice credit proxy data | `-v` or `--ivcp-data` | A hex string to pass to the initial voice credit proxy contract which may use it to determine how many voice credits to assign to the user. Default: an empty bytestring. | ### User: Change key / vote `node build/index.js publish <options>` Fields that the user has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | The user's MACI private key | `-sk` or `--pubkey` | This should not be an Ethereum private key | | Prompt for the user's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input thier MACI private key | | User's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform the transaction | | Prompt for the user's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the user to input their Ethereum private key | | State index | `-i` or `--state-index` | The state index of the user | | The user's new or current MACI public key | `-p` or `--pubkey` | This should be a serialised BabyJub public key which should replace the user\'s public key in the state tree if the command is valid| | Vote option index | `-v` or `--vote-option-index` | The index of the option to vote for | | New vote weight | `-w` or `--new-vote-weight` | The vote weight to assign to said vote option | | Nonce | `-n` or `--nonce` | The nonce of the message | | Salt | `-s` or `--salt` | The salt of the message. If unspecified, this command will randomly generate a salt | ### Coordinator: Process messages `NODE_OPTIONS=--max-old-space-size=4096 node build/index.js process <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input the coordinator's MACI private key | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform transactions | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | | Repeat until all messages have been processed | `-r` or `--repeat` | Default: false | ### Coordinator: Tally votes `NODE_OPTIONS=--max-old-space-size=4096 node build/index.js tally <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input the coordinator's MACI private key | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform transactions | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | | Repeat until all votes have been processed | `-r` or `--repeat` | Default: false | | The serialised state leaf preimage at index 0 | `-z` or `--leaf-zero` | | | The current results salt | `-c` or `--current-results-salt` | The secret salt which is hashed along with the current results to produce the current result commitment input to the snark. | | The current total voice credits salt | `-tvc` or `--current-total-vc-salt` | The secret salt which is hashed along with the current total number of spent voice credits to produce the current total voice credits commitment input to the snark. | | The current per vote option voice credits salt | `-pvc` or `--current-per-vo-vc-salt` | The secret salt which is hashed along with the current total number of spent voice credits per vote option to produce the current total voice credits commitment input to the snark. | | The final tally file | `-t` or `--tally-file` | A filepath in which to save the final vote tally and salt. | ### Anyone: Verify a vote tally `node build/index.js verify <options>` Fields to set: | Option | Flags | About | |-|-|-| | The final tally file | `-t` or `--tally-file` | The final tally file created by the `tally` subcommand. | ## Demonstration This section contains a sequence of commands which will be useful for a live demonstration. They simulate the following scenario: 1. Eve tries to bribe Alice to vote for Party B 1. Alice votes for Party B (`m0`) 2. Alice changes her key (`m1`) 4. Alice submits a vote for Party A (`m2`) 5. The coordinator processes the votes and computes the final tally 6. The expected result is: Party A has 1 vote and Party B has 0 votes. Alice’s invalid vote was not counted, and Eve had no way to tell. Note that since messages are processed in reverse order, message `m0` will be rendered invalid by `m1`. **Coordinator: create keypair** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c Public key: macipk.4ba3aa2718d5e3741aa643217722cf4a480854dfae544837d4af332f0c2b4586 Please store your private key in a safe place and do not reveal it to anyone. ``` **Alice: create keypair** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 Public key: macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 Please store your private key in a safe place and do not reveal it to anyone. ``` **Coordinator: create election** ``` node ./build/index.js create -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -e http://localhost:8545 \ -s 15 \ -o 60 \ -bm 4 \ -bv 4 ``` Example output: ``` MACI: 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` **Alice: sign up** ``` node ./build/index.js signup -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` Example output: ``` Transaction hash: 0x3cd2e6e805b54a6dfaff840dcf496092447400a1b26ba9f3c31bd78c3fe15723 State index: 1 ``` **Alice: vote for party B** ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 1 \ -w 9 \ -n 1 ``` Example output: ``` Transaction hash: 0xc52ff70c3bbcc91457fd61738cd00d09d8bac96c56094910e275e474132ff741 Ephemeral private key: macisk.1e3233eec8d0ccf722f2576ba5cb1b361939f0617ac3583a3eb025e4944b0e40 ``` **Alice: create new key** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.ff3ae0e7855e4c62237e2b7c72de109865f087bd5f792cf4589d3cdc495d8f2 Public key: macipk.15fe02285ad8573d7dca877420a22ea1b55abf47dce6b6d59127b49f67131e0d Please store your private key in a safe place and do not reveal it to anyone. ``` **Alice: change key** ```sh node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.15fe02285ad8573d7dca877420a22ea1b55abf47dce6b6d59127b49f67131e0d \ -i 1 \ -v 0 \ -w 9 \ -n 1 ``` Example output: ``` Transaction hash: 0x812dc6345e2515bced4f15e7ca3842d3d343c22f6729fe3216b946fa97bffc1e Ephemeral private key: macisk.24115d8d585b7dd8f7ea1975668b3d4f34dcf8b1bcc6617bdefbed7e41b89846 ``` **Alice: vote for party A** ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.ff3ae0e7855e4c62237e2b7c72de109865f087bd5f792cf4589d3cdc495d8f2 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 1 \ -w 9 \ -n 2 ``` Example output: ``` Transaction hash: 0x45ae379b056a6fc647a3718bd356268a1bcda35e6645bb7a1aba44cb76418c98 Ephemeral private key: macisk.2b23e978301d029e46117ef0138f860e277ffed0f008712f3d7ca2c40f1a6768 ``` **Coordinator: process all messages** ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js process \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r ``` Example output: ``` Processed batch starting at index 0 Transaction hash: 0xbd1bbe86cd4fc72f34911220db428751e8a483b3afcc9d30c1a15989a7b6a031 Random state leaf: <RANDOM STATE LEAF> ``` **Coordinator: tally all votes** ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js tally \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r \ -c 0x0 \ -tvc 0x0 \ -pvc 0x0 \ -t tally.json \ -z <PASTE RANDOM STATE LEAF HERE> ``` Example output: ``` Transaction hash: 0x9ef0ab94d534650445c4ff748a43eacdedff1602929bd6a1bd568573374ddca2 Current results salt: 0xa54b75db545fcda278ce882cae90d069c6fcf81368778264550d9b66af05a42 Result commitment: 0x25deb6f675ed4f08742e1776eee130c627d168106fd813627963b241c1ba0754 ``` The file `tally.json` will now contain something like the following: ```json { "provider": "http://localhost:8545", "maci": "0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4", "results": { "commitment": "0x1cd0ec2789abceb908b06f6a74c26a848e209011ec41b3e5028bb7aeff2bdeb2", "tally": [ "9", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ], "salt": "0x2d7f1744185507a529fdb32dec920bfdaf825b0fdba5b66661a40a71beac3b46" }, "totalVoiceCredits": { "spent": "81", "commitment": "0x2d55a42ec1da99227125cf9562aa91aad12e2f1387ccf3411da79b0a953d69a6", "salt": "0xfc95a102f3c66d92d7a5700f1e12a6f2325c54a10efa0e1178cc21b67f0d97c" }, "totalVoiceCreditsPerVoteOption": { "commitment": "0x18526f481cf2476543c8dcc3762f3a54af8e217d3d048810856623367ef4ba14", "tally": [ "81", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ], "salt": "0x1f17d2ff16b9791ef4b1849bfccf420b9fece161e419ad4f8b1ef726c62e3943" } } ``` Anyone can now run `verify` to check if the tally is correct: ```bash node build/index.js verify -t tally.json ``` Example output: ``` The results commitment in the specified file is correct given the tally and salt The total spent voice credit commitment in the specified file is correct given the tally and salt The per vote option spent voice credit commitment in the specified file is correct given the tally and salt The results commitment in the MACI contract on-chain is valid The total spent voice credit commitment in the MACI contract on-chain is valid The per vote option spent voice credit commitment in the MACI contract on-chain is valid The total sum of votes in the MACI contract on-chain is valid. ``` ## Demonstration with `prod-small` settings Create a MACI instance: ```bash node ./build/index.js create -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -e http://localhost:8545 \ -s 15 \ -o 60 \ -bm 4 \ -bv 4 \ -u 255 \ -m 2048 ``` Sign up: ``` node ./build/index.js signup -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` Vote: ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 0 \ -w 9 \ -n 1 ``` Process all messages: ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js process \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r ``` Tally all votes: ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js tally \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r \ -c 0x0 \ -tvc 0x0 \ -pvc 0x0 \ -t tally.json \ -z <PASTE RANDOM STATE LEAF HERE> ``` # Minimal Anti-Collusion Infrastructure Please refer to the [implementation spec](./specs/) for technical details, and the original [ethresear.ch post](https://ethresear.ch/t/minimal-anti-collusion-infrastructure/5413) for a high-level view. We welcome contributions to this project. Please join our [Telegram group](https://t.me/joinchat/LUgOpE7J2gstRcZqdERyvw) to discuss. ## Local development and testing ### Requirements You should have Node 12 installed. Use [`nvm`](https://github.com/nvm-sh/nvm) to install it. ### Get started Clone this repository, install NodeJS dependencies, and build the source code: ```bash git clone [email protected]:appliedzkp/maci.git && \ npm i && \ npm run bootstrap && \ npm run build ``` For development purposes, you can generate the proving and verifying keys for the zk-SNARK circuits, along with their Solidity verifier contracts as such. Install Rust: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` Also install [`zkutil`](https://github.com/poma/zkutil) v0.3.2 and ensure that the `zkutil` binary is in the `~/.cargo/bin/` directory. You can [configure](https://lorenwest.github.io/node-config/) the path to this binary via `maci-config` (see `config/test.yaml` for an example). ```bash cargo install zkutil --version 0.3.2 && zkutil --help ``` Build the zk-SNARKs and generate their proving and verifying keys: ```bash cd circuits npm run buildBatchUpdateStateTreeSnark npm run buildQuadVoteTallySnark ``` This should take no more than 5 minutes. We used to provide download links to working versions of the keys and compiiled circuit files, but now that we can use `snarkjs` to produce them very quickly, we no longer maintain them. Note that if you change the circuits and recompile them, you should also update and recompile the verifier contracts in `contracts/sol` with their new versions, or the tests will fail: ```bash cd contracts npm run compileSol ``` ### Demo You can use the MACI command-line interface to run a demo. See: https://github.com/appliedzkp/maci/tree/master/cli#demonstration ### Local development This repository is organised as Lerna submodules. Each submodule contains its own unit tests. - `config`: project-wide configuration files. Includes config files for both testing and production. - `crypto`: low-level cryptographic operations. - `circuits`: zk-SNARK circuits. - `contracts`: Solidity contracts and deployment code. - `domainobjs`: Classes which represent high-level [domain objects](https://wiki.c2.com/?DomainObject) particular to this project. - `core`: Business logic functions for message processing, vote tallying, and circuit input generation through `MaciState`, a state machine abstraction. - `cli`: A command-line interface with which one can deploy and interact with an instance of MACI. - `integrationTests`: Integration tests which use the command-line interface to perform end-to-end tests. ### Testing #### Unit tests The following submodules contain unit tests: `core`, `crypto`, `circuits`, `contracts`, and `domainobjs`. Except for the `contracts` submodule, run unit tests as such (the following example is for `crypto`): ```bash cd crypto npm run test ``` For `contracts` and `integrationTests`, run the tests one by one. This prevents incorrect nonce errors. First, start a Ganache instance in a separate terminal: ```bash cd contracts npm run ganache ``` In another terminal, run the tests individually: ```bash cd contracts ./scripts/runTestsInCircleCi.sh ``` or ```bash cd integrationTests ./scripts/runTestsInCircleCi.sh ``` You can ignore the Ganache errors which this script emits as you should already have Ganache running in a separate terminal. Otherwise, you will have to exit Ganache using the `kill` command. # SuffrageNet Computational Integrity Information Architecture for Electronic Voting using Zero Knowledge Proof Frameworks. ## Inspiration Concept of Quadratic Voting and how it can help to address the voice of minorities. Quadratic voting is a collective decision-making procedure where individuals allocate votes to express the degree of their preferences, rather than just the direction of their preferences. By doing so, quadratic voting helps enable users to address issues of voting paradox and majority rule. Following privacy preserving computational integrity information architectures are also inspirations. - Minimal Anti Collusion Infrastructure from Applied ZKP - Semaphore Signaling Framework from Applied ZKP ## What it does - Generates a prover - verifier infrastructure for constructing the proofs of minority votes. - Generated privacy preserving vote infrastructure using Zero Knowledge Proofs - Ability to execute Quadratic Voting Algorithms to make sure minority voices are addressed ## How I built it - Circom Circuit Compiler generated computational integrity proofs - Proofs are generated in Web Assembly. Proofs are translated to Solidity Smart Contracts. ## Challenges I ran into - Compilation of Semaphore Smart Contracts. ## Accomplishments that I'm proud of - Integration of Semaphore Framework into Electronic Voting - Identification of Quadratic Voting Concept for Minority Voting ## What I learned - Power of Zero Knowledge Proofs - Power of Semaphore Signaling Framework - Power of Quadratic Voting Concept ## What's next for SuffrageNet - Deployment into Matic Network - Development of a Wallet - Development of a Dashboard # `maci-contracts` This submodule contains all the Ethereum contracts and tests for MACI. # maci-integrationTests This submodule contains test suites that span between different submodules. The current approach that it takes is to test each CLI command and also chain them together. # Arbitration Network with Anti Collusion and Anti Corruption Computational Integrity Information Architecture for Electronic Voting using Zero Knowledge Proof Frameworks. ## Inspiration Concept of Quadratic Voting and how it can help to address the voice of minorities. Quadratic voting is a collective decision-making procedure where individuals allocate votes to express the degree of their preferences, rather than just the direction of their preferences. By doing so, quadratic voting helps enable users to address issues of voting paradox and majority rule. Following privacy preserving computational integrity information architectures are also inspirations. - Minimal Anti Collusion Infrastructure from Applied ZKP - Semaphore Signaling Framework from Applied ZKP ## What it does - Generates a prover - verifier infrastructure for constructing the proofs of minority votes. - Generated privacy preserving vote infrastructure using Zero Knowledge Proofs - Ability to execute Quadratic Voting Algorithms to make sure minority voices are addressed ## How I built it - Circom Circuit Compiler generated computational integrity proofs - Proofs are generated in Web Assembly. Proofs are translated to Solidity Smart Contracts. ## Challenges I ran into - Compilation of Semaphore Smart Contracts. ## Accomplishments that I'm proud of - Integration of Semaphore Framework into Electronic Voting - Identification of Quadratic Voting Concept for Minority Voting ## What I learned - Power of Zero Knowledge Proofs - Power of Semaphore Signaling Framework - Power of Quadratic Voting Concept ## What's next for SuffrageNet - Deployment into Matic Network - Development of a Wallet - Development of a Dashboard # MACI Circuits ## About Poseidon Hash Functions We use the Poseidon hash function implementation found in `circomlib` v0.2.4 and newer. Information about this implementation is available here: https://github.com/iden3/circomlib/pull/47 Before 27 August 2020, we used an custom-tailored implementation (credits to Chih-Cheng Liang) where we set non-default parameters (`t`, `roundFull`, and `roundPartial`). ## Information about the custom-tailored implementation (deprecated) We use the [Poseidon hash function](https://eprint.iacr.org/2019/458.pdf) which is a snark-friendly hash function. **Note (7 Aug 2020) This code has not been audited. We do not recommend copy-pasting the `circom` implementations in this folder before it is reviewed. Please get in touch if you have or wish to use it.** Poseidon hash functions need to be parameterized for the number of inputs. If the input has `n` field elements, the parameter `t` would be `n + 1`, for security reasons (see below). We have these hash functions defined: | Poseidon t | number of elements | Use cases | | ---------- | -----------------: | ------------------------------------ | | t = 3 | 2 | Build Merkle tree with HashLeftRight | | t = 6 | 5 | Hash stateLeaf | The Message has 11 elements and we hash it with a Hasher11, which is a combination of t3 and t6. ### Why `t := n+1`? Here's a quote from the poseidon-hash [website](https://www.poseidon-hash.info/). Notations are changed to the same with our context. > ..., you determine the width `t`, measured in the number of F elements, of > Poseidon permutation as follows: > - Reserve `c` elements for capacity so that `c` elements of F contain `2M` or more bits. > - If messages have fixed length `n` which is reasonably small (10 or less), then set `t = c+n`. We target 128 bits of security (`M=128`) and use BN128, aka BN254, curve in circom. A BN128 field element has roughly 256 bits, so we reserve only one element (`c=1`) to contain `2M` (2 \* 128 = 256) bits. That's why if a input has length `n` then use `t = 1 + n` ### About Poseidon Parameters The behavior of Poseidon hash function is determined by 4 parameters, `t`, `roundFull`, `roundPartial`, and `seed`. We discussed above how to choose `t`. We set `seed` to the string `poseidon`, which is the same as the one in circomlib. `roundFull` and `roundPartial` are generated by a [script](https://github.com/ChihChengLiang/misc_crypto/blob/master/misc_crypto/poseidon/parameter_finder.py) which finds smallest possible values which are safe from statistical and algebraic attacks. # maci-domainobjs This module implements domain objects. A domain object is: > a logical container of purely domain information, usually represents a > logical entity in the problem domain space https://wiki.c2.com/?DomainObject In effect, domain objects are representations of objects shared between other modules in this codebase. They also encapsulate helper functions which make it easy to use them with said modules. ## `Command` The `Command` domain object represents a request by a user to cast a vote and/or change one's public key. ## `Message` The `Message` domain object is an encrypted `Command` and signature. That is, a `Message` is a `Ciphertext` (defined in [`maci-crypto`](../crypto/README.md)) which is the encrypted `Command` and its `Signature` (also defined in `maci-crypto`). In other terms: ``` Message = Encrypt([Command, Signature], Key) ``` ## `VoteOptionTreeLeaf` ## `StateLeaf` # MACI Circuits ## About Poseidon Hash Functions We use the Poseidon hash function implementation found in `circomlib` v0.2.4 and newer. Information about this implementation is available here: https://github.com/iden3/circomlib/pull/47 Before 27 August 2020, we used an custom-tailored implementation (credits to Chih-Cheng Liang) where we set non-default parameters (`t`, `roundFull`, and `roundPartial`). ## Information about the custom-tailored implementation (deprecated) We use the [Poseidon hash function](https://eprint.iacr.org/2019/458.pdf) which is a snark-friendly hash function. **Note (7 Aug 2020) This code has not been audited. We do not recommend copy-pasting the `circom` implementations in this folder before it is reviewed. Please get in touch if you have or wish to use it.** Poseidon hash functions need to be parameterized for the number of inputs. If the input has `n` field elements, the parameter `t` would be `n + 1`, for security reasons (see below). We have these hash functions defined: | Poseidon t | number of elements | Use cases | | ---------- | -----------------: | ------------------------------------ | | t = 3 | 2 | Build Merkle tree with HashLeftRight | | t = 6 | 5 | Hash stateLeaf | The Message has 11 elements and we hash it with a Hasher11, which is a combination of t3 and t6. ### Why `t := n+1`? Here's a quote from the poseidon-hash [website](https://www.poseidon-hash.info/). Notations are changed to the same with our context. > ..., you determine the width `t`, measured in the number of F elements, of > Poseidon permutation as follows: > - Reserve `c` elements for capacity so that `c` elements of F contain `2M` or more bits. > - If messages have fixed length `n` which is reasonably small (10 or less), then set `t = c+n`. We target 128 bits of security (`M=128`) and use BN128, aka BN254, curve in circom. A BN128 field element has roughly 256 bits, so we reserve only one element (`c=1`) to contain `2M` (2 \* 128 = 256) bits. That's why if a input has length `n` then use `t = 1 + n` ### About Poseidon Parameters The behavior of Poseidon hash function is determined by 4 parameters, `t`, `roundFull`, `roundPartial`, and `seed`. We discussed above how to choose `t`. We set `seed` to the string `poseidon`, which is the same as the one in circomlib. `roundFull` and `roundPartial` are generated by a [script](https://github.com/ChihChengLiang/misc_crypto/blob/master/misc_crypto/poseidon/parameter_finder.py) which finds smallest possible values which are safe from statistical and algebraic attacks. # Siddhi Secure Skill Streaming Social Token Network - Self Organized and Self Stablized Skill Streaming Protocol on Matic Network ## Introduction SiddhiNet is a Secure Streaming Network for Social Token Distribution for Skilled Professionals within Self Organized Networks. Skills are defined as Self Soverign Social Tokens. Privacy Preserving Proofs are constructed using Zokrates Toolkit for Skill Self Verification, Sequence Verification and Summary Verification. Skill Social Tokens are generated as ERC 721. Skill Session Tokens are generated from Chainlink VRF. Skill Selection Oracles are also constructed from ChainLink VRF. Skill Streams are constructed from ERC 1620 Specifications. Skill Social Tokens are anonymized on Zether Framework. ## MATIC TestNet - SiddhiCoin >> https://explorer-mumbai.maticvigil.com/tx/0x3ee879cbde3fe03c9a026344a6e0ebc32efc4eb51f8ea8a2398f53705a858d78/ - SiddihiStream >> https://mumbai-explorer.matic.today/tx/0xa7b35dd2dd3bf34d40040a84486c941c717d496897f57cdc1a6560c0a9da2686/ ## BSC TestNet - SiddhiCoin >> https://testnet.bscscan.com/tx/0xd898b49ea6b1e95aee205ac8560b4be45db0028c5778f0e65b645f004e5e98d8 - SiddhiStream >> https://testnet.bscscan.com/tx/0x3dc97c2498384522c0e82a97f73d891599fdb0cc9d6f4a8b7d14b6c7a772d8fe ## Features - Skill Self Verification through Privcy Preserving Zokrates Contracts - Skill Summary Verification through Privacy Preserving Zokrates Contracts - Skill Sequence Verification through Privacy Preserving Zokrates Contracts - Skill Social Verification through Minimal Anti Collusion Framework - Skill Streaming with Time Locked Pause and Freeze Facilities - Skill Token Distribution over Money Streaming Protocol - Skill Token Supply Expansion and Contraction on Bonding Curves - Skill Streaming based on Multi Dimensional Time Locks - Skill Token Integration with Anonymous Zether Framework - Multi Dimensional Time Locks using Verifiable Delay Functions - Privacy Preserving Confidential Skill Share and Yield Tokens ## Roadmap - Optimistic Rollup based Dispute and Fraud Control - Stationary Time Average Functions using Verifible Delay Functions - Zero Knowldge Rollups for Skill Exchange on the Layer 2 DEXs - Zero Knowldge Proofs for Minimal Anti Collusion in Skill Selection # Semaphore Semaphore is a zero-knowledge gadget which allows users to prove their membership of a set without revealing their original identity. At the same time, it allows users to signal their endorsement of an arbitrary string. It is designed to be a simple and generic privacy layer for Ethereum dApps. Use cases include private voting, whistleblowing, mixers, and anonymous authentication. For more information, refer to the [documentation](https://appliedzkp.github.io/semaphore/). Join the [Telegram group](https://t.me/joinchat/B-PQx1U3GtAh--Z4Fwo56A) to discuss. # Chainlink NodeJS IPFS External Adapter Send and get data from your IPFS node. ## Creating your own adapter from this template Clone this repo and change "ExternalAdapterProject" below to the name of your project ```bash git clone https://github.com/PatrickAlphaC/ipfs_cl_ea ``` Enter into the newly-created directory See [Install Locally](#install-locally) for a quickstart ## Input Params This is currently a work in progress, and supports some of the [IPFS HTTP parameters.](https://docs.ipfs.io/reference/http/api/) PRs are welcome :) - `endpoint`: The endpoint to use from the IPFS API - `ipfs_host`: The Base URL of you IPFS host - `starting_char`: Which character to start at for returning the string Parameters from the IPFS API: ``` quiet: false, quieter: false, silent: false, progress: false, trickle: false, pin: false, file: false, // The location of the file you want to upload arg: false ``` ## Example input ``` curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": {"file":"./test/test.json"}}' ``` ## Output ```json { "jobRunID":0, "data":{ "Name":"test.json", "Hash":"Qmd3zUksep8MQnjeSsXgEE4xa2DKgw48HJPjk5BiMDn1u7", "Size":"24", "result":"Qmd3zUksep8MQnjeSsXgEE4xa2DKgw48HJPjk5BiMDn1u7" }, "result":"Qmd3zUksep8MQnjeSsXgEE4xa2DKgw48HJPjk5BiMDn1u7", "statusCode":200 } ``` or ## Example input ```bash curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": {"endpoint":"api/v0/cat", "arg":"Qmd3zUksep8MQnjeSsXgEE4xa2DKgw48HJPjk5BiMDn1u7"}}' ``` ## Output ```json {"jobRunID":0,"data":{"cat":"dog"},"statusCode":200} ``` ## Example Input ```bash curl -X POST -H "content-type:application/json" "http://localhost--data '{ "id": 0, "data": {"text_for_file_name":"patrick.json", "text_for_file":"[\"dog\"]"}}' ``` ## Output ```json {"jobRunID":0,"data":{"Name":"patrick.json","Hash":"QmWk8NQVeoXyMizcxT3D2y85eFDQGQfmRvupCnni3nuS1q","Size":"15","result":"QmWk8NQVeoXyMizcxT3D2y85eFDQGQfmRvupCnni3nuS1q"},"result":"QmWk8NQVeoXyMizcxT3D2y85eFDQGQfmRvupCnni3nuS1q","statusCode":200} ``` ## Install Locally Install dependencies: ```bash yarn ``` ### Test Run the local tests: ```bash yarn test ``` Natively run the application (defaults to port 8080): ### Run ```bash yarn start ``` ## Call the external adapter/API server ```bash curl -X POST -H "content-type:application/json" "http://localhost:8080/" --data '{ "id": 0, "data": {"file":"./test/test.json"}}' ``` ## Docker If you wish to use Docker to run the adapter, you can build the image by running the following command: ```bash docker build . -t external-adapter ``` Then run it with: ```bash docker run -p 8080:8080 -it external-adapter:latest ``` ## Serverless hosts After [installing locally](#install-locally): ### Create the zip ```bash zip -r external-adapter.zip . ``` ### Install to AWS Lambda - In Lambda Functions, create function - On the Create function page: - Give the function a name - Use Node.js 12.x for the runtime - Choose an existing role or create a new one - Click Create Function - Under Function code, select "Upload a .zip file" from the Code entry type drop-down - Click Upload and select the `external-adapter.zip` file - Handler: - index.handler for REST API Gateways - index.handlerv2 for HTTP API Gateways - Add the environment variable (repeat for all environment variables): - Key: API_KEY - Value: Your_API_key - Save #### To Set Up an API Gateway (HTTP API) If using a HTTP API Gateway, Lambda's built-in Test will fail, but you will be able to externally call the function successfully. - Click Add Trigger - Select API Gateway in Trigger configuration - Under API, click Create an API - Choose HTTP API - Select the security for the API - Click Add #### To Set Up an API Gateway (REST API) If using a REST API Gateway, you will need to disable the Lambda proxy integration for Lambda-based adapter to function. - Click Add Trigger - Select API Gateway in Trigger configuration - Under API, click Create an API - Choose REST API - Select the security for the API - Click Add - Click the API Gateway trigger - Click the name of the trigger (this is a link, a new window opens) - Click Integration Request - Uncheck Use Lamba Proxy integration - Click OK on the two dialogs - Return to your function - Remove the API Gateway and Save - Click Add Trigger and use the same API Gateway - Select the deployment stage and security - Click Add ### Install to GCP - In Functions, create a new function, choose to ZIP upload - Click Browse and select the `external-adapter.zip` file - Select a Storage Bucket to keep the zip in - Function to execute: gcpservice - Click More, Add variable (repeat for all environment variables) - NAME: API_KEY - VALUE: Your_API_key # maci-cli ## Subcommands | Role | Action | Subcommand | |-|-|-| | User | Generate MACI keypair | `genMaciKeypair` | | User | Generate MACI public key | `genMaciPubkey` | | Coordinator | Create election | `create `| | User | Sign up | `signup` | | User | Change key / vote | `publish` | | Coordinator | Process one batch or all remaining batches of messages | `process` | | Coordinator | Tally one batch or all remaining batches of state leaves | `tally` | ## Public and private key format MACI uses private keys in the BabyJub field for operations which occur within zk-SNARKs, such as decrypting messages or signing commands. As MACI is deployed on Ethereum, we seek to avoid confusing BabyJub private keys with Ethereum private keys. To that end, users should pass serialized formats of public and private keys to this CLI. We use `maci-domainobj`'s `PrivKey.serialize` and `PubKey.serialize` functions to do so. Examples of serialized public and private keys: ``` Private key: macisk.2422e5e9b8eb7c3ca5865168bf52480bb90b44df50070881c99a4e4f0d79a815 Public key: macipk.9643c94d5a2c918cab49a476feeab82eeec61ead9625e901c340c71aecdeb282 ``` ### Coordinator: Create election This command deploys an instance of a MACI contract. Note that all the example commands default to a local Ethereum testnet at `http://localhost:8545`. For testing purposes, you can run one using: ```bash # in maci/contracts npm run ganache ``` Fields that the coordinator has to set: `node build/index.js create <options>` Example usage: ``` $ node build/index.js create -sk macisk.23d007423d56475d7e39dcd5053c5aa98f57a69ee85bc7813ccbf4c5e688307 -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 -u 15 -m 15 ``` Example output: ``` MACI: 0xE28158eCFde143e2536761c3254C7C31efd97271 ``` | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to an Ethereum provider. Default: `http://localhost:8545` | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the coordinator to input their MACI private key | | Deployer's Ethereum private key | `-d` or `--deployer-privkey` | A private key of the Ethereum account to use to deploy the MACI contract | | Prompt for the deployer's Ethereum private key | `-dp` or `--prompt-for-deployer-privkey` | If specified, ignores `-d / --deployer-privkey` and prompts the coordinator to input their Ethereum private key | | Maximum number of users | `-u` or `--max-users` | Default: 15 | | Maximum number of messages | `-m` or `--max-messages` | Default: 15 | | Maximum number of vote options | `-v` or `--max-vote-options` | Default: 25 | | Sign-up duration | `-s` or `--signup-duration` | The sign-up duration, in seconds. Default: 3600. | | Voting duration | `-o` or `--voting-duration` | The voting duration, in seconds. Default: 3600. | | Initial voice credits | `-c` or `--initial-voice-credits` | Default: 100 | | Initial voice credit proxy contract | `-i` or `--initial-vc-proxy` | If specified, deploys the MACI contract with this address as the initial voice credit proxy constructor argument. Otherwise, deploys a ConstantInitialVoiceCreditProxy contract with the above-specified value. | | Signup gatekeeper contract | `-g` or `--signup-gatekeeper` | If specified, deploys the MACI contract with this address as the signup gatekeeper constructor argument. Otherwise, deploys a gatekeeper contract which allows any address to sign up. | | Batch size for processing messages | `-bm` or `--message-batch-size` | Default: 4 | | Batch size for tallying votes | `-bv` or `--tally-batch-size` | Default: 4 | ### Coordinator: Process, tally and verify outcome These three commands share the same option flags. `node build/index.js process <options>` `node build/index.js tally <options>` `node build/index.js verify <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | See above | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform the transaction | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | As message processing and vote tallying occurs in batches, this command should automatically resume a job halfway done. ### User: Generate MACI keypair `node build/index.js genMaciKeypair <options>` The output of this command is a serialised private key and serialised public key. ### User: Generate MACI public key `node build/index.js genMaciPubkey <options>` | Option | Flags | About | |-|-|-| | Private key | `-sk` or `--privKey` | A serialised private key | The output of this command is a serialised public key derived from the given private key. ### User: Sign up `node build/index.js signup <options>` Fields that the user has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | The user's MACI public key | `-p` or `--pubkey` | This should not be an Ethereum public key. Instead, it should be the user's serialised BabyJub public key (where the x and y values have been concatenated. | | User's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to sign up | | Prompt for the user's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the user to input their Ethereum private key | | Signup gatekeeper proxy data | `-s` or `--sg-data` | A hex string to pass to the sign-up gatekeeper proxy contract which may use it to determine whether to allow the user to sign up. Default: an empty bytestring. | | Initial voice credit proxy data | `-v` or `--ivcp-data` | A hex string to pass to the initial voice credit proxy contract which may use it to determine how many voice credits to assign to the user. Default: an empty bytestring. | ### User: Change key / vote `node build/index.js publish <options>` Fields that the user has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | The user's MACI private key | `-sk` or `--pubkey` | This should not be an Ethereum private key | | Prompt for the user's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input thier MACI private key | | User's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform the transaction | | Prompt for the user's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the user to input their Ethereum private key | | State index | `-i` or `--state-index` | The state index of the user | | The user's new or current MACI public key | `-p` or `--pubkey` | This should be a serialised BabyJub public key which should replace the user\'s public key in the state tree if the command is valid| | Vote option index | `-v` or `--vote-option-index` | The index of the option to vote for | | New vote weight | `-w` or `--new-vote-weight` | The vote weight to assign to said vote option | | Nonce | `-n` or `--nonce` | The nonce of the message | | Salt | `-s` or `--salt` | The salt of the message. If unspecified, this command will randomly generate a salt | ### Coordinator: Process messages `NODE_OPTIONS=--max-old-space-size=4096 node build/index.js process <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input the coordinator's MACI private key | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform transactions | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | | Repeat until all messages have been processed | `-r` or `--repeat` | Default: false | ### Coordinator: Tally votes `NODE_OPTIONS=--max-old-space-size=4096 node build/index.js tally <options>` Fields that the coordinator has to set: | Option | Flags | About | |-|-|-| | Ethereum provider | `-e` or `--eth-provider` | A connection string to the Ethereum provider. Default: `http://localhost:8545` | | MACI contract address | `-x` or `--contract` | The address of the deployed MACI contract | | Coordinator's MACI private key | `-sk` or `--privkey` | A serialized MACI private key. This is *not* an Ethereum private key. Its big-endian value must be below the snark field size. | | Prompt for the coordinator's MACI private key | `-dsk` or `--prompt-for-maci-privkey` | If specified, ignores `-sk / --privkey` and prompts the user to input the coordinator's MACI private key | | Coordinator's Ethereum private key | `-d` or `--eth-privkey` | A private key of the Ethereum account to use to perform transactions | | Prompt for the coordinator's Ethereum private key | `-dp` or `--prompt-for-eth-privkey` | If specified, ignores `-d / --eth-privkey` and prompts the coordinator to input their Ethereum private key | | Repeat until all votes have been processed | `-r` or `--repeat` | Default: false | | The serialised state leaf preimage at index 0 | `-z` or `--leaf-zero` | | | The current results salt | `-c` or `--current-results-salt` | The secret salt which is hashed along with the current results to produce the current result commitment input to the snark. | | The current total voice credits salt | `-tvc` or `--current-total-vc-salt` | The secret salt which is hashed along with the current total number of spent voice credits to produce the current total voice credits commitment input to the snark. | | The current per vote option voice credits salt | `-pvc` or `--current-per-vo-vc-salt` | The secret salt which is hashed along with the current total number of spent voice credits per vote option to produce the current total voice credits commitment input to the snark. | | The final tally file | `-t` or `--tally-file` | A filepath in which to save the final vote tally and salt. | ### Anyone: Verify a vote tally `node build/index.js verify <options>` Fields to set: | Option | Flags | About | |-|-|-| | The final tally file | `-t` or `--tally-file` | The final tally file created by the `tally` subcommand. | ## Demonstration This section contains a sequence of commands which will be useful for a live demonstration. They simulate the following scenario: 1. Eve tries to bribe Alice to vote for Party B 1. Alice votes for Party B (`m0`) 2. Alice changes her key (`m1`) 4. Alice submits a vote for Party A (`m2`) 5. The coordinator processes the votes and computes the final tally 6. The expected result is: Party A has 1 vote and Party B has 0 votes. Alice’s invalid vote was not counted, and Eve had no way to tell. Note that since messages are processed in reverse order, message `m0` will be rendered invalid by `m1`. **Coordinator: create keypair** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c Public key: macipk.4ba3aa2718d5e3741aa643217722cf4a480854dfae544837d4af332f0c2b4586 Please store your private key in a safe place and do not reveal it to anyone. ``` **Alice: create keypair** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 Public key: macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 Please store your private key in a safe place and do not reveal it to anyone. ``` **Coordinator: create election** ``` node ./build/index.js create -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -e http://localhost:8545 \ -s 15 \ -o 60 \ -bm 4 \ -bv 4 ``` Example output: ``` MACI: 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` **Alice: sign up** ``` node ./build/index.js signup -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` Example output: ``` Transaction hash: 0x3cd2e6e805b54a6dfaff840dcf496092447400a1b26ba9f3c31bd78c3fe15723 State index: 1 ``` **Alice: vote for party B** ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 1 \ -w 9 \ -n 1 ``` Example output: ``` Transaction hash: 0xc52ff70c3bbcc91457fd61738cd00d09d8bac96c56094910e275e474132ff741 Ephemeral private key: macisk.1e3233eec8d0ccf722f2576ba5cb1b361939f0617ac3583a3eb025e4944b0e40 ``` **Alice: create new key** ``` node ./build/index.js genMaciKeypair ``` Example output: ``` Private key: macisk.ff3ae0e7855e4c62237e2b7c72de109865f087bd5f792cf4589d3cdc495d8f2 Public key: macipk.15fe02285ad8573d7dca877420a22ea1b55abf47dce6b6d59127b49f67131e0d Please store your private key in a safe place and do not reveal it to anyone. ``` **Alice: change key** ```sh node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.15fe02285ad8573d7dca877420a22ea1b55abf47dce6b6d59127b49f67131e0d \ -i 1 \ -v 0 \ -w 9 \ -n 1 ``` Example output: ``` Transaction hash: 0x812dc6345e2515bced4f15e7ca3842d3d343c22f6729fe3216b946fa97bffc1e Ephemeral private key: macisk.24115d8d585b7dd8f7ea1975668b3d4f34dcf8b1bcc6617bdefbed7e41b89846 ``` **Alice: vote for party A** ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.ff3ae0e7855e4c62237e2b7c72de109865f087bd5f792cf4589d3cdc495d8f2 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 1 \ -w 9 \ -n 2 ``` Example output: ``` Transaction hash: 0x45ae379b056a6fc647a3718bd356268a1bcda35e6645bb7a1aba44cb76418c98 Ephemeral private key: macisk.2b23e978301d029e46117ef0138f860e277ffed0f008712f3d7ca2c40f1a6768 ``` **Coordinator: process all messages** ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js process \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r ``` Example output: ``` Processed batch starting at index 0 Transaction hash: 0xbd1bbe86cd4fc72f34911220db428751e8a483b3afcc9d30c1a15989a7b6a031 Random state leaf: <RANDOM STATE LEAF> ``` **Coordinator: tally all votes** ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js tally \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r \ -c 0x0 \ -tvc 0x0 \ -pvc 0x0 \ -t tally.json \ -z <PASTE RANDOM STATE LEAF HERE> ``` Example output: ``` Transaction hash: 0x9ef0ab94d534650445c4ff748a43eacdedff1602929bd6a1bd568573374ddca2 Current results salt: 0xa54b75db545fcda278ce882cae90d069c6fcf81368778264550d9b66af05a42 Result commitment: 0x25deb6f675ed4f08742e1776eee130c627d168106fd813627963b241c1ba0754 ``` The file `tally.json` will now contain something like the following: ```json { "provider": "http://localhost:8545", "maci": "0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4", "results": { "commitment": "0x1cd0ec2789abceb908b06f6a74c26a848e209011ec41b3e5028bb7aeff2bdeb2", "tally": [ "9", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ], "salt": "0x2d7f1744185507a529fdb32dec920bfdaf825b0fdba5b66661a40a71beac3b46" }, "totalVoiceCredits": { "spent": "81", "commitment": "0x2d55a42ec1da99227125cf9562aa91aad12e2f1387ccf3411da79b0a953d69a6", "salt": "0xfc95a102f3c66d92d7a5700f1e12a6f2325c54a10efa0e1178cc21b67f0d97c" }, "totalVoiceCreditsPerVoteOption": { "commitment": "0x18526f481cf2476543c8dcc3762f3a54af8e217d3d048810856623367ef4ba14", "tally": [ "81", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0" ], "salt": "0x1f17d2ff16b9791ef4b1849bfccf420b9fece161e419ad4f8b1ef726c62e3943" } } ``` Anyone can now run `verify` to check if the tally is correct: ```bash node build/index.js verify -t tally.json ``` Example output: ``` The results commitment in the specified file is correct given the tally and salt The total spent voice credit commitment in the specified file is correct given the tally and salt The per vote option spent voice credit commitment in the specified file is correct given the tally and salt The results commitment in the MACI contract on-chain is valid The total spent voice credit commitment in the MACI contract on-chain is valid The per vote option spent voice credit commitment in the MACI contract on-chain is valid The total sum of votes in the MACI contract on-chain is valid. ``` ## Demonstration with `prod-small` settings Create a MACI instance: ```bash node ./build/index.js create -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -e http://localhost:8545 \ -s 15 \ -o 60 \ -bm 4 \ -bv 4 \ -u 255 \ -m 2048 ``` Sign up: ``` node ./build/index.js signup -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 ``` Vote: ``` node ./build/index.js publish -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.53c8bc722a9f9d4c7bd478c8c8b01177f82d9c68d1ce15078e93ea84f198644 \ -p macipk.40270618e1797c4969587eb04d7f3e9b39a91ecbbdf7d3c998d8e34d08e11c86 \ -i 1 \ -v 0 \ -w 9 \ -n 1 ``` Process all messages: ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js process \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r ``` Tally all votes: ``` NODE_OPTIONS=--max-old-space-size=4096 node ./build/index.js tally \ -d 0xc87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3 \ -e http://localhost:8545 \ -x 0x2C2B9C9a4a25e24B174f26114e8926a9f2128FE4 \ -sk macisk.8715ab59a3e88a7ceec80f214ec24a95287ef2cb399a329b6964a87f85cf51c \ -r \ -c 0x0 \ -tvc 0x0 \ -pvc 0x0 \ -t tally.json \ -z <PASTE RANDOM STATE LEAF HERE> ``` # Matic contracts [![Build Status](https://travis-ci.org/maticnetwork/contracts.svg?branch=master)](https://travis-ci.org/maticnetwork/contracts) Ethereum smart contracts that power the [Matic Network](https://matic.network). ### Install dependencies with ``` npm install ``` ### Compile ``` npm run template:process npm run truffle:compile ``` ### Start main chain and side chain - Start Main chain ``` npm run testrpc ``` - Start Matic side chain. Requires docker. ``` npm run bor:simulate ``` - If you ran a bor instance before, a dead docker container might still be lying around, clean it with ``` npm run bor:clean ``` - Run a bor (our matic chain node) instance. ### Deploy Contracts - For local development ``` npm run truffle:migrate ``` - For a properly initialized set of contracts, follow the instructions [here](./deploy-migrations/README.md). ### Run tests ``` npm test ``` # Zora Media Protocol This repository contains the core contracts that compose the Zora Media Protocol. The protocol aims to provide a universal value system for media. Further documentation is available at [zora.engineering](https://zora.engineering) ## Table of Contents - [Whitepaper](#whitepaper) - [Architecture](#architecture) - [Mint](#mint) - [Set Bid](#set-bid) - [Remove Bid](#remove-bid) - [Transfer](#transfer) - [Burn](#burn) - [Set Ask](#set-ask) - [Accept Bid](#accept-bid) - [Approve](#approve) - [Update Token and Media URI](#update-token-and-media-uri) - [Permit](#permit) - [Mint with Signature](#mint-with-signature) - [Local Development](#Local-Development) - [Install Dependencies](#install-dependencies) - [Compile Contracts](#compile-contracts) - [Start a Local Blockchain](#start-a-local-blockchain) - [Run Tests](#run-tests) ## Whitepaper The whitepaper is available at [zora.engineering](https://zora.engineering/whitepaper) ## Architecture This protocol is an extension of the ERC-721 NFT standard, intended to provide a unified pool of liquidity in the form of bids in a market for each NFT. This protocol refers to NFTs as `Media`. The protocol's roles and methods interact with the core contracts as follows: ![Architecture Diagram](./architecture.png) The following structs are defined in the contract and used as parameters for some methods: ```solidity // Decimal.D256 struct D256 { uint256 value; } struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the previous owner Decimal.D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; // % of the next sale to award the previous owner Decimal.D256 sellOnShare; } struct BidShares { // % of sale value that goes to the _previous_ owner of the nft Decimal.D256 prevOwner; // % of sale value that goes to the original creator of the nft Decimal.D256 creator; // % of sale value that goes to the seller (current owner) of the nft Decimal.D256 owner; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A SHA256 hash of the content pointed to by tokenURI bytes32 contentHash; // A SHA256 hash of the content pointed to by metadataURI bytes32 metadataHash; } struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } ``` ### Mint At any time, a creator may mint a new piece of media. When a piece is minted, the new media is transferred to the creator and a market is formed. | **Name** | **Type** | **Description** | | ----------- | ----------- | --------------------------------------------------------------------------------------- | | `data` | `MediaData` | The data represented by this media, including SHA256 hashes for future integrity checks | | `bidShares` | `BidShares` | The percentage of bid fees that should be perpetually rewarded to the creator. | ![Mint process flow diagram](./mint.png) ### Set Bid Anyone may place a bid on a minted token. By placing a bid, the bidder deposits the currency of their choosing into the market contract. Any valid ERC-20 currencies can be used to bid. Note that we strongly recommend that bidders do not bid using a currency that can be rebased, such as [AMPL](https://www.ampleforth.org/), [YAM](https://yam.finance/), or [BASED](https://based.money), as funds can become locked in the Market if the token is rebased. | **Name** | **Type** | **Description** | | --------- | --------- | -------------------------------------- | | `tokenId` | `uint256` | The tokenID for the media being bid on | | `bid` | `Bid` | The bid to be placed | ![Set Bid process flow diagram](./setBid.png) ### Remove Bid Once a bid has been set by a bidder, it can be removed. In order to remove a bid from a piece of media, the bidder simply specifies the piece of media that they wish to remove their bid from. Note from the process flow diagram above for setting a bid that only one bid can be set a time per bidder per piece of media. | **Name** | **Type** | **Description** | | --------- | --------- | ---------------------------------------------------- | | `tokenId` | `uint256` | The tokenID for the media who's bid is being removed | ![Remove Bid process flow diagram](./removeBid.png) ### Transfer Any media owner is able to transfer their media to an address of their choosing. This does not alter the market for the media, except to remove the Ask on the piece, if it is present. Its implementation from the standard ERC721 standard is unchanged in this protocol. ### Burn This protocol allows for media to be burned, if and only if the owner of the media is also the creator. When burned, the `tokenURI` and `metadataURI` of the media are not removed. This means that even though the market becomes inactive, the media is still viewable. Effectively, the media becomes read-only. Any bids that were placed on a piece prior to it being burned can still be removed. | **Name** | **Type** | **Description** | | --------- | --------- | --------------------------------- | | `tokenId` | `uint256` | The tokenID for the media to burn | ![Burn process flow diagram](./burn.png) ### Set Ask At any time, an owner may set an Ask on their media. The ask serves to automatically fulfill a bid if it satisfies the parameters of the ask. This allows collectors to optionally buy a piece outright, without waiting for the owner to explicitly accept their bid. | **Name** | **Type** | **Description** | | --------- | --------- | ------------------------- | | `tokenId` | `uint256` | The tokenID for the media | | `ask` | `Ask` | The ask to be set | ![Set Ask process flow diagram](./setAsk.png) ### Accept Bid When an owner sees a satisfactory bid, they can accept it and transfer the ownership of the piece to the bidder's recipient. The bid's funds are split according to the percentages defined in the piece's bid shares. Note that bids can have a sell-on fee. This fee is to entitle the seller to a piece of the next sale of the media. For example, suppose someone owns a piece with a limited means of promoting it. In this case, it may be favorable to accept a bid from a highly regarded platform for a lower initial capital, but high potential resale fee. Since the sell-on fee can be easily avoided by bidders with ill intent, it's suggested that owners only accept sell-on fee offers from reputable buyers. | **Name** | **Type** | **Description** | | --------- | --------- | ------------------------- | | `tokenId` | `uint256` | The tokenID for the media | | `bid` | `Bid` | The bid to accept | ![Accept Bid process flow diagram](./acceptBid.png) ### Approve At any time, the owner of a piece of media is able to approve another address to act on its behalf. This implementation is unchanged from the ERC-721 standard. However, approved addresses are now also able to accept bids, set asks, update URIs, and burn media (provided the owner is the creator, as above). ### Update Token and Media URI Although this protocol is designed to maintain perpetual markets for media, data availability of that media is considered out of scope. However, in the event that the URIs that point to the data must be changed, this protocol offers the ability to update them. Recall that when minting tokens, sha256 hashes of the content and metadata are provided for integrity checks. As a result, anyone is able to check the integrity of the media if the URIs change. This protocol deviates from the ERC-721 in that the `tokenURI` does **not** point to a valid ERC721 Metadata JSON Schema as defined in the EIP. In order to support integrity checks when updating the tokenURIs, the content and metadata of a piece of media are split into `tokenURI` and `metadataURI`, respectively. This split effectively allows for the reconfiguration of the URIs of both the content and metadata, while preserving integrity checks. #### Metadata JSON schema In order to enable anyone to use this protocol as they see fit, there is no single metadata JSON schema that is used for this protocol. However, it is strongly recommended that developers submit a valid [JSON schema](https://json-schema.org/) to the [Media Metadata Schemas Repository](https://github.com/ourzora/media-metadata-schemas) to allow anyone to support custom metadata. The only **required** key of the JSON metadata is `version`, which is a string in the format of `<name-calVersion>` (e.g. `zora-20210101`). This key can be used by implementing platforms to determine which metadata schemas to support. ### Permit In order to provide support for third parties to interact with this protocol on a user's behalf, the EIP-712 standard for signing typed data structures is supported. The protocol offers a `permit` method loosely based off of EIP-2612, with some adjustments made to support NFTs rather than ERC-20 currencies. The `Permit` EIP-712 data structure is as follows: ```typescript { Permit: [ { name: 'spender', type: 'address' }, { name: 'tokenId', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }, ]; } ``` If the permit is applied, the specified `spender` is set as approved for the signer. Note that the `spender` will stay approved until the approval is revoked. ### Mint With Signature If the media has yet to be minted yet, creators are able to permit a third party to mint on their behalf by signing a `MintWithSig` object. The structure is as follows: ```typescript { MintWithSig: [ { name: 'tokenURI', type: 'string' }, { name: 'metadataURI', type: 'string' }, { name: 'creatorShare', type: 'uint256' }, { name: 'nonce', type: 'uint256' }, { name: 'deadline', type: 'uint256' }, ]; } ``` ## Local Development The following assumes `node >= 12` ### Install Dependencies ```shell script yarn ``` ### Compile Contracts ```shell script yarn build ``` ### Start a Local Blockchain ```shell script yarn chain ``` ### Run Tests ```shell script yarn test ``` # maci-integrationTests This submodule contains test suites that span between different submodules. The current approach that it takes is to test each CLI command and also chain them together. # Minimal Anti-Collusion Infrastructure Please refer to the [implementation spec](./specs/) for technical details, and the original [ethresear.ch post](https://ethresear.ch/t/minimal-anti-collusion-infrastructure/5413) for a high-level view. We welcome contributions to this project. Please join our [Telegram group](https://t.me/joinchat/LUgOpE7J2gstRcZqdERyvw) to discuss. ## Local development and testing ### Requirements You should have Node 12 installed. Use [`nvm`](https://github.com/nvm-sh/nvm) to install it. ### Get started Clone this repository, install NodeJS dependencies, and build the source code: ```bash git clone [email protected]:appliedzkp/maci.git && \ npm i && \ npm run bootstrap && \ npm run build ``` For development purposes, you can generate the proving and verifying keys for the zk-SNARK circuits, along with their Solidity verifier contracts as such. Install Rust: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` Also install [`zkutil`](https://github.com/poma/zkutil) v0.3.2 and ensure that the `zkutil` binary is in the `~/.cargo/bin/` directory. You can [configure](https://lorenwest.github.io/node-config/) the path to this binary via `maci-config` (see `config/test.yaml` for an example). ```bash cargo install zkutil --version 0.3.2 && zkutil --help ``` Build the zk-SNARKs and generate their proving and verifying keys: ```bash cd circuits npm run buildBatchUpdateStateTreeSnark npm run buildQuadVoteTallySnark ``` This should take no more than 5 minutes. We used to provide download links to working versions of the keys and compiiled circuit files, but now that we can use `snarkjs` to produce them very quickly, we no longer maintain them. Note that if you change the circuits and recompile them, you should also update and recompile the verifier contracts in `contracts/sol` with their new versions, or the tests will fail: ```bash cd contracts npm run compileSol ``` ### Demo You can use the MACI command-line interface to run a demo. See: https://github.com/appliedzkp/maci/tree/master/cli#demonstration ### Local development This repository is organised as Lerna submodules. Each submodule contains its own unit tests. - `config`: project-wide configuration files. Includes config files for both testing and production. - `crypto`: low-level cryptographic operations. - `circuits`: zk-SNARK circuits. - `contracts`: Solidity contracts and deployment code. - `domainobjs`: Classes which represent high-level [domain objects](https://wiki.c2.com/?DomainObject) particular to this project. - `core`: Business logic functions for message processing, vote tallying, and circuit input generation through `MaciState`, a state machine abstraction. - `cli`: A command-line interface with which one can deploy and interact with an instance of MACI. - `integrationTests`: Integration tests which use the command-line interface to perform end-to-end tests. ### Testing #### Unit tests The following submodules contain unit tests: `core`, `crypto`, `circuits`, `contracts`, and `domainobjs`. Except for the `contracts` submodule, run unit tests as such (the following example is for `crypto`): ```bash cd crypto npm run test ``` For `contracts` and `integrationTests`, run the tests one by one. This prevents incorrect nonce errors. First, start a Ganache instance in a separate terminal: ```bash cd contracts npm run ganache ``` In another terminal, run the tests individually: ```bash cd contracts ./scripts/runTestsInCircleCi.sh ``` or ```bash cd integrationTests ./scripts/runTestsInCircleCi.sh ``` You can ignore the Ganache errors which this script emits as you should already have Ganache running in a separate terminal. Otherwise, you will have to exit Ganache using the `kill` command. # EthBridge Ethereum Light Client built on top of NearProtocol with Rust ## Testing ```bash ./test.sh ``` # Graph Node Docker Image Preconfigured Docker image for running a Graph Node. ## Usage ```sh docker run -it \ -e postgres_host=<HOST> \ -e postgres_port=<PORT> \ -e postgres_user=<USER> \ -e postgres_pass=<PASSWORD> \ -e postgres_db=<DBNAME> \ -e ipfs=<HOST>:<PORT> \ -e ethereum=<NETWORK_NAME>:<ETHEREUM_RPC_URL> \ graphprotocol/graph-node:latest ``` ### Example usage ```sh docker run -it \ -e postgres_host=host.docker.internal \ -e postgres_port=5432 \ -e postgres_user=graph-node \ -e postgres_pass=oh-hello \ -e postgres_db=graph-node \ -e ipfs=host.docker.internal:5001 \ -e ethereum=mainnet:http://localhost:8545/ \ graphprotocol/graph-node:latest ``` ## Docker Compose The Docker Compose setup requires an Ethereum network name and node to connect to. By default, it will use `mainnet:http://host.docker.internal:8545` in order to connect to an Ethereum node running on your host machine. You can replace this with anything else in `docker-compose.yaml`. > **Note for Linux users:** On Linux, `host.docker.internal` is not > currently supported. Instead, you will have to replace it with the > IP address of your Docker host (from the perspective of the Graph > Node container). > To do this, run: > > ``` > CONTAINER_ID=$(docker container ls | grep graph-node | cut -d' ' -f1) > docker exec $CONTAINER_ID /bin/bash -c 'apt install -y iproute2 && ip route' | awk '/^default via /{print $3}' > ``` > > This will print the host's IP address. Then, put it into `docker-compose.yml`: > > ``` > sed -i -e 's/host.docker.internal/<IP ADDRESS>/g' docker-compose.yml > ``` After you have set up an Ethereum node—e.g. Ganache or Parity—simply clone this repository and run ```sh docker-compose up ``` This will start IPFS, Postgres and Graph Node in Docker and create persistent data directories for IPFS and Postgres in `./data/ipfs` and `./data/postgres`. You can access these via: - Graph Node: - GraphiQL: `http://localhost:8000/` - HTTP: `http://localhost:8000/subgraphs/name/<subgraph-name>` - WebSockets: `ws://localhost:8001/subgraphs/name/<subgraph-name>` - Admin: `http://localhost:8020/` - IPFS: - `127.0.0.1:5001` or `/ip4/127.0.0.1/tcp/5001` - Postgres: - `postgresql://graph-node:let-me-in@localhost:5432/graph-node` Once this is up and running, you can use [`graph-cli`](https://github.com/graphprotocol/graph-cli) to create and deploy your subgraph to the running Graph Node. # HehuNet ## Origin - Hehu is the Ancient God of Infinite Wisdom and Wealth ## Design - An Ensemble of Evolving Tokens of Infinite and Immersive Value Systems ## Concept - LabsDAO - AlchemyDAO ( https://docs.alchemydao.com/ ) - ArtBlocks ( https://artblocks.io/ ) - Radicle ## Context - Integration of Radicle based Code Collaboration with based Arbitrum Rollups - Generative ArtNFTs with chainlink adaptors to affect their appearance into the future - Abstraction NFT and Aggregation of NFTs on Arbitrum - Quadratic Voting Mechanism - Twitter Streams ## Convergence - SiddhiNet - RheaNet - TerrainNet - SemiotNet - ConcertNet - EbbNet # minty Minty is an example of how to _mint_ non-fungible tokens (NFTs) while storing the associated data on IPFS. You can also use Minty to pin your data on an IPFS pinning service such as Pinata. ## Usage Run `minty help` to see full usage instructions or `minty help <command>` for help on a specific command: ```shell minty help mint > create a new NFT from an image file > > Options: > -n, --name <name> The name of the NFT > -d, --description <desc> A description of the NFT > -o, --owner <address> The ethereum address that should own the NFT.If not provided, > defaults to the first signing address. > -h, --help display help for command ``` ## Setup To install and run Minty, you must have NPM installed. Windows is not currently supported. 1. Clone this repository and move into the `minty` directory: ```shell git clone https://github.com/yusefnapora/minty cd minty ``` 1. Install the NPM dependencies: ```shell npm install ``` 1. Add the `minty` command to your `$PATH`. This makes it easier to run Minty from anywhere on your computer: ``` npm link ``` 1. Run the `start-local-environment.sh` script to start the local Ethereum testnet and IPFS daemon: ```shell ./start-local-environment.sh > Compiling smart contract > Compiling 16 files with 0.7.3 > ... ``` This command continues to run. All further commands must be entered in another terminal window. ## Deploy the contract Before running any of the other `minty` commands, you'll need to deploy an instance of the smart contract: ```shell minty deploy > deploying contract for token Julep (JLP) to network "localhost"... > deployed contract for token Julep (JLP) to 0x5FbDB2315678afecb367f032d93F642f64180aa3 (network: localhost) > Writing deployment info to minty-deployment.json ``` The terminal window running the `./start-local-environment.sh` will output something like: ```shell > [eth] eth_chainId > [eth] eth_getTransactionByHash > [eth] eth_blockNumber > eth_chainId (2)Id > eth_getTransactionReceipt ``` This deploys to the network configured in [`hardhat.config.js`](./hardhat.config.js), which is set to the `localhost` network by default. If you get an error about not being able to reach the network, make sure to run the local development network with `./start-local-environment.sh`. When the contract is deployed, the address and other information about the deployment is written to `minty-deployment.json`. This file must be present for subsequent commands to work. To deploy to an ethereum testnet, see the [Hardhat configuration docs](https://hardhat.org/config/) to learn how to configure a JSON-RPC node. Once you've added a new network to the Hardhat config, you can use it by setting the `HARDHAT_NETWORK` environment variable to the name of the new network when you run `minty` commands. Alternatively, you can change the `defaultNetwork` in `hardhat.config.js` to always prefer the new network. Deploying this contract to the Ethereum mainnet is a bad idea since the contract itself lacks any access control. See the [Open Zeppelin article](https://docs.openzeppelin.com/contracts/3.x/access-control) about what access control is, and why it's important to have. ## Configuration Configuration are stored in [`./config/default.js`](./config/default.js). The `start-local-devnet.sh` script will try to run a local IPFS daemon, which Minty will connect to on its default port. If you've already installed IPFS and configured it to use a non-standard API port, you may need to change the `ipfsApiUrl` field to set the correct API address. The `pinningService` configuration option is used by the `minty pin` command to persist IPFS data to a remote pinning service. The default configuration is setup to pin data to [Pinata](https://pinata.cloud), and it expects a Pinata JWT access token to be set to the `PINATA_API_TOKEN` environment variable. If you don't have an API token, either get a free one or configure a different pinning service. With no pinning service, everything apart from the `minty pin` command should still work. ### Mint a new NFT Once you have the local Ethereum network and IPFS daemon running, minting an NFT is incredibly simple. Just specify what you want to _tokenize_, the name of the NFT, and a description to tell users what the NFT is for: ```shell minty mint ~/flight-to-the-moon.txt --name "Moon Flight #1" --description "This ticket serves as proof-of-ownership of a first-class seat on a flight to the moon." > 🌿 Minted a new NFT: > Token ID: 1 > Metadata URI: ipfs://Qma4RRDu9Q5ZXb4F6HSPAHXeyinYYFuBMTrk7HbHrsbcN9/metadata.json > Metadata Gateway URL: http://localhost:8080/ipfs/Qma4RRDu9Q5ZXb4F6HSPAHXeyinYYFuBMTrk7HbHrsbcN9/metadata.json > Asset URI: ipfs://QmbwYvCrjnv9nKqagwYoniNzppf96za7BnateWD18mQnHX/flight-to-the-moon.txt > Asset Gateway URL: http://localhost:8080/ipfs/QmbwYvCrjnv9nKqagwYoniNzppf96za7BnateWD18mQnHX/flight-to-the-moon.txt > NFT Metadata: > { > "name": "Moon Flight #1", > "description": "This ticket serves are proof-of-ownership of a first-class seat on a flight to the moon.", > "image": "ipfs://QmbwYvCrjnv9nKqagwYoniNzppf96za7BnateWD18mQnHX/flight-to-the-moon.txt" > } ``` ### Show details of an existing NFT You can view the details of each individual NFT by calling `show` along with the ID of the NFT: ```shell minty show 1 > Token ID: 1 > Owner Address: 0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266 > Metadata URI: ipfs://Qma4RRDu9Q5ZXb4F6HSPAHXeyinYYFuBMTrk7HbHrsbcN9/metadata.json > ... ``` ### Pin IPFS assets for an NFT The assets for new tokens are stored in a local IPFS repository which is only _online_ while a local IPFS daemon is running. The `start-local-environment.sh` script starts a local daemon for you if you aren't already running and IPFS daemon. If you are, then the script just uses the daemon you already have. To make the data highly available without needing to run a local IPFS daemon 24/7, you can request that a [Remote Pinning Service](https://ipfs.github.io/pinning-services-api-spec) like [Pinata](https://pinata.cloud/) store a copy of your IPFS data on their IPFS nodes. To pin the data for token, use the `minty pin` command: ```shell minty pin 1 > Pinning asset data (ipfs://QmUAACALRufqXnGHM1QCSr5JA3b54N5QBKD73EXx6pws2f/ipfs-logo.png) for token id 1.... > Pinning metadata (ipfs://QmR6YQJX9woK2SzmzFJ1T4q1bMinbQrWaSQdcxcJmgKuDY/metadata.json) for token id 1... > 🌿 Pinned all data for token id 1 ``` The `pin` command looks for a JWT access token from [Pinata](https://pinata.cloud) in the `PINATA_API_TOKEN` environment variable. Once you've obtained a token from Pinata, make a file in the `config` directory called `default.env`, and edit it to look like this, with your JWT token inside the quote marks: ```shell PINATA_API_TOKEN="Paste your Pinata JWT token inside the quotes!" ``` Now Minty will be able to pin things to your Pinata account! If you'd prefer to use a different pinning service, you can edit the configuration in `config/default.js`. # `maci-core` This submodule assists with handling key business logic functions and processes. ## Overview One may conceive of MACI as a state machine with 1) data and 2) functions which transform said data. This makes it easier to reason about the system, write tests, and implement functionality. It also allows us to implement the smart contracts in discrete components which are easy to test. To this end, we this submodule exposes a `MaciState` class and a `User` class. ## **`User`** Each `User object has the following attributes: `pubKey: PubKey`: The user's public key. `votes: SnarkBigInt[]`: The voice credits assigned to each vote option. `voiceCreditBalance: SnarkBigInt`: The user's remaining voice credit balance. ### Functions #### **`genStateLeaf`** Function signature: ```ts (_voteOptionTreeDepth: number): StateLeaf ``` Generates and returns an equivalent `StateLeaf` [domain object](../domainobjs/). This function helps `MaciState` to generate a state tree. #### **`copy`** Function signature: ```ts (): User ``` Deep-copies and returns this object. ## `MaciState` We denote all state data as attributes of a `MaciState` object. Only the coordinator should have access to state data. Each user can only access their own keypair, commands, and on-chain state and message tree roots. `MaciState` contains the following attributes: `coordinatorKeypair: Keypair`: The coordinator's keypair. `users: User[]`: An array of `User` objects, each of which represents the current state of a user. `stateTreeDepth: SnarkBigInt`: The depth of the state tree. `messageTreeDepth: SnarkBigInt`: The depth of the message tree. `voteOptionTreeDepth: SnarkBigInt`: The depth of each user's vote option tree. `messages: Message[]`: An array of all published messages. `zerothStateLeaf: StateLeaf`: The leaf of the state tree at index 0. This means that the zeroth user in `users` has index 1 in the state tree. `maxVoteOptionIndex: SnarkBigInt`: The maximum allowed vote options. For instance, even if the vote option tree supports up to 16 vote options, this value can be set to 12 so as to enforce the fact that there are only 12 options to choose from. `encPubKeys: PubKey[]`: An array of public keys used to generate ephermeral ECDH shared keys with which to encrypt commands to messages. For each `PubKey` in `encPubKey`, its corresponding `Message` in `messages` shares the same array index. ### Functions The following functions modify the state: - `signUp()` - `publishMessage()` - `processMessage()` - `batchProcessMessage()` The following functions do not modify the state: - `copy()` - `genStateTree()` - `genStateRoot()` - `genMessageTree()` - `genMessageRoot()` - `computeCumulativeVoteTally()` - `genUpdateStateTreeCircuitInputs()` - `genBatchUpdateStateTreeCircuitInputs()` #### **`signUp`** Function signature: ```ts ( _pubKey: PubKey, _initialVoiceCreditBalance: SnarkBigInt, ): void ``` Appends a `User` with the specified public key and initial voice credit balance to the `users` array. #### **`publishMessage`** Function signature: ```ts ( _message: Message, _encPubKey: PubKey, ): void ``` Appends a `Message` to the `messages` array. It also appends the public key used to generate the ECDH shared key which encrypts `_message` to the `encPubKeys` array. #### **`processMessage`** Function signature: ```ts (_index: number): void ``` This function: 1. Generates a shared key using `encPubKeys[index]` and `coordinatorKeyPair.pubKey` 2. Decrypts `messages[_index]` to derive a `Command` 3. If the message is invalid, do nothing and return 4. If the message is valid, update the user's public key and vote at `_index`. #### **`batchProcessMessage`** Function signature: ```ts ( _index: number, _batchSize: number, _randomStateLeaf: StateLeaf, ): void ``` This function runs `processMessage()` on a batch of `_batchSize` leaves starting from index `_index`, and then replaces the zeroth leaf with `_randomStateLeaf`. **`genStateTree()`** Function signature: ```ts (): IncrementalMerkleTree ``` Generates and returns the state tree as an incremental Merkle tree. **`genStateRoot()`** Function signature: ```ts (): SnarkBigInt ``` This function computes the state root given the data stored in `users` and `zerothStateLeaf`. **`genMessageTree()`** Function signature: ```ts (): IncrementalMerkleTree ``` Generates and returns the message tree as an incremental Merkle tree. **`genMessageRoot()`** Function signature: ```ts (): SnarkBigInt ``` This function computes the state root given the data stored in `messsages`. **`genUpdateStateTreeCircuitInputs`** Function signature: ```ts genUpdateStateTreeCircuitInputs = (_index: number): object ``` Generates the circuit inputs (both public and private) for the `UpdateStateTree` circuit, as an object with the following attributes: - `coordinator_public_key` - `ecdh_private_key` - `ecdh_public_key` - `message` - `msg_tree_root` - `msg_tree_path_elements` - `msg_tree_path_index` - `vote_options_leaf_raw` - `vote_options_tree_root` - `vote_options_tree_path_elements` - `vote_options_tree_path_index` - `vote_options_max_leaf_index` - `state_tree_data_raw` - `state_tree_max_leaf_index` - `state_tree_root` - `state_tree_path_elements` - `state_tree_path_index` **`genBatchUpdateStateTreeCircuitInputs`** Function signature: ```ts genBatchUpdateStateTreeCircuitInputs = ( _index: number, _batchSize: number, _randomStateLeaf: StateLeaf, ) => object ``` Generates the circuit inputs (both public and private) for the `BatchUpdateStateTree` circuit, as an object with the following attributes: - `coordinator_public_key` - `message` - `ecdh_private_key` - `ecdh_public_key` - `msg_tree_root` - `msg_tree_path_elements` - `msg_tree_batch_start_index` - `random_leaf` - `state_tree_root` - `state_tree_path_elements` - `state_tree_path_index` - `random_leaf_root` - `random_leaf_path_elements` - `vote_options_leaf_raw` - `state_tree_data_raw` - `state_tree_max_leaf_index` - `vote_options_max_leaf_index` - `vote_options_tree_root` - `vote_options_tree_path_elements` - `vote_options_tree_path_index` **`genQuadVoteTallyCircuitInputs`** Function signature: ```ts genQuadVoteTallyCircuitInputs = ( _startIndex: SnarkBigInt, _batchSize: SnarkBigInt, _currentResultsSalt: SnarkBigInt, _newResultsSalt: SnarkBigInt, ): object ``` Generates the circuit inputs (both public and private) for the `QuadVoteTally` circuit, as an object with the following attributes: - `voteLeaves` - `stateLeaves` - `currentResults` - `fullStateRoot` - `currentResultsSalt` - `newResultsSalt` - `currentResultsCommitment` - `intermediatePathElements` - `intermediatePathIndex` - `intermediateStateRoot` **`copy()`** Function signature: ```ts (): MaciState ``` This function returns a deep-copied `MaciState` object. # maci-crypto This module implements abstractions over cryptographic functions which MACI employs. ## Types and interfaces **`PrivKey`**: A private key. **`PubKey`**: A public key. **`EcdhSharedKey`**: An Elliptic-curve Diffie–Hellman shared key. **`Plaintext`**: An array of unencrypted values. **`Ciphertext`**: Encrypted `Plaintext`. This data structure abstracts over the initialisation vector and encrypted data. **`Signature`**: A signature. This data structure abstracts over the`R8` and `S` values. ## Functions **`genPrivKey: PrivKey`** Returns a securely random private key. **`genPubKey = (privKey: PrivKey): PubKey `** Generates the public key associated with the given private key. **`genEcdhSharedKey = (privKey: PrivKey, pubKey: PubKey): EcdhSharedKey`** Generates an ECDH shared key. **`encrypt = (plaintext: Plaintext, sharedKey: EcdhSharedKey): Ciphertext`** Encrypts the plaintext with the given key and returns the associated ciphertext. **`decrypt = (ciphertext: Ciphertext, sharedKey: EcdhSharedKey): Plaintext`** Decrypts the ciphertext using the given key. **`sign = (privKey: PrivKey, message: Plaintext): Signature`** Produces a signature of the given message using the private key. **`verifySignature = (message: Plaintext, signature: Signature, publicKey: PubKey): boolean`** Checks whether the given signature is valid. # RheaNet - Rhea Resolution Reserve Protocol - Digital Dispute Resolution System for Maritime Trade Powered by Chainlink Oracles ## Tracks - ChainLink Oracles - ChainLink VRF - Graph Protocol - Polygon Network - Protocol Labs - Arbitrum - AAVE Protocol - OpenLaw Protocol ## Concepts - ERC 1155 for Bill of Lading - ERC 721 for each of the goods - Fractionalising ERC 1155 based of delivery time and location - Dispute Resolution Reserve - Flash Loans based on Dispute Resolution Reserve - Yield Farming from Dispute Resolution Reserve ## Data Model ### Resolution Claim - Input ### Resolution Reserve - Input ### Goods NFT - Properties - Metadata ### Bill of Lading NFT - Properties - Metadata ### OpenLaw Agreements - Parties - ### Dispute Workflow - Task Name - Task Name ### Flash Loans - ## References - https://github.com/smartcontractkit/chainlink - https://docs.chain.link/docs/architecture-request-model - https://docs.chain.link/docs/create-a-chainlinked-project - https://blog.chain.link/chainlink-external-adapters-explained/ - https://chainlinkadapters.com/guides/link-chainlink-to-url-endpoint - https://docs.chain.link/docs/intermediates-tutorial#introduction - https://github.com/thodges-gh/CL-EA-Python-Template - https://docs.chain.link/docs/running-a-chainlink-node - https://blog.chain.link/build-and-use-external-adapters/ - https://chainlinkadapters.com/guides - https://github.com/DAOfi/fungify_nft - https://github.com/mapachurro/OpenLease - https://github.com/openlawteam/OpenCourt - https://billoflading.org/ - https://www.wired.com/1999/04/open-source-in-open-court/ - https://developer.offchainlabs.com/docs/contract_deployment - https://media.consensys.net/opencourt-legally-enforceable-blockchain-based-arbitration-3d7147dbb56f # Edible Experience and Entertainment on Ethereum Creative Convergence of Chefs and Coders for the Culinary Community of GastroNauts ## Concept EddyNet is an Ethereum Experience, Entertainment and Engineering Platform powered by the concept of Non Fungible Tokens. It is created for tokenising the food recipes, food streets, food sharing events, food blogs, food festivals and so on. EddyNet envisions an enthusiastic and exciting future for dynamic decentralization of culinary cultures and cuisines across the world. EddyNet is embarking on a creative convergence of food makers, lovers and consumers beyond the walls of arbitrary accumulations and aggregated architectures. ## Technology The Food Streets are captured on Videos and added to the IPFS. The Food Recipes are also added to IPFS. All these food related artifacts are minted into Non Fungible Tokens using the Minty Framework integrated to the IPFS. The profits from the Food Experiences are converted to Food Fungible ERC 20 tokens and then distributed through Bonding Curve based on Bancor Formula. Food Events, Festivals, Carnivals, Blogs, etc will be streamed through the ERC 1620 Streaming Token Specification. Wherever privacy is required for specific food festivals, food recipes and food experiences they are delivered through the Zether Framework implementation of ERC 1724 specification. A Food Auction on Zora Protocol and a Food Marketplace powered by the Graph Protocol are in progress. Food NFTs are deployed on the Rainbow Bridge between Ethereum and NEAR Protocol. To summarize following are the tools and technologies used : * Ethereum, ERC 721, ERC 20, ERC 1620, ERC 1724 * Bonding Curves * IPFS, Minty, Pinata, * Zora, Graph, NEAR Protocols * Rainbow Bridge * NodeJS, ReactJS ## Deployment - EddyNet Streaming Token - https://mumbai-explorer.matic.today/tx/0x0f1c0d8bf80860635ee0cac31247a38a440157a4d30cc2663383390f0234c60f ## Images ![First EddyNet Recipe on IPFS](https://github.com/Semiott/EddyNet/blob/main/images/IPFSAdd_Recipe_21032021.png) # Alchemy Repository for the Alchemy Contracts ## Dapps You can find the mainnet version of the Alchemy Dapp here: [https://alchemydao.com/](https://alchemydao.com) ## Airdrop Holders of certain NFT projects can claim 20 $ALCH for free as an airdrop here [https://alchemydao.com/stake](https://alchemydao.com/stake) ## Deployments ALCH Token deployed to: 0x0000A1c00009A619684135B824Ba02f7FbF3A572 AlchemyTimelock deployed to: 0xCA2b3CF3989e70813719ac7703daF4B14f46b377 AlchemyGovernorAlpha deployed to: 0x9789D57093c66AF78C1AEb5CE19A10f963673f87 Alchemy Implementation deployed to: 0xb8ea9249D45681edc5cE730478132417697f2097 GovernorAlpha Implementation deployed to: 0x32c1970560a604bcFF4c4C82AcF9F47161b5f428 Timelock Implementation deployed to: 0x81692F5647ef63766F3A521114bc9ED094eC23cE AlchemyFactory deployed to: 0xdc2778E19C7F32D2Cf0c4c90B705Fb702Aa94150 Router deployed to: 0xe02eF7BeAc8c723a17545e0F9F2774Caf13466fc ETH Rewards Pool deployed to: 0x82E025bce8f4707b7AD406c036E5b8273389612B ALCH Rewards LPPool deployed to: 0x6d46fb5527bDb6Dcb2716f0FE1F0EA0F9ae019fC MerkleDistributor deployed to: 0xE23f250670A8151819D0d72710cb2f9D55761Bb3 DelegatingVester deployed to: 0x29fE35491ca8e01f8fd3120cDc38A8487d5A4017 DelegatingVesterFactory deployed to: 0xb63881f0Be29506B28386781C8603910396C75E9 AlchemyTimelock deployed to: 0xCA2b3CF3989e70813719ac7703daF4B14f46b377 AlchemyGovernorAlpha deployed to: 0x9789D57093c66AF78C1AEb5CE19A10f963673f87 # Setup ## Install the dependencies ``` npm install ``` ## Testing The contracts can be tested by running the corresponding tests from the hardhat test folder with a total of 51 unit tests. ``` npx hardhat test ``` # maci-crypto This module implements abstractions over cryptographic functions which MACI employs. ## Types and interfaces **`PrivKey`**: A private key. **`PubKey`**: A public key. **`EcdhSharedKey`**: An Elliptic-curve Diffie–Hellman shared key. **`Plaintext`**: An array of unencrypted values. **`Ciphertext`**: Encrypted `Plaintext`. This data structure abstracts over the initialisation vector and encrypted data. **`Signature`**: A signature. This data structure abstracts over the`R8` and `S` values. ## Functions **`genPrivKey: PrivKey`** Returns a securely random private key. **`genPubKey = (privKey: PrivKey): PubKey `** Generates the public key associated with the given private key. **`genEcdhSharedKey = (privKey: PrivKey, pubKey: PubKey): EcdhSharedKey`** Generates an ECDH shared key. **`encrypt = (plaintext: Plaintext, sharedKey: EcdhSharedKey): Ciphertext`** Encrypts the plaintext with the given key and returns the associated ciphertext. **`decrypt = (ciphertext: Ciphertext, sharedKey: EcdhSharedKey): Plaintext`** Decrypts the ciphertext using the given key. **`sign = (privKey: PrivKey, message: Plaintext): Signature`** Produces a signature of the given message using the private key. **`verifySignature = (message: Plaintext, signature: Signature, publicKey: PubKey): boolean`** Checks whether the given signature is valid. # NearBridge TruffleFramework template with travis-ci.org and coveralls.io configured [![Build Status](https://travis-ci.org/nearprotocol/bridge.svg?branch=master)](https://travis-ci.org/nearprotocol/bridge) [![Coverage Status](https://coveralls.io/repos/github/nearprotocol/bridge/badge.svg?branch=master)](https://coveralls.io/github/nearprotocol/bridge?branch=master) # OpenCourt > Digital dispute resolution with OpenLaw [OpenLaw](https://lib.openlaw.io/web/default/template/OpenCourt) Mainnet: [0x1cec62223ad247288fa0e6cd16a61e90c3eedbfe](https://etherscan.io/address/0x1cec62223ad247288fa0e6cd16a61e90c3eedbfe#code) Rinkeby: [0x47E5f67066fa967af8bB7b85099617130898B1a5](https://rinkeby.etherscan.io/address/0x47E5f67066fa967af8bB7b85099617130898B1a5#code) #### Judge Membership Token - "OpenCourt Judge" - [0x0fd583A2161B08526008559dc9914613679ef68e](https://rinkeby.etherscan.io/address/0x0fd583a2161b08526008559dc9914613679ef68e#code) > [Rinkeby DAO](https://rinkeby.aragon.org/#/opencourt) #### Judgement Tracker Token: "OpenCourt Judgement" - [0x0776400cE11E99ff18293F65fD4d36EC50d7cd6a](https://rinkeby.etherscan.io/address/0x0776400ce11e99ff18293f65fd4d36ec50d7cd6a#code) > Granted to judges that issue verdicts on OpenCourt (Rinkeby) # `maci-core` This submodule assists with handling key business logic functions and processes. ## Overview One may conceive of MACI as a state machine with 1) data and 2) functions which transform said data. This makes it easier to reason about the system, write tests, and implement functionality. It also allows us to implement the smart contracts in discrete components which are easy to test. To this end, we this submodule exposes a `MaciState` class and a `User` class. ## **`User`** Each `User object has the following attributes: `pubKey: PubKey`: The user's public key. `votes: SnarkBigInt[]`: The voice credits assigned to each vote option. `voiceCreditBalance: SnarkBigInt`: The user's remaining voice credit balance. ### Functions #### **`genStateLeaf`** Function signature: ```ts (_voteOptionTreeDepth: number): StateLeaf ``` Generates and returns an equivalent `StateLeaf` [domain object](../domainobjs/). This function helps `MaciState` to generate a state tree. #### **`copy`** Function signature: ```ts (): User ``` Deep-copies and returns this object. ## `MaciState` We denote all state data as attributes of a `MaciState` object. Only the coordinator should have access to state data. Each user can only access their own keypair, commands, and on-chain state and message tree roots. `MaciState` contains the following attributes: `coordinatorKeypair: Keypair`: The coordinator's keypair. `users: User[]`: An array of `User` objects, each of which represents the current state of a user. `stateTreeDepth: SnarkBigInt`: The depth of the state tree. `messageTreeDepth: SnarkBigInt`: The depth of the message tree. `voteOptionTreeDepth: SnarkBigInt`: The depth of each user's vote option tree. `messages: Message[]`: An array of all published messages. `zerothStateLeaf: StateLeaf`: The leaf of the state tree at index 0. This means that the zeroth user in `users` has index 1 in the state tree. `maxVoteOptionIndex: SnarkBigInt`: The maximum allowed vote options. For instance, even if the vote option tree supports up to 16 vote options, this value can be set to 12 so as to enforce the fact that there are only 12 options to choose from. `encPubKeys: PubKey[]`: An array of public keys used to generate ephermeral ECDH shared keys with which to encrypt commands to messages. For each `PubKey` in `encPubKey`, its corresponding `Message` in `messages` shares the same array index. ### Functions The following functions modify the state: - `signUp()` - `publishMessage()` - `processMessage()` - `batchProcessMessage()` The following functions do not modify the state: - `copy()` - `genStateTree()` - `genStateRoot()` - `genMessageTree()` - `genMessageRoot()` - `computeCumulativeVoteTally()` - `genUpdateStateTreeCircuitInputs()` - `genBatchUpdateStateTreeCircuitInputs()` #### **`signUp`** Function signature: ```ts ( _pubKey: PubKey, _initialVoiceCreditBalance: SnarkBigInt, ): void ``` Appends a `User` with the specified public key and initial voice credit balance to the `users` array. #### **`publishMessage`** Function signature: ```ts ( _message: Message, _encPubKey: PubKey, ): void ``` Appends a `Message` to the `messages` array. It also appends the public key used to generate the ECDH shared key which encrypts `_message` to the `encPubKeys` array. #### **`processMessage`** Function signature: ```ts (_index: number): void ``` This function: 1. Generates a shared key using `encPubKeys[index]` and `coordinatorKeyPair.pubKey` 2. Decrypts `messages[_index]` to derive a `Command` 3. If the message is invalid, do nothing and return 4. If the message is valid, update the user's public key and vote at `_index`. #### **`batchProcessMessage`** Function signature: ```ts ( _index: number, _batchSize: number, _randomStateLeaf: StateLeaf, ): void ``` This function runs `processMessage()` on a batch of `_batchSize` leaves starting from index `_index`, and then replaces the zeroth leaf with `_randomStateLeaf`. **`genStateTree()`** Function signature: ```ts (): IncrementalMerkleTree ``` Generates and returns the state tree as an incremental Merkle tree. **`genStateRoot()`** Function signature: ```ts (): SnarkBigInt ``` This function computes the state root given the data stored in `users` and `zerothStateLeaf`. **`genMessageTree()`** Function signature: ```ts (): IncrementalMerkleTree ``` Generates and returns the message tree as an incremental Merkle tree. **`genMessageRoot()`** Function signature: ```ts (): SnarkBigInt ``` This function computes the state root given the data stored in `messsages`. **`genUpdateStateTreeCircuitInputs`** Function signature: ```ts genUpdateStateTreeCircuitInputs = (_index: number): object ``` Generates the circuit inputs (both public and private) for the `UpdateStateTree` circuit, as an object with the following attributes: - `coordinator_public_key` - `ecdh_private_key` - `ecdh_public_key` - `message` - `msg_tree_root` - `msg_tree_path_elements` - `msg_tree_path_index` - `vote_options_leaf_raw` - `vote_options_tree_root` - `vote_options_tree_path_elements` - `vote_options_tree_path_index` - `vote_options_max_leaf_index` - `state_tree_data_raw` - `state_tree_max_leaf_index` - `state_tree_root` - `state_tree_path_elements` - `state_tree_path_index` **`genBatchUpdateStateTreeCircuitInputs`** Function signature: ```ts genBatchUpdateStateTreeCircuitInputs = ( _index: number, _batchSize: number, _randomStateLeaf: StateLeaf, ) => object ``` Generates the circuit inputs (both public and private) for the `BatchUpdateStateTree` circuit, as an object with the following attributes: - `coordinator_public_key` - `message` - `ecdh_private_key` - `ecdh_public_key` - `msg_tree_root` - `msg_tree_path_elements` - `msg_tree_batch_start_index` - `random_leaf` - `state_tree_root` - `state_tree_path_elements` - `state_tree_path_index` - `random_leaf_root` - `random_leaf_path_elements` - `vote_options_leaf_raw` - `state_tree_data_raw` - `state_tree_max_leaf_index` - `vote_options_max_leaf_index` - `vote_options_tree_root` - `vote_options_tree_path_elements` - `vote_options_tree_path_index` **`genQuadVoteTallyCircuitInputs`** Function signature: ```ts genQuadVoteTallyCircuitInputs = ( _startIndex: SnarkBigInt, _batchSize: SnarkBigInt, _currentResultsSalt: SnarkBigInt, _newResultsSalt: SnarkBigInt, ): object ``` Generates the circuit inputs (both public and private) for the `QuadVoteTally` circuit, as an object with the following attributes: - `voteLeaves` - `stateLeaves` - `currentResults` - `fullStateRoot` - `currentResultsSalt` - `newResultsSalt` - `currentResultsCommitment` - `intermediatePathElements` - `intermediatePathIndex` - `intermediateStateRoot` **`copy()`** Function signature: ```ts (): MaciState ``` This function returns a deep-copied `MaciState` object. # Graph Node [![Build Status](https://travis-ci.org/graphprotocol/graph-node.svg?branch=master)](https://travis-ci.org/graphprotocol/graph-node) [![Getting Started Docs](https://img.shields.io/badge/docs-getting--started-brightgreen.svg)](docs/getting-started.md) [The Graph](https://thegraph.com/) is a protocol for building decentralized applications (dApps) quickly on Ethereum and IPFS using GraphQL. Graph Node is an open source Rust implementation that event sources the Ethereum blockchain to deterministically update a data store that can be queried via the GraphQL endpoint. For detailed instructions and more context, check out the [Getting Started Guide](docs/getting-started.md). ## Quick Start ### Prerequisites To build and run this project you need to have the following installed on your system: - Rust (latest stable) – [How to install Rust](https://www.rust-lang.org/en-US/install.html) - PostgreSQL – [PostgreSQL Downloads](https://www.postgresql.org/download/) - IPFS – [Installing IPFS](https://docs.ipfs.io/install/) For Ethereum network data, you can either run your own Ethereum node or use an Ethereum node provider of your choice. ### Running a Local Graph Node This is a quick example to show a working Graph Node. It is a [subgraph for the Ethereum Name Service (ENS)](https://github.com/graphprotocol/ens-subgraph) that The Graph team built. 1. Install IPFS and run `ipfs init` followed by `ipfs daemon`. 2. Install PostgreSQL and run `initdb -D .postgres` followed by `pg_ctl -D .postgres -l logfile start` and `createdb graph-node`. 3. If using Ubuntu, you may need to install additional packages: - `sudo apt-get install -y clang libpq-dev libssl-dev pkg-config` 4. In the terminal, clone https://github.com/graphprotocol/ens-subgraph, and install dependencies and generate types for contract ABIs: ``` yarn yarn codegen ``` 5. In the terminal, clone https://github.com/graphprotocol/graph-node, and run `cargo build`. Once you have all the dependencies set up, you can run the following: ``` cargo run -p graph-node --release -- \ --postgres-url postgresql://USERNAME[:PASSWORD]@localhost:5432/graph-node \ --ethereum-rpc [URL] \ --ipfs 127.0.0.1:5001 ``` Try your OS username as `USERNAME` and `PASSWORD`. The password might be optional. It depends on your setup. This will also spin up a GraphiQL interface at `http://127.0.0.1:8000/`. 6. With this ENS example, to get the subgraph working locally run: ``` yarn create-local ``` Then you can deploy the subgraph: ``` yarn deploy-local ``` This will build and deploy the subgraph to the Graph Node. It should start indexing the subgraph immediately. ### Command-Line Interface ``` USAGE: graph-node [FLAGS] [OPTIONS] --ethereum-ipc <NETWORK_NAME:FILE> --ethereum-rpc <NETWORK_NAME:URL> --ethereum-ws <NETWORK_NAME:URL> --ipfs <HOST:PORT> --postgres-url <URL> FLAGS: --debug Enable debug logging -h, --help Prints help information -V, --version Prints version information OPTIONS: --admin-port <PORT> Port for the JSON-RPC admin server [default: 8020] --elasticsearch-password <PASSWORD> Password to use for Elasticsearch logging [env: ELASTICSEARCH_PASSWORD] --elasticsearch-url <URL> Elasticsearch service to write subgraph logs to [env: ELASTICSEARCH_URL=] --elasticsearch-user <USER> User to use for Elasticsearch logging [env: ELASTICSEARCH_USER=] --ethereum-ipc <NETWORK_NAME:[CAPABILITIES]:FILE> Ethereum network name (e.g. 'mainnet'), optional comma-seperated capabilities (eg full,archive), and an Ethereum IPC pipe, separated by a ':' --ethereum-polling-interval <MILLISECONDS> How often to poll the Ethereum node for new blocks [env: ETHEREUM_POLLING_INTERVAL=] [default: 500] --ethereum-rpc <NETWORK_NAME:[CAPABILITIES]:URL> Ethereum network name (e.g. 'mainnet'), optional comma-seperated capabilities (eg 'full,archive'), and an Ethereum RPC URL, separated by a ':' --ethereum-ws <NETWORK_NAME:[CAPABILITIES]:URL> Ethereum network name (e.g. 'mainnet'), optional comma-seperated capabilities (eg `full,archive), and an Ethereum WebSocket URL, separated by a ':' --http-port <PORT> Port for the GraphQL HTTP server [default: 8000] --ipfs <HOST:PORT> HTTP address of an IPFS node --node-id <NODE_ID> a unique identifier for this node [default: default] --postgres-url <URL> Location of the Postgres database used for storing entities --subgraph <[NAME:]IPFS_HASH> name and IPFS hash of the subgraph manifest --ws-port <PORT> Port for the GraphQL WebSocket server [default: 8001] ``` ### Advanced Configuration The command line arguments generally are all that is needed to run a `graph-node` instance. For advanced uses, various aspects of `graph-node` can further be configured through [environment variables](https://github.com/graphprotocol/graph-node/blob/master/docs/environment-variables.md). Very large `graph-node` instances can also split the work of querying and indexing across [multiple databases](./docs/sharding.md). ## Project Layout - `node` — A local Graph Node. - `graph` — A library providing traits for system components and types for common data. - `core` — A library providing implementations for core components, used by all nodes. - `chain/ethereum` — A library with components for obtaining data from Ethereum. - `graphql` — A GraphQL implementation with API schema generation, introspection, and more. - `mock` — A library providing mock implementations for all system components. - `runtime/wasm` — A library for running WASM data-extraction scripts. - `server/http` — A library providing a GraphQL server over HTTP. - `store/postgres` — A Postgres store with a GraphQL-friendly interface and audit logs. ## Roadmap 🔨 = In Progress 🛠 = Feature complete. Additional testing required. ✅ = Feature complete | Feature | Status | | ------- | :------: | | **Ethereum** | | | Indexing smart contract events | ✅ | | Handle chain reorganizations | ✅ | | **Mappings** | | | WASM-based mappings| ✅ | | TypeScript-to-WASM toolchain | ✅ | | Autogenerated TypeScript types | ✅ | | **GraphQL** | | | Query entities by ID | ✅ | | Query entity collections | ✅ | | Pagination | ✅ | | Filtering | ✅ | | Entity relationships | ✅ | | Subscriptions | ✅ | ## Contributing Please check [CONTRIBUTING.md](CONTRIBUTING.md) for development flow and conventions we use. Here's [a list of good first issues](https://github.com/graphprotocol/graph-node/labels/good%20first%20issue). ## License Copyright &copy; 2018-2019 Graph Protocol, Inc. and contributors. The Graph is dual-licensed under the [MIT license](LICENSE-MIT) and the [Apache License, Version 2.0](LICENSE-APACHE). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied. See the License for the specific language governing permissions and limitations under the License. <div align="center"> <h1><code>Rainbow Bridge CLI</code></h1> <p> <strong>OPS tool to Rainbow Bridge, an Ethereum to Near trustless, fully decentralized, bidirectional bridge</strong> </p> <p> <a href="https://buildkite.com/nearprotocol/rainbow-bridge-cli"><img src=" https://badge.buildkite.com/93478642b0ddf8e3548c16d2e60c4adbca4fd853520b6a5bca.svg?branch=master" alt="Buildkite Build" /></a> <a href="https://npmjs.com/rainbow-bridge-cli"><img alt="npm" src="https://img.shields.io/npm/v/rainbow-bridge-cli.svg?style=flat-square"></a> </p> </div> ## Table of Contents - [Pre-requisites](#pre-requisites) - [Usage](#usage) - [Security](#security) - [Gas costs](#gas-costs) - [Using Bridge on Testnet](#using-bridge-on-testnet) - [Deploying and Using Locally](#deploying-and-using-locally) - [Contract Development Workflow](#contract-development-workflow) ## Pre-requisites The current version of CLI is all-in-one package -- it is used both for production and testing. As a result, even if you need CLI only for the token transfer you need to install all testing dependencies. This will be changed in the future. - Install golang, [see](https://golang.org/dl/). - Make sure you are using Node with version >=10 and <=13. We recommend using [nvm](https://github.com/nvm-sh/nvm) for installing node and npm, if you already don't have one. This constraint will be removed soon; - yarn - docker, for deterministic compile rust contracts - bash, for preparation steps (needs to be re-implemented in JS) ### If you want to test with a local near node: - You would also need to install resources needed to compile nearcore (in the future this will only be required for the testing CLI): ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env rustup default stable rustup target add wasm32-unknown-unknown ``` - Then install dependencies needed for the compilation of nearcore, [see](https://docs.near.org/docs/local-setup/running-testnet#compiling-and-running-official-node-without-docker). - python3 pip , for nearup #### Install nearup ```bash pip3 install nearup ``` ## Usage Clone this repo, `yarn install`, then to learn the commands that you can use with the rainbow bridge run: ``` cli/index.js --help ``` Parameters of each command can be specified through environment variables, command line arguments, entries in the `~/.rainbow/config.json` config file, or the default value will be used -- in that priority. If argument is not provided and there is no default value the program will not execute. If script successfully executes a command then each parameter provided through the command line argument will be written into the config file. Additionally, if scripts generates new parameters (e.g. it deploys a contract to Ethereum and obtains its address) will also be written into the config file. Arguments should not be specified multiple times. Note, you can use environment variables to pass sensitive data which will not lead to it being written into the config file. ## Security Bridge is secure as long as majority (1/2) of Etherem mining power is honest and supermajority (2/3) of NEAR stake is honest. There are no additional security requirements, except that Ethereum should be able to accept 1 transaction within 4 hour period even in the worst congestion scenario. ## Gas costs NEAR fees are negligible, both for bridge maintenance and for token transfer. Ethereum fees are the following: - To transfer ERC20 token from ETH to NEAR: Approx 43,989 gas to set allowance and approx 37,407 gas to lock it; - To transfer ERC20 token back from NEAR to ETH: Approx 240,531 gas to unlock the token; - To submit a NEAR block header: approx 697,140 gas; - To challenge a NEAR block header: approx 700k gas. As of 2020-07-14 (gas price is 40 gwei) the cost of running bridge on NEAR mainnnet and Ethereum mainnet is approx 42 USD/day. The cost of ETH->NEAR transfer of ERC20 token is 1 USD. The cost of NEAR->ETH transfer of ERC20 token is 2 USD. ## Using Bridge on Testnet ### PoA vs PoW Ethereum networks Rainbow bridge can be deployed either on PoW or PoA networks. However, the main use case of the bridge is Ethereum Mainnet, which makes its design very PoW-centric and it is only trustless and decentralized for PoW networks. Unfortunately, the only popular PoW testnet is Ropsten, which frequently undergoes huge reorgs of more than [16k blocks](https://github.com/near/rainbow-bridge-cli/issues/329), because people test 51% attacks on it. 16k reorgs can wipe out entire contracts and revert days of computations. Overall, Ropsten has the following unfortunate specifics that does not exist with Ethereum Mainnet: * Extremely long re-orgs; * Gas price volatility -- Ropsten blocks might have orders of magnitude different median gas price; * Slow block production -- sometimes Ropsten blocks are produced once per several minutes; * [Infura is unreliable on Ropsten](https://github.com/near/rainbow-bridge-cli/issues/330) Therefore we advise users to not use Ropsten for bridge testing. Instead, we recommend using one of Ethereum's PoA testnet. Unfortunately, PoA networks have a differen header format and are also centralized by nature. Therefore when deploying bridge on PoA network please use `--near-client-trusted-signer` parameter. This will force `EthOnNearClient` to not validate Ethereum headers (since PoA headers are not valid PoW headers) and accept them only from the provided authority. The documenation below assumes Rinkeby testnet. ### Using existing bridge on Rinkeby This section explains how to use existing bridge with mock ERC20 token that was already deployed. You would need to have some amount of this token on Rinkeby, so reach out to [email protected] if you want to give it a try. We assume you have two accounts: * One NEAR account on NEAR testnet with at least 1 NEAR token. We denote it as `<near_token_holder_account>` and its secret key as `<near_token_holder_sk>`; * One Ethereum account on Rinkeby testnet with at least 1 ETH and 100 ERC20 tokens (this example uses ERC20 deployed to `0x8151a8F90267bFf183E06921841C5dE774499388` as an example. If you want some of these ERC20 tokens please contact [email protected]). We denote it as `<eth_token_holder_address>` and its private key as `<eth_token_holder_sk>`; Make sure you have rainbow cli installed: ```bash yarn install ``` If you have already used the bridge on this machine run a cleanup: ```bash cli/index.js clean ``` If you're using rainbow-bridge-cli 1.x, create `~/.rainbow/config.json` file with the following content: ```json { "nearNetworkId": "testnet", "nearNodeUrl": "https://rpc.testnet.near.org/", "ethNodeUrl": "https://rinkeby.infura.io/v3/<project_id>", "nearMasterAccount": "<near_token_holder_account>", "nearMasterSk": "<near_token_holder_sk>", "nearClientAccount": "ethonnearclient10", "nearProverAccount": "ethonnearprover10", "nearClientTrustedSigner": "eth2nearrelay10.testnet", "ethMasterSk": "<eth_token_holder_sk>", "ethEd25519Address": "0x9003342d15B21b4C42e1702447fE2f39FfAF55C2", "ethClientAddress": "0xF721c979db97413AA9D0F91ad531FaBF769bb09C", "ethProverAddress": "0xc5D62d66B8650E6242D9936c7e50E959BA0F9E37", "ethErc20Address": "0x8151a8F90267bFf183E06921841C5dE774499388", "ethLockerAddress": "0x5f7Cc23F90b5264a083dcB3b171c7111Dc32dD00", "nearFunTokenAccount": "mintablefuntoken11" } ``` If you are using rainbow-bridge-cli 2.x, create `~/.rainbow/config.json` file with the following content: ```json { "nearNetworkId": "testnet", "nearNodeUrl": "https://rpc.testnet.near.org/", "ethNodeUrl": "https://rinkeby.infura.io/v3/<project_id>", "nearMasterAccount": "<near_token_holder_account>", "nearMasterSk": "<near_token_holder_sk>", "nearClientAccount": "ethonnearclient10", "nearProverAccount": "ethonnearprover10", "nearClientTrustedSigner": "eth2nearrelay10.testnet", "ethMasterSk": "<eth_token_holder_sk>", "ethEd25519Address": "0x9003342d15B21b4C42e1702447fE2f39FfAF55C2", "ethClientAddress": "0xF721c979db97413AA9D0F91ad531FaBF769bb09C", "ethProverAddress": "0xc5D62d66B8650E6242D9936c7e50E959BA0F9E37", "nearTokenFactoryAccount": "ntf4.bridge2.testnet", "ethErc20Address": "0x21e7381368baa3f3e9640fe19780c4271ad96f37", "ethLockerAddress": "0x7f66c116a4f51e43e7c1c33d3714a4acfa9c40fb", "nearErc20Account": "21e7381368baa3f3e9640fe19780c4271ad96f37.ntf4.bridge2.testnet" } ``` You can get infura project id, by registering at [infura.io](http://infura.io/). To transfer ERC20 from ETH to NEAR run: ```bash cli/index.js TESTING transfer-eth-erc20-to-near --amount 10 --eth-sender-sk <eth_token_holder_address> --near-receiver-account <near_token_holder_account> ``` (If the command interrupts in the middle re-run it and it will resume the transfer. PoA RPC sometimes has issues) Wait for the transfer to finish. You should see: ``` Transferred Balance of <near_token_holder_account> after the transfer is 10 ``` To transfer ERC20 back from NEAR to ETH run: ```bash cli/index.js TESTING transfer-eth-erc20-from-near --amount 1 --near-sender-account <near_token_holder_account> --near-sender-sk <near_token_holder_sk> --eth-receiver-address <eth_token_holder_address> ``` You should see: ``` ERC20 balance of <eth_token_holder_address> after the transfer: 91 ``` Congratulations, you have achieved a roundtrip of ERC20 token through the bridge! <!--- ### Deploying new bridge If you used bridge before from your machine, then clean up the setup. We recommend using cloud instance for deploying and running the bridge. Go to a cloud instance and install dependencies from [Pre-requisites](#pre-requisites). Then run: ```bash cli/index.js clean cli/index.js prepare ``` Then initialize `EthOnNearClient` and `EthOnNearProver`: ```bash cli/index.js init-near-contracts --near-network-id testnet --near-node-url <testnet_nodes_url> --eth-node-url https://ropsten.infura.io/v3/<infura_project_id> --near-master-account <near_master_account> --near-master-sk <near_master_sk> --near-client-account ethonnearclient01 --near-client-init-balance 2000000000000000000000000000 --near-prover-account ethonnearprover01 ``` * Make sure `ethonnearclient01` and `ethonnearprover01` do not exist yet. You can check it by going to https://explorer.testnet.near.org/accounts/ethonnearclient01 and https://explorer.testnet.near.org/accounts/ethonnearprover01 . If they exist, pick different names; * You can get `<infura_project_id>` by creating a free [infura](http://infura.io/) account. If you are working in NEAR organization please ask [email protected]; * For `<testnet_nodes_url>` you can use `http://rpc.testnet.near.org/`. If you are working in NEAR organization please ask [email protected]; Then start `eth2near-relay`: ```bash node index.js start eth2near-relay --near-master-account <eth2nearrelay_account> --near-master-sk <eth2nearrelay_sk> ``` Now initialize `NearOnEthClient` and `NearOnEthProver`: ```bash node index.js init-eth-ed25519 --eth-master-sk <eth_master_sk> node index.js init-eth-client --eth-client-lock-eth-amount 100000000000000000 --eth-client-lock-duration 600 node index.js init-eth-prover ``` This will set the bond to 0.1 ETH and challenge period to 10 minutes. **Do not use these settings on Mainnet!** Mainnet should be using 20ETH bond and 4 hour challenge period. Then start the `near2eth-relay` and watchdog: ```bash node index.js start near2eth-relay --eth-master-sk <near2ethrelay_sk> node index.js start bride-watchdog --eth-master-sk <watchdog_sk> ``` --> ## Deploying and Using Locally To locally test the bridge run: ```bash cli/index.js clean cli/index.js prepare cli/index.js start near-node cli/index.js start ganache ``` ### Initializing the contracts First let's initialize the contracts that bridge needs to function: ```bash cli/index.js init-near-contracts cli/index.js init-eth-ed25519 cli/index.js init-eth-client --eth-client-lock-eth-amount 1000 --eth-client-lock-duration 10 cli/index.js init-eth-prover ``` Now, let's set up token on Ethereum blockchain that we can transfer to NEAR blockchain (this can be your own token). ```bash cli/index.js init-eth-erc20 cli/index.js init-eth-locker ``` Now, let's initialize token factory on NEAR blockchain. ```bash cli/index.js init-near-token-factory ``` ### Starting the services Now start the services that will relay the information between the chains: ```bash cli/index.js start eth2near-relay cli/index.js start near2eth-relay --eth-master-sk 0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501201 cli/index.js start bridge-watchdog --eth-master-sk 0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501202 ``` Note, you can observe the logs of the relays by running: ```bash pm2 logs ``` ### Transferring tokens Let's check the balance of bridged tokens from ETH to NEAR before starting the transfer. To this end let's use `node0` account, which is automatically created and funded on startup when localnet is started. ```bash cli/index.js TESTING get-bridge-on-near-balance --near-receiver-account node0 ``` Then transfer some tokens with: ```bash cli/index.js TESTING transfer-eth-erc20-to-near --amount 1000 --eth-sender-sk 0x2bdd21761a483f71054e14f5b827213567971c676928d9a1808cbfa4b7501200 --near-receiver-account node0 --near-master-account neartokenfactory ``` Now you check the balance of `node0` again. You should notice the balance was changed. Note, when we deployed ERC20 to the Ethereum blockchain we have minted a large number of tokens to the default master key of Ganache, so we have transferred ERC20 tokens from it to `node0` account. Notice that we are using `neartokenfactory` account here to pay for the NEAR gas fees, any account for which we know a secret key would've worked too. You must observe blocks being submitted. You can also manually check the ERC20 balance of the receiver before and after receiving the transfer back from the NEAR side ```bash cli/index.js TESTING get-erc20-balance 0xEC8bE1A5630364292E56D01129E8ee8A9578d7D8 ``` Now let's try to transfer one token back to Ethereum ```bash cli/index.js TESTING transfer-eth-erc20-from-near --amount 1 --near-sender-account node0 --near-sender-sk ed25519:3D4YudUQRE39Lc4JHghuB5WM8kbgDDa34mnrEP5DdTApVH81af7e2dWgNPEaiQfdJnZq1CNPp5im4Rg5b733oiMP --eth-receiver-address 0xEC8bE1A5630364292E56D01129E8ee8A9578d7D8 ``` You should observe the change of the ERC20 balance as reported by the CLI. ### Stopping the services To stop relay services and node clients execute the following command: ```bash cli/index.js stop all ``` Or you can stop them one by one using these commands: ```bash cli/index.js stop near-node cli/index.js stop ganache cli/index.js stop eth2near-relay cli/index.js stop near2eth-relay cli/index.js stop bridge-watchdog ``` ## Contract Development Workflow Above steps are ways to run a local bridge and development workflows you need if make any changes to rainbow-bridge-cli. If you want to update any of solidity or rust contracts, they're not in this repo now and workflow is as following. - Install dependencies: ```bash cli/index.js clean cli/index.js prepare ``` - Start local NEAR network and Ganache ```bash cli/index.js near-node cli/index.js ganache ``` - If you want to modify solidity contracts, go to `node_modules/rainbow-bridge-sol`, make changes there and run `./build_all.sh` to recompile solidity contracts. - If you want to modify rust contracts, go to `node_modules/ranbow-bridge-rs`, make changes there and run `./build_all.sh` to recompile rust contracts. - If you want to modify rainbow bridge lib, go to `node_modules/rainbow-bridge-lib` and make changes there - Follow instructions above to init eth contracts and near contracts, start services and start testing with bridge - For changes to Solidity contract, Rust contract, and rainbow-bridge-lib, please submit PRs to: https://github.com/near/rainbow-bridge-sol , https://github.com/near/rainbow-bridge-rs , and https://github.com/near/rainbow-bridge-lib respectively. - After PR merged in contract repos and rainbow-bridge-lib repo, we will periodically publish them as new version of npm packages. And rainbow-bridge-cli will adopt new version of them. <!--- The following is outdated. # Docker: ## Currently we have the following docker options: 1. Rainbow Docker image containing rainbow ready for running - run the rainbow docker image with a custom command 2. A development docker compose setup (docker-compose-dev.yml) - ganache - local near node - eth2near-relay 3. A production docker compose setup (docker-compose-prod.yml) - eth2near-relay ## Running the docker setup: 1. One options is to adapt the current config.json specified in the root folder of the project and build a new image. 2. Specifying the configuration flags through environment variables. We recommend a usage of both, encouraging using the config.json for common configurations, while passing the secrets through environment variables. Examples: ``` # Creating a docker image docker build . # Running the development env with config setup docker-compose up # Running the development env with ENV overrides docker-compose -f docker-compose-dev.yml up -e MASTER_SK=<key> -e ... # Running the production env just use: docker-compose -f docker-compose-prod.yml instead ``` --> # Implementation Notes The files in this directory explain some higher-level concepts about the implementation of `graph-node`. Explanations that are tied more closely to the code should go into comments. * [Schema Generation](./schema-generation.md) * [Time-travel Queries](./time-travel.md) * [SQL Query Generation](./sql-query-generation.md)
ngocthach_near-dapp-example
.gitpod.yml README.md contract Cargo.toml README.md neardev dev-account.env src lib.rs frontend App.js assets global.css logo-black.svg logo-white.svg index.html index.js near-api.js near-config.js package-lock.json package.json ui-components.js integration-tests Cargo.toml src tests.rs package-lock.json package.json
Hello NEAR! ================================= A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. 2. There are two functions to the smart contract: `get_greeting` and `set_greeting`. 3. Tests: You can run smart contract tests with the `cargo test`. [smart contract]: https://docs.near.org/develop/welcome [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://docs.near.org/develop/prerequisites#rust-and-wasm [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html Install cargo-watch to debug =========================== cargo install cargo-watch cargo watch -x check -x test -x run near-blank-project ================== This app was initialized with [create-near-app] npx create-near-app \ near-dapp-example \ --contract rust \ --frontend react \ --tests rust \ --install Quick Start =========== If you haven't installed dependencies during setup: npm run deps-install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
gautamprikshit1_near-beginner
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
jorgeavaldez_near-protocol-adapter
.eslintrc.js .github workflows ci-workflow.yml .prettierrc.js .vim coc-settings.json .vscode extensions.json settings.json .yarn sdks eslint bin eslint.js lib api.js package.json integrations.yml prettier index.js package.json typescript lib tsc.js tsserver.js typescript.js package.json .yarnrc.yml LICENCE.md README.md package.json src adapter.ts app.ts config.ts errors.ts global.d.ts index.ts near config.ts index.ts single_key_store.ts test app.test.ts config.test.ts near config.test.ts tsconfig.json
# NEAR Protocol Write Adapter This service is used by a Chainlink node as an external adapter for writing to [NEAR Blockchain](https://near.org/). The external adapter allows you to configure an endpoint, account and private key to sign and send transactions. ## Prerequisite - Yarn v1.22+: You will need to have [Yarn v1.22+ installed](https://yarnpkg.com/getting-started/install) locally. - This repo also activates the Berry release (codename for the Yarn 2), disabled by default. - To switch between versions use the `yarnPath` release path in [.yarnrc.yml](.yarnrc.yml) file, and run `yarn install` because of differences in `yarn.lock` file. - Node v12+: [n](https://github.com/tj/n) is a great interactive manager for your Node.js versions. ## Install If using Yarn v1.22+ (default), or when switching between versions (from v1.22+ -> v2, and back), please run: ```bash yarn install ``` ## Set up NEAR accout ### Prerequisite - NEAR account: Please create one with [NEAR Wallet](https://wallet.nearprotocol.com). - NEAR CLI: Please install it following the [NEAR docs instructions](https://docs.near.org/docs/development/near-cli). ### NEAR login In the project root, login with `near-cli` by following the instructions after this command: ```bash near login ``` This step is required to get to the NEAR account private key which can be found at `~/.near-credentials/default/${ACCOUNT_ID}.json`: ```json { "account_id": "${ACCOUNT_ID}", "private_key": "ed25519:..." } ``` ## Start Supported environment variables: - ACCOUNT_ID: NEAR account that this service will use - PRIVATE_KEY: NEAR account private key - PORT: (optional) defaults to `3000` - NODE_ENV: (optional) one of `[production|mainnet|development|testnet|devnet|betanet|local]`, defaults to `development` - NETWORK_ID: (optional) custom network id, `NODE_URL` must also be set - NODE_URL: (optional) custom node url, `NETWORK_ID` must also be set Set the required environment, and run from the project root: ```bash yarn start ``` Alternatively you can set the environment inline: ```bash env \ ACCOUNT_ID=dummy.testnet \ PRIVATE_KEY=ed25519:3Zo9bWRC7vUoDHMaXdMd6osajUktbgGWxL3P89QxR8VguVPnFa7BXd5brw6tBa6RASn8YCVjPgkhpujnorCF7FR2 \ NODE_ENV=testnet \ yarn start ``` Or for a custom connection: ```bash env \ ACCOUNT_ID=dummy.acmenet \ PRIVATE_KEY=ed25519:3Zo9bWRC7vUoDHMaXdMd6osajUktbgGWxL3P89QxR8VguVPnFa7BXd5brw6tBa6RASn8YCVjPgkhpujnorCF7FR2 \ NETWORK_ID=acmenet \ NODE_URL=https://rpc.acmenet.acme.org \ yarn start ``` This service can be started as a standalone service or as a **[Chainlink node adapter](#chainlink-node-integration)**. ## API The standalone service exposes all endpoints discussed next, while the service started as a [Chainlink node adapter](#chainlink-node-integration) exposes just one endpoint `POST /call`, but it's mapped as root endpoint `POST /`. ### HTTP `GET /` endpoint Read NEAR network connection status. Output: ```json { "chain_id": "testnet", "latest_protocol_version": 22, "protocol_version": 22, "rpc_addr": "0.0.0.0:3030", "sync_info": { "latest_block_hash": "7nWiri3qx9G2h2qG2KCX9N2ChDPDgWjgzo5V31HTMxxf", "latest_block_height": 7626572, "latest_block_time": "2020-06-25T10:36:40.696884241Z", "latest_state_root": "FMwXSxgkgvtxdMZaHMrsLsZVKcxDJi2mBk9nbrz4CxWN", "syncing": false }, "validators": [ { "account_id": "bisontrails.stakingpool", "is_slashed": false }, ... // more validators ], "version": { "build": "ebe21b33", "version": "1.0.0" } } ``` ### HTTP `GET /account` endpoint Read configured NEAR account. Output: ```json { "accessKey": "ed25519:6J9NoFmr4mzBLch3tzKDfetY4YVNGQG74urLHeUDfCcw", "accountId": "krebernisak_1.testnet" } ``` ### HTTP `GET /view` endpoint Read contract state from NEAR network. Input: - `contractId`: account where the contract is deployed - `methodName`: function name to call on the contract - `args`: (optional) function arguments ```json { "contractId": "counter.testnet", "methodName": "getCounter" } ``` Output: ```json { "data": ..., // View function output data "statusCode": 200 } ``` ### HTTP `POST /call` endpoint **Available as `POST /` when started as Chainlink node adapter** Send transaction and write state to the NEAR network. Input: - `contractId`: account where the contract is deployed - `methodName`: function name to call on the contract - `args`: (optional) function arguments - `gas`: (optional) gas amount allocated for transaction execution - `amount`: (optional) amount of NEAR sent with the transaction ```json { "contractId": "counter.testnet", "methodName": "decrementCounter", "args": { "value": 13 }, "gas": 5000000000000, "amount": 50 } ``` Output: ```json { "data": { ... // Transaction result data }, "statusCode": 200 } ``` ### Errors API will return a `HTTP 400` for client errors: ```json { "message": "Missing required fields: contractId or methodName", "status": "BadRequest", "statusCode": 400, "type": "UntypedError" } ``` Or `HTTP 500` for server errors: ```json { "message": "Exceeded the prepaid gas", "status": "Error", "statusCode": 500, "type": "GasExceeded" } ``` ## Test ### Unit tests Run from the project root: ```bash yarn test ``` ### Integration tests #### Step 1: Deploy contract to NEAR network For this test we are going to use [NEAR counter example](https://github.com/near-examples/counter) deployed to `@counter.testnet`. Please follow their instructions to: - Set up a new NEAR account where the contract will be deployed - Login to NEAR CLI with your new account - Deploy the contract #### Step 2: Interact with contracts To interact with the contracts, we are going to use [HTTPie](https://httpie.org/), a user-friendly command-line HTTP client, as an alternative to CURL. Make sure the counter contract is deployed and the adapter service is started. ##### Read contract state Use the `/view` endpoint to read contract state: ```bash echo '{"contractId": "counter.testnet", "methodName": "getCounter"}' | http GET :3000/view ``` Example output: ```json { "data": 0, "statusCode": 200 } ``` ##### Write contract state Use the `/call` endpoint to write contract state: ```bash echo '{"contractId": "counter.testnet", "methodName": "incrementCounter", "args": {"value": 4}}' | http POST :3000/call ``` The `/call` endpoint also lets you control the `gas` and `amount` sent to the contract: ```bash echo '{"contractId": "counter.testnet", "methodName": "decrementCounter", "args": {"value": 13}, "gas": 5000000000000, "amount": 50}' | http POST :3000/call ``` Example output: ```json { "data": { "receipts_outcome": [ { "block_hash": "9fdLpAdoPKoxwETaycVvwT5Lm2zy28fLGPKj2f4pkAVP", "id": "DeJ1GKwsRTfW63DBJBnAZPC4T8mnVgkkpvconBtfsWzM", "outcome": { "gas_burnt": 2757914274712, "logs": ["Counter is now: -9"], "receipt_ids": ["FeGwwskgZ95NQ6Pg9z745uq8sRJyyw83xYEXfJP4qoCe"], "status": { "SuccessValue": "" } }, "proof": [] }, { "block_hash": "HEs6d5HkTCojADaw2DHJgXMEBGNkn3GuLfNDVjWqV3Qx", "id": "FeGwwskgZ95NQ6Pg9z745uq8sRJyyw83xYEXfJP4qoCe", "outcome": { "gas_burnt": 0, "logs": [], "receipt_ids": [], "status": { "SuccessValue": "" } }, "proof": [] } ], "status": { "SuccessValue": "" }, "transaction": { "actions": [ { "FunctionCall": { "args": "eyJ2YWx1ZSI6MTN9", "deposit": "50", "gas": 5000000000000, "method_name": "decrementCounter" } } ], "hash": "EGMf4L6YvinLpjeCbfVVVXEPcfRMZ2HrvcHbDfiNiRMN", "nonce": 37, "public_key": "ed25519:6J9NoFmr4mzBLch3tzKDfetY4YVNGQG74urLHeUDfCcw", "receiver_id": "counter.testnet", "signature": "ed25519:21zN5PZKVueb79oUwKMkhshrwqw7uGzh7vgGCqkr8K1CF5XL6G6NtciYyU4xochHFXm4WY3pcHACPfnKUXSh7EvU", "signer_id": "krebernisak_1.testnet" }, "transaction_outcome": { "block_hash": "GDZGu1P2Ff983WgiVuDkMVULZs5ED85L99TJaQE62pyL", "id": "EGMf4L6YvinLpjeCbfVVVXEPcfRMZ2HrvcHbDfiNiRMN", "outcome": { "gas_burnt": 2427983606152, "logs": [], "receipt_ids": ["DeJ1GKwsRTfW63DBJBnAZPC4T8mnVgkkpvconBtfsWzM"], "status": { "SuccessReceiptId": "DeJ1GKwsRTfW63DBJBnAZPC4T8mnVgkkpvconBtfsWzM" } }, "proof": [] } }, "statusCode": 200 } ``` ## Chainlink node integration The Chainlink node expects a specific adapter API - we only expose the call function (send tx) on `/` endpoint. Chainlink adapter requires and supports additional environment variables: - CONTRACT_ID: NEAR account where the contract is deployed - METHOD_NAME: Method name that will be called by the adapter - GAS: (optional) Gas sent with the transaction, defaults to `300000000000000` - AMOUNT: (optional) Amount sent with the transaction, defaults to `0` To start the service as Chainlink node adapter: ```bash env \ NODE_ENV=testnet \ PORT=3000 \ ACCOUNT_ID=dummy.testnet \ PRIVATE_KEY=ed25519:3Zo9bWRC7vUoDHMaXdMd6osajUktbgGWxL3P89QxR8VguVPnFa7BXd5brw6tBa6RASn8YCVjPgkhpujnorCF7FR2 \ CONTRACT_ID=oracle.oracle.testnet \ METHOD_NAME=fulfill_request \ yarn start:adapter ``` In this configuration the `/` endpoint connects directly to [NEAR oracle contract](https://github.com/smartcontractkit/near-protocol-contracts/), and expects a slightly different input. We need to include the job spec id: ```json { "id": 1, // job spec id "data": {...} // input to our call function (specified in the env) } ``` Example for adapter set up to call the `fulfill_request` function: ```json echo '{"id": 1, "data": {"nonce":"1", "account": "client.oracle.testnet", "value": 17}}' | http POST :3000/ ``` Output: ```json { "data": { "result": "6yTpkCW3UqVtpGj766Wvr73zEambzL2n44CDYiB4TpVP" // tx hash }, "jobRunID": 1, "result": "6yTpkCW3UqVtpGj766Wvr73zEambzL2n44CDYiB4TpVP", // tx hash "statusCode": 200 } ``` ### Deployment To deploy a container, build the Docker image: ```bash docker build -t near-protocol-adapter . ``` Run the Docker container: ```bash docker run -d \ --name near-protocol-adapter \ -p 3000:3000 \ -e NODE_ENV=testnet \ -e PORT=3000 \ -e ACCOUNT_ID=dummy.testnet \ -e PRIVATE_KEY=ed25519:3Zo9bWRC7vUoDHMaXdMd6osajUktbgGWxL3P89QxR8VguVPnFa7BXd5brw6tBa6RASn8YCVjPgkhpujnorCF7FR2 \ -e CONTRACT_ID=oracle.oracle.testnet \ -e METHOD_NAME=fulfill_request \ near-protocol-adapter ``` #### Serverless deployment Package the adapter: ```json yarn build:package ``` #### Install to AWS Lambda - In Lambda Functions, create function - On the Create function page: - Give the function a name - Use Node.js 12.x for the runtime - Choose an existing role or create a new one - Click Create Function - Under Function code, select "Upload a .zip file" from the Code entry type drop-down - Click Upload and select the `near-protocol-adapter-0.0.1.zip` file - Handler should be set as `dist/index.handler` - Add the environment variables as required - Save #### Install to GCP - In Functions, create a new function, choose to ZIP upload - Click Browse and select the `near-protocol-adapter-0.0.1.zip` file - Select a Storage Bucket to keep the zip in - Function to execute: gcpservice - Click More, add the environment variables as required
khorolets_nearoverflow-demo
README.md package.json public index.html manifest.json robots.txt src App.css App.js App.test.js components Answer index.js AnswerForm index.js Box index.js Header index.js QuestionDetail index.js QuestionForm index.js QuestionsList index.js item.js config.js index.css index.js lib constants.js logo.svg modules common.js index.js questions.js routes.js serviceWorker.js setupTests.js
# nearoverflow-demo Demo available https://khorolets.github.io/nearoverflow-demo/ Contract for this demo can be found in this repo https://github.com/khorolets/nearoverflow
omarr45_NEAR-quotes
README.md __tests__ as-pect.d.ts index.unit.spec.ts as-pect.config.js asconfig.json assembly as_types.d.ts index.ts model.ts tsconfig.json package.json
### Frontend repo for [The Quotes Notebooks](https://github.com/omarr45/NEAR-quotes) done with NEAR protocol ![Screenshot](https://user-images.githubusercontent.com/58887202/179410852-5aa8966a-e2e9-45e1-8fda-afc04474e9cb.png) ## The Quotes Notebook A simple project that I made for dApps 2022 internship by NEAR foundation ### Check the deployed version [here](https://near-quotes.web.app/): ### and check the code for the frontend [here](https://github.com/omarr45/NEAR-quotes-fe/) ![Screenshot](https://user-images.githubusercontent.com/58887202/179410852-5aa8966a-e2e9-45e1-8fda-afc04474e9cb.png)
esaminu_test-rs-boilerplate-543
.eslintrc.yml .github ISSUE_TEMPLATE 01_BUG_REPORT.md 02_FEATURE_REQUEST.md 03_CODEBASE_IMPROVEMENT.md 04_SUPPORT_QUESTION.md config.yml PULL_REQUEST_TEMPLATE.md labels.yml workflows codeql.yml deploy-to-console.yml labels.yml lock.yml pr-labels.yml stale.yml .gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs docs CODE_OF_CONDUCT.md CONTRIBUTING.md SECURITY.md frontend App.js assets global.css logo-black.svg logo-white.svg index.html index.js near-interface.js near-wallet.js package.json start.sh ui-components.js integration-tests Cargo.toml src tests.rs package.json
<h1 align="center"> <a href="https://github.com/near/boilerplate-template-rs"> <picture> <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_light.png"> <source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_dark.png"> <img alt="" src="https://raw.githubusercontent.com/near/boilerplate-template-rs/main/docs/images/pagoda_logo_dark.png"> </picture> </a> </h1> <div align="center"> Rust Boilerplate Template <br /> <br /> <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=bug&template=01_BUG_REPORT.md&title=bug%3A+">Report a Bug</a> · <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=enhancement&template=02_FEATURE_REQUEST.md&title=feat%3A+">Request a Feature</a> . <a href="https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+">Ask a Question</a> </div> <div align="center"> <br /> [![Pull Requests welcome](https://img.shields.io/badge/PRs-welcome-ff69b4.svg?style=flat-square)](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) [![code with love by near](https://img.shields.io/badge/%3C%2F%3E%20with%20%E2%99%A5%20by-near-ff1414.svg?style=flat-square)](https://github.com/near) </div> <details open="open"> <summary>Table of Contents</summary> - [About](#about) - [Built With](#built-with) - [Getting Started](#getting-started) - [Prerequisites](#prerequisites) - [Installation](#installation) - [Usage](#usage) - [Roadmap](#roadmap) - [Support](#support) - [Project assistance](#project-assistance) - [Contributing](#contributing) - [Authors & contributors](#authors--contributors) - [Security](#security) </details> --- ## About This project is created for easy-to-start as a React + Rust skeleton template in the Pagoda Gallery. It was initialized with [create-near-app]. Clone it and start to build your own gallery project! ### Built With [create-near-app], [amazing-github-template](https://github.com/dec0dOS/amazing-github-template) Getting Started ================== ### Prerequisites Make sure you have a [current version of Node.js](https://nodejs.org/en/about/releases/) installed – we are targeting versions `16+`. Read about other [prerequisites](https://docs.near.org/develop/prerequisites) in our docs. ### Installation Install all dependencies: npm install Build your contract: npm run build Deploy your contract to TestNet with a temporary dev account: npm run deploy Usage ===== Test your contract: npm test Start your frontend: npm start Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages ## Roadmap See the [open issues](https://github.com/near/boilerplate-template-rs/issues) for a list of proposed features (and known issues). - [Top Feature Requests](https://github.com/near/boilerplate-template-rs/issues?q=label%3Aenhancement+is%3Aopen+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Top Bugs](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aissue+is%3Aopen+label%3Abug+sort%3Areactions-%2B1-desc) (Add your votes using the 👍 reaction) - [Newest Bugs](https://github.com/near/boilerplate-template-rs/issues?q=is%3Aopen+is%3Aissue+label%3Abug) ## Support Reach out to the maintainer: - [GitHub issues](https://github.com/near/boilerplate-template-rs/issues/new?assignees=&labels=question&template=04_SUPPORT_QUESTION.md&title=support%3A+) ## Project assistance If you want to say **thank you** or/and support active development of Rust Boilerplate Template: - Add a [GitHub Star](https://github.com/near/boilerplate-template-rs) to the project. - Tweet about the Rust Boilerplate Template. - Write interesting articles about the project on [Dev.to](https://dev.to/), [Medium](https://medium.com/) or your personal blog. Together, we can make Rust Boilerplate Template **better**! ## Contributing First off, thanks for taking the time to contribute! Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make will benefit everybody else and are **greatly appreciated**. Please read [our contribution guidelines](docs/CONTRIBUTING.md), and thank you for being involved! ## Authors & contributors The original setup of this repository is by [Dmitriy Sheleg](https://github.com/shelegdmitriy). For a full list of all authors and contributors, see [the contributors page](https://github.com/near/boilerplate-template-rs/contributors). ## Security Rust Boilerplate Template follows good practices of security, but 100% security cannot be assured. Rust Boilerplate Template is provided **"as is"** without any **warranty**. Use at your own risk. _For more information and to report security issues, please refer to our [security documentation](docs/SECURITY.md)._ # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
MustafaBayrakk_task3
README.md starter--near-sdk-as README.md as-pect.config.js asconfig.json neardev dev-account.env package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
# task3 # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` ## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068)
nearprotocol_near-bindgen-as
.github workflows nodejs.yml README.md assembly index.ts tsconfig.json compiler.js dist ASTBuilder.js JSONBuilder.js ast.js base.js index.js transformer.js typeChecker.js visitor.js package.json src ASTBuilder.ts JSONBuilder.ts ast.d.ts ast.js base.ts index.ts transformer.ts typeChecker.ts visitor.ts tests asconfig.js assembly f32.ts f64.ts main.ts model.ts test.ts types.d.ts out assembly main.ts model.ts test.ts package.json test.js tsconfig.json tsconfig.json
Deprecated see [near-sdk-as](https://github.com/near/near-sdk-as)
GuijonGustavo_notes-near
.cache 00 1d0ae57114d19876dcff48707ba40d.json 04 34d183c5038179b62cd99c65e68bc2.json 05 2343114de32f41ab4b6168910a8dcb.json b0059d19cbad68a8d018f47caf47c9.json 06 b2a2778c2327f7637b51fd35135f16.json 0d 3999600d02bb008ab0b0fe5570dbc5.json 0e 6f3b597b361fe7204eee086e976dda.json 0f 6ed6634cf690409de284c322a84feb.json 11 5aff7cc79145df472efb2555beb6bd.json 17 1d7a3e1f7183fc315b3572141fa73a.json 18 5bcb78834678333224d97481546f4d.json 19 6c8d1aeb69fc0dd925515752549d2a.json 1a b94705b1f4bde3435712423a523fb9.json 1b b1ff1f3bf5b4cac758cc7fe7227896.json 1c 0086142ded72ec3a887c582d6f104b.json 1e 9c0114bef0f75556c3bf1c76c140db.json 20 3f726c943c77c14359d73ed020407d.json 22 5a4daa69de3fbf02a7ea71cee8d68a.json 23 ade11f95ebc3ca7761d43c769260f7.json 26 20bb966e9aeb3a0910d970ac424359.json f38a7c95c3e9730dc07f81a5181f1e.json 2b 9f1dd0737e066c940144ca6fffdfd6.json 2c be756c7cb9b469423a0f507c7601ae.json ea3bb7c41759ebc5b76f6c84d54084.json 2f ec0309038fc7949efcf8c8aa902795.json 31 40239cb9be4294b8e467473b74d36a.json 6522fb0a68d603ec4839ca564052e3.json 33 23eca9cd907290c8b63fb13feaaa72.json eac96a89f3ffbcd1a5020fda9f0523.json 37 23f6332370e274fc0630a9e9671145.json 38 25dcb3057242853bccdf35d9d4d8e1.json be7ed2dc0af6be15dc0011805a90ab.json da035578d6651a5ad1d77c0dab29a1.json 3a 2fe9363375ec5fdce2ff9800edee87.json 9213e463dfad2184ef5b3700362d31.json 3e 5663f0b3788dee2bb09792d2b3b2b6.json 7e8b813c6afd99ec0513fdcb9b66ae.json 40 9f9e5f79a4180c61f619d839e5df23.json 41 f2002cbabf013d958ae62643ba0ed6.json 43 c156df450e01f360a0e1a1a74335d0.json 49 6f53fff795f9942055b20d86b9caf7.json 4d 2266262a2624bb1de345d20c79428e.json 8052437d85c106fd901a3b6349050d.json 50 82e32d7569f9abfd37ca4f54751680.json 51 4247e304f6696a3bb8ff3606a01871.json 84f16d6740e4f0321b4e2ebe18f038.json 53 9a93eceadaf6b4b334762b79d0e803.json 54 d7138253e456c058a1806da3778edb.json 5a 4f3750a66034386b5f7081af9ab91d.json 5b 93697a03aafd06bc2efbac88cb37c3.json 60 3acfcac9d4204dc43b4a7c08b52ffa.json 8dc8d1ad4a0f23dac1ed48faf8da2f.json 61 8acb1c85dd08793a25645f317d8253.json 62 7b54db7d2cded9f4051426ddfd40f0.json 65 0a2393755bde007d2b934ea126eee2.json 66 954a5ae31406b1c8b664e6750a2d14.json c8724fa890a757f6e5e4ef1fbae71a.json 68 f7d14f2ca3e61e9e636e72add0acf4.json 69 64da0d7a7a1507dfd0355ca6a2b8c9.json 6b 2d88f7509122ae346904f4395751a1.json 6d a6de197280d78cc00546c0687d7354.json 6e a9bd8a492ab0a5c2a8e203596c93b1.json 75 e9f52c7d8b4443ac36d35a1e5c3f30.json 79 066b2ee4793f642d72d7e9a98b7771.json 83 74384620f98b8bbe2684ba6c5b2669.json 89 9878eb703ef04d45f8410961ec009b.json 8b 494cfe9515faad308f2bd310f6bb0b.json af33a8ab825ec480c9aaa82599d745.json 8d 22c2ddb9da434bac6c8b739cce74b3.json 95 14b7fdac8709e647d29bc411fef01e.json dacf7878617def0132868827c2355f.json 99 116c960e62add909ea29495820e3bc.json 9d 1269c222f9cfdec7370e2cd8cd50d8.json 9e 4902d4e72b010ad4cdc35c66b49ccd.json a3 17b71eeb94aa740e705e82c887a6de.json a7 45ef68321a4493aa07e0a52ca13d08.json a8 50d2231a41b3cba89df585b9cb2c1d.json ad 6a8fed3a35dc23672fb8bb6a56e59b.json af 76a7adc527d110ce06506cd70fe77b.json b3 181ec456632a86aad1a66c4e81d37d.json b5 1d3ccef0911d4a9a7ba51bcc548f17.json bb 3a3d1d0cec51eef33c2d094f3919c8.json bc 940a24a071b58a5aef992dfb42a043.json c6 eefdc5620c730baaa593d2dbb672ed.json ca 59b91c318e2eed5da3a79ca28b587b.json cd ecf46105714c26a71832afa8681398.json d7 b0a8f202958c0b3eccfdec8b8d099a.json dd c19c772b9d47d522dacd4b91fa3c00.json e5 0a793a507d9e666758663a6cee2fd0.json e6 0e4916c7f6a7830522a9a141d37f97.json eb 2063c887584c607271f869fc617f8e.json ed c22b72e51fa490ec4d5e0365d9acac.json f6 9d121b582afb5ae3f1972ed4476ab3.json fb 56ca5cfd44bc2d1a20703f46727dc2.json .gitpod.yml README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts tsconfig.json compile.js node_modules .package-lock.json @as-covers assembly CONTRIBUTING.md README.md index.ts package.json tsconfig.json core CONTRIBUTING.md README.md package.json glue README.md lib index.d.ts index.js package.json transform README.md lib index.d.ts index.js util.d.ts util.js node_modules visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js toString.d.ts toString.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformRange.d.ts transformRange.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json package.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @eslint eslintrc CHANGELOG.md README.md conf config-schema.js environments.js eslint-all.js eslint-recommended.js lib cascading-config-array-factory.js config-array-factory.js config-array config-array.js config-dependency.js extracted-config.js ignore-pattern.js index.js override-tester.js flat-compat.js index.js shared ajv.js config-ops.js config-validator.js deprecation-warnings.js naming.js relative-module-resolver.js types.js package.json @humanwhocodes config-array README.md api.js package.json object-schema .eslintrc.js .github workflows nodejs-test.yml release-please.yml CHANGELOG.md README.md package.json src index.js merge-strategy.js object-schema.js validation-strategy.js tests merge-strategy.js object-schema.js validation-strategy.js acorn-jsx README.md index.d.ts index.js package.json xhtml.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json as-bignum README.md assembly __tests__ as-pect.d.ts i128.spec.as.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts package.json asbuild README.md dist cli.d.ts cli.js commands build.d.ts build.js fmt.d.ts fmt.js index.d.ts index.js init cmd.d.ts cmd.js files asconfigJson.d.ts asconfigJson.js aspecConfig.d.ts aspecConfig.js assembly_files.d.ts assembly_files.js eslintConfig.d.ts eslintConfig.js gitignores.d.ts gitignores.js index.d.ts index.js indexJs.d.ts indexJs.js packageJson.d.ts packageJson.js test_files.d.ts test_files.js index.d.ts index.js interfaces.d.ts interfaces.js run.d.ts run.js test.d.ts test.js index.d.ts index.js main.d.ts main.js utils.d.ts utils.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json assemblyscript-json .eslintrc.js .travis.yml README.md assembly JSON.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json temp-docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md assemblyscript-regex .eslintrc.js .github workflows benchmark.yml release.yml test.yml README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __spec_tests__ generated.spec.ts __tests__ alterations.spec.ts as-pect.d.ts boundary-assertions.spec.ts capture-group.spec.ts character-classes.spec.ts character-sets.spec.ts characters.ts empty.ts quantifiers.spec.ts range-quantifiers.spec.ts regex.spec.ts utils.ts char.ts env.ts index.ts nfa matcher.ts nfa.ts types.ts walker.ts parser node.ts parser.ts string-iterator.ts walker.ts regexp.ts tsconfig.json util.ts benchmark benchmark.js package.json spec test-generator.js ts index.ts tsconfig.json assemblyscript-temporal .github workflows node.js.yml release.yml .vscode launch.json README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __tests__ README.md as-pect.d.ts date.spec.ts duration.spec.ts empty.ts plaindate.spec.ts plaindatetime.spec.ts plainmonthday.spec.ts plaintime.spec.ts plainyearmonth.spec.ts timezone.spec.ts zoneddatetime.spec.ts constants.ts date.ts duration.ts enums.ts env.ts index.ts instant.ts now.ts plaindate.ts plaindatetime.ts plainmonthday.ts plaintime.ts plainyearmonth.ts timezone.ts tsconfig.json tz __tests__ index.spec.ts rule.spec.ts zone.spec.ts iana.ts index.ts rule.ts zone.ts utils.ts zoneddatetime.ts development.md package.json tzdb README.md iana theory.html zoneinfo2tdf.pl assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md bin rtplot.js index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json astral-regex index.d.ts index.js package.json readme.md axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js CHANGELOG.md README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json csv-stringify README.md lib browser index.js sync.js es5 index.d.ts index.js sync.d.ts sync.js index.d.ts index.js sync.d.ts sync.js package.json debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js diff CONTRIBUTING.md README.md dist diff.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js doctrine CHANGELOG.md README.md lib doctrine.js typed.js utility.js package.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js enquirer CHANGELOG.md README.md index.d.ts index.js lib ansi.js combos.js completer.js interpolate.js keypress.js placeholder.js prompt.js prompts autocomplete.js basicauth.js confirm.js editable.js form.js index.js input.js invisible.js list.js multiselect.js numeral.js password.js quiz.js scale.js select.js snippet.js sort.js survey.js text.js toggle.js render.js roles.js state.js styles.js symbols.js theme.js timer.js types array.js auth.js boolean.js index.js number.js string.js utils.js package.json env-paths index.d.ts index.js package.json readme.md escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js package.json eslint-utils README.md index.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json eslint CHANGELOG.md README.md bin eslint.js conf category-list.json config-schema.js default-cli-options.js eslint-all.js eslint-recommended.js replacements.json lib api.js cli-engine cli-engine.js file-enumerator.js formatters checkstyle.js codeframe.js compact.js html.js jslint-xml.js json-with-metadata.js json.js junit.js stylish.js table.js tap.js unix.js visualstudio.js hash.js index.js lint-result-cache.js load-rules.js xml-escape.js cli.js config default-config.js flat-config-array.js flat-config-schema.js rule-validator.js eslint eslint.js index.js init autoconfig.js config-file.js config-initializer.js config-rule.js npm-utils.js source-code-utils.js linter apply-disable-directives.js code-path-analysis code-path-analyzer.js code-path-segment.js code-path-state.js code-path.js debug-helpers.js fork-context.js id-generator.js config-comment-parser.js index.js interpolate.js linter.js node-event-generator.js report-translator.js rule-fixer.js rules.js safe-emitter.js source-code-fixer.js timing.js options.js rule-tester index.js rule-tester.js rules accessor-pairs.js array-bracket-newline.js array-bracket-spacing.js array-callback-return.js array-element-newline.js arrow-body-style.js arrow-parens.js arrow-spacing.js block-scoped-var.js block-spacing.js brace-style.js callback-return.js camelcase.js capitalized-comments.js class-methods-use-this.js comma-dangle.js comma-spacing.js comma-style.js complexity.js computed-property-spacing.js consistent-return.js consistent-this.js constructor-super.js curly.js default-case-last.js default-case.js default-param-last.js dot-location.js dot-notation.js eol-last.js eqeqeq.js for-direction.js func-call-spacing.js func-name-matching.js func-names.js func-style.js function-call-argument-newline.js function-paren-newline.js generator-star-spacing.js getter-return.js global-require.js grouped-accessor-pairs.js guard-for-in.js handle-callback-err.js id-blacklist.js id-denylist.js id-length.js id-match.js implicit-arrow-linebreak.js indent-legacy.js indent.js index.js init-declarations.js jsx-quotes.js key-spacing.js keyword-spacing.js line-comment-position.js linebreak-style.js lines-around-comment.js lines-around-directive.js lines-between-class-members.js max-classes-per-file.js max-depth.js max-len.js max-lines-per-function.js max-lines.js max-nested-callbacks.js max-params.js max-statements-per-line.js max-statements.js multiline-comment-style.js multiline-ternary.js new-cap.js new-parens.js newline-after-var.js newline-before-return.js newline-per-chained-call.js no-alert.js no-array-constructor.js no-async-promise-executor.js no-await-in-loop.js no-bitwise.js no-buffer-constructor.js no-caller.js no-case-declarations.js no-catch-shadow.js no-class-assign.js no-compare-neg-zero.js no-cond-assign.js no-confusing-arrow.js no-console.js no-const-assign.js no-constant-condition.js no-constructor-return.js no-continue.js no-control-regex.js no-debugger.js no-delete-var.js no-div-regex.js no-dupe-args.js no-dupe-class-members.js no-dupe-else-if.js no-dupe-keys.js no-duplicate-case.js no-duplicate-imports.js no-else-return.js no-empty-character-class.js no-empty-function.js no-empty-pattern.js no-empty.js no-eq-null.js no-eval.js no-ex-assign.js no-extend-native.js no-extra-bind.js no-extra-boolean-cast.js no-extra-label.js no-extra-parens.js no-extra-semi.js no-fallthrough.js no-floating-decimal.js no-func-assign.js no-global-assign.js no-implicit-coercion.js no-implicit-globals.js no-implied-eval.js no-import-assign.js no-inline-comments.js no-inner-declarations.js no-invalid-regexp.js no-invalid-this.js no-irregular-whitespace.js no-iterator.js no-label-var.js no-labels.js no-lone-blocks.js no-lonely-if.js no-loop-func.js no-loss-of-precision.js no-magic-numbers.js no-misleading-character-class.js no-mixed-operators.js no-mixed-requires.js no-mixed-spaces-and-tabs.js no-multi-assign.js no-multi-spaces.js no-multi-str.js no-multiple-empty-lines.js no-native-reassign.js no-negated-condition.js no-negated-in-lhs.js no-nested-ternary.js no-new-func.js no-new-object.js no-new-require.js no-new-symbol.js no-new-wrappers.js no-new.js no-nonoctal-decimal-escape.js no-obj-calls.js no-octal-escape.js no-octal.js no-param-reassign.js no-path-concat.js no-plusplus.js no-process-env.js no-process-exit.js no-promise-executor-return.js no-proto.js no-prototype-builtins.js no-redeclare.js no-regex-spaces.js no-restricted-exports.js no-restricted-globals.js no-restricted-imports.js no-restricted-modules.js no-restricted-properties.js no-restricted-syntax.js no-return-assign.js no-return-await.js no-script-url.js no-self-assign.js no-self-compare.js no-sequences.js no-setter-return.js no-shadow-restricted-names.js no-shadow.js no-spaced-func.js no-sparse-arrays.js no-sync.js no-tabs.js no-template-curly-in-string.js no-ternary.js no-this-before-super.js no-throw-literal.js no-trailing-spaces.js no-undef-init.js no-undef.js no-undefined.js no-underscore-dangle.js no-unexpected-multiline.js no-unmodified-loop-condition.js no-unneeded-ternary.js no-unreachable-loop.js no-unreachable.js no-unsafe-finally.js no-unsafe-negation.js no-unsafe-optional-chaining.js no-unused-expressions.js no-unused-labels.js no-unused-vars.js no-use-before-define.js no-useless-backreference.js no-useless-call.js no-useless-catch.js no-useless-computed-key.js no-useless-concat.js no-useless-constructor.js no-useless-escape.js no-useless-rename.js no-useless-return.js no-var.js no-void.js no-warning-comments.js no-whitespace-before-property.js no-with.js nonblock-statement-body-position.js object-curly-newline.js object-curly-spacing.js object-property-newline.js object-shorthand.js one-var-declaration-per-line.js one-var.js operator-assignment.js operator-linebreak.js padded-blocks.js padding-line-between-statements.js prefer-arrow-callback.js prefer-const.js prefer-destructuring.js prefer-exponentiation-operator.js prefer-named-capture-group.js prefer-numeric-literals.js prefer-object-spread.js prefer-promise-reject-errors.js prefer-reflect.js prefer-regex-literals.js prefer-rest-params.js prefer-spread.js prefer-template.js quote-props.js quotes.js radix.js require-atomic-updates.js require-await.js require-jsdoc.js require-unicode-regexp.js require-yield.js rest-spread-spacing.js semi-spacing.js semi-style.js semi.js sort-imports.js sort-keys.js sort-vars.js space-before-blocks.js space-before-function-paren.js space-in-parens.js space-infix-ops.js space-unary-ops.js spaced-comment.js strict.js switch-colon-spacing.js symbol-description.js template-curly-spacing.js template-tag-spacing.js unicode-bom.js use-isnan.js utils ast-utils.js fix-tracker.js keywords.js lazy-loading-rule-map.js patterns letters.js unicode index.js is-combining-character.js is-emoji-modifier.js is-regional-indicator-symbol.js is-surrogate-pair.js valid-jsdoc.js valid-typeof.js vars-on-top.js wrap-iife.js wrap-regex.js yield-star-spacing.js yoda.js shared ajv.js ast-utils.js config-validator.js deprecation-warnings.js logging.js relative-module-resolver.js runtime-info.js string-utils.js traverser.js types.js source-code index.js source-code.js token-store backward-token-comment-cursor.js backward-token-cursor.js cursor.js cursors.js decorative-cursor.js filter-cursor.js forward-token-comment-cursor.js forward-token-cursor.js index.js limit-cursor.js padded-token-cursor.js skip-cursor.js utils.js messages all-files-ignored.js extend-config-missing.js failed-to-read-json.js file-not-found.js no-config-found.js plugin-conflict.js plugin-invalid.js plugin-missing.js print-config-with-directory-path.js whitespace-found.js package.json espree CHANGELOG.md README.md espree.js lib ast-node-types.js espree.js features.js options.js token-translator.js visitor-keys.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esquery README.md dist esquery.esm.js esquery.esm.min.js esquery.js esquery.lite.js esquery.lite.min.js esquery.min.js license.txt node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json parser.js esrecurse README.md esrecurse.js gulpfile.babel.js node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json estraverse README.md estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-deep-equal README.md es6 index.d.ts index.js react.d.ts react.js index.d.ts index.js package.json react.d.ts react.js fast-json-stable-stringify .eslintrc.yml .github FUNDING.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.d.ts index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json file-entry-cache README.md cache.js changelog.md package.json find-up index.d.ts index.js package.json readme.md flat-cache README.md changelog.md package.json src cache.js del.js utils.js flatted .github FUNDING.yml workflows node.js.yml README.md SPECS.md cjs index.js package.json es.js esm index.js index.js min.js package.json php flatted.php types.d.ts follow-redirects README.md http.js https.js index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js ms index.js license.md package.json readme.md package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js functional-red-black-tree README.md bench test.js package.json rbtree.js test test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globals globals.json index.d.ts index.js package.json readme.md has-flag index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hasurl README.md index.js package.json ignore CHANGELOG.md README.md index.d.ts index.js legacy.js package.json import-fresh index.d.ts index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json interpret README.md index.js mjs-stub.js package.json is-core-module CHANGELOG.md README.md core.json index.js package.json test index.js is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.js package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json js-tokens CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-stable-stringify-without-jsonify .travis.yml example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js replacer.js space.js str.js to-json.js levn README.md lib cast.js index.js parse-string.js package.json line-column README.md lib line-column.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.merge README.md index.js package.json lodash.sortby README.md index.js package.json lodash.truncate README.md index.js package.json long README.md dist long.js index.js package.json src long.js lru-cache README.md index.js package.json minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md natural-compare README.md index.js package.json near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt empty.ts generic.ts includeBytes.spec.ts main.ts max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts json.lib.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts maxHeap.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts datetime.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ empty.ts exportAs.ts model.ts sentences.ts singleton copy.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md parent-module index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-key index.d.ts index.js package.json readme.md path-parse README.md index.js package.json prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json rechoir .travis.yml README.md index.js lib extension.js normalize.js register.js package.json regexpp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json require-from-string index.js package.json readme.md require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve-from index.js package.json readme.md resolve .github FUNDING.yml SECURITY.md appveyor.yml async.js example async.js sync.js index.js lib async.js caller.js core.js core.json homedir.js is-core.js node-modules-paths.js normalize-options.js sync.js package.json sync.js test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js home_paths.js home_paths_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json malformed_package_json index.js package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json semver CHANGELOG.md README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md shelljs CHANGELOG.md README.md commands.js global.js make.js package.json plugin.js shell.js src cat.js cd.js chmod.js common.js cp.js dirs.js echo.js error.js exec-child.js exec.js find.js grep.js head.js ln.js ls.js mkdir.js mv.js popd.js pushd.js pwd.js rm.js sed.js set.js sort.js tail.js tempdir.js test.js to.js toEnd.js touch.js uniq.js which.js slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md supports-preserve-symlinks-flag .github FUNDING.yml CHANGELOG.md README.md browser.js index.js package.json test index.js table README.md dist src alignSpanningCell.d.ts alignSpanningCell.js alignString.d.ts alignString.js alignTableData.d.ts alignTableData.js calculateCellHeight.d.ts calculateCellHeight.js calculateMaximumColumnWidths.d.ts calculateMaximumColumnWidths.js calculateOutputColumnWidths.d.ts calculateOutputColumnWidths.js calculateRowHeights.d.ts calculateRowHeights.js calculateSpanningCellWidth.d.ts calculateSpanningCellWidth.js createStream.d.ts createStream.js drawBorder.d.ts drawBorder.js drawContent.d.ts drawContent.js drawRow.d.ts drawRow.js drawTable.d.ts drawTable.js generated validators.d.ts validators.js getBorderCharacters.d.ts getBorderCharacters.js index.d.ts index.js injectHeaderConfig.d.ts injectHeaderConfig.js makeRangeConfig.d.ts makeRangeConfig.js makeStreamConfig.d.ts makeStreamConfig.js makeTableConfig.d.ts makeTableConfig.js mapDataUsingRowHeights.d.ts mapDataUsingRowHeights.js padTableData.d.ts padTableData.js schemas config.json shared.json streamConfig.json spanningCellManager.d.ts spanningCellManager.js stringifyTableData.d.ts stringifyTableData.js table.d.ts table.js truncateTableData.d.ts truncateTableData.js types api.d.ts api.js internal.d.ts internal.js utils.d.ts utils.js validateConfig.d.ts validateConfig.js validateSpanningCellConfig.d.ts validateSpanningCellConfig.js validateTableData.d.ts validateTableData.js wrapCell.d.ts wrapCell.js wrapString.d.ts wrapString.js wrapWord.d.ts wrapWord.js node_modules ajv .runkit_example.js README.md dist 2019.d.ts 2019.js 2020.d.ts 2020.js ajv.d.ts ajv.js compile codegen code.d.ts code.js index.d.ts index.js scope.d.ts scope.js errors.d.ts errors.js index.d.ts index.js jtd parse.d.ts parse.js serialize.d.ts serialize.js types.d.ts types.js names.d.ts names.js ref_error.d.ts ref_error.js resolve.d.ts resolve.js rules.d.ts rules.js util.d.ts util.js validate applicability.d.ts applicability.js boolSchema.d.ts boolSchema.js dataType.d.ts dataType.js defaults.d.ts defaults.js index.d.ts index.js keyword.d.ts keyword.js subschema.d.ts subschema.js core.d.ts core.js jtd.d.ts jtd.js refs data.json json-schema-2019-09 index.d.ts index.js meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.d.ts index.js meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.d.ts jtd-schema.js runtime equal.d.ts equal.js parseJson.d.ts parseJson.js quote.d.ts quote.js re2.d.ts re2.js timestamp.d.ts timestamp.js ucs2length.d.ts ucs2length.js uri.d.ts uri.js validation_error.d.ts validation_error.js standalone index.d.ts index.js instance.d.ts instance.js types index.d.ts index.js json-schema.d.ts json-schema.js jtd-schema.d.ts jtd-schema.js vocabularies applicator additionalItems.d.ts additionalItems.js additionalProperties.d.ts additionalProperties.js allOf.d.ts allOf.js anyOf.d.ts anyOf.js contains.d.ts contains.js dependencies.d.ts dependencies.js dependentSchemas.d.ts dependentSchemas.js if.d.ts if.js index.d.ts index.js items.d.ts items.js items2020.d.ts items2020.js not.d.ts not.js oneOf.d.ts oneOf.js patternProperties.d.ts patternProperties.js prefixItems.d.ts prefixItems.js properties.d.ts properties.js propertyNames.d.ts propertyNames.js thenElse.d.ts thenElse.js code.d.ts code.js core id.d.ts id.js index.d.ts index.js ref.d.ts ref.js discriminator index.d.ts index.js types.d.ts types.js draft2020.d.ts draft2020.js draft7.d.ts draft7.js dynamic dynamicAnchor.d.ts dynamicAnchor.js dynamicRef.d.ts dynamicRef.js index.d.ts index.js recursiveAnchor.d.ts recursiveAnchor.js recursiveRef.d.ts recursiveRef.js errors.d.ts errors.js format format.d.ts format.js index.d.ts index.js jtd discriminator.d.ts discriminator.js elements.d.ts elements.js enum.d.ts enum.js error.d.ts error.js index.d.ts index.js metadata.d.ts metadata.js nullable.d.ts nullable.js optionalProperties.d.ts optionalProperties.js properties.d.ts properties.js ref.d.ts ref.js type.d.ts type.js union.d.ts union.js values.d.ts values.js metadata.d.ts metadata.js next.d.ts next.js unevaluated index.d.ts index.js unevaluatedItems.d.ts unevaluatedItems.js unevaluatedProperties.d.ts unevaluatedProperties.js validation const.d.ts const.js dependentRequired.d.ts dependentRequired.js enum.d.ts enum.js index.d.ts index.js limitContains.d.ts limitContains.js limitItems.d.ts limitItems.js limitLength.d.ts limitLength.js limitNumber.d.ts limitNumber.js limitProperties.d.ts limitProperties.js multipleOf.d.ts multipleOf.js pattern.d.ts pattern.js required.d.ts required.js uniqueItems.d.ts uniqueItems.js lib 2019.ts 2020.ts ajv.ts compile codegen code.ts index.ts scope.ts errors.ts index.ts jtd parse.ts serialize.ts types.ts names.ts ref_error.ts resolve.ts rules.ts util.ts validate applicability.ts boolSchema.ts dataType.ts defaults.ts index.ts keyword.ts subschema.ts core.ts jtd.ts refs data.json json-schema-2019-09 index.ts meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.ts meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.ts runtime equal.ts parseJson.ts quote.ts re2.ts timestamp.ts ucs2length.ts uri.ts validation_error.ts standalone index.ts instance.ts types index.ts json-schema.ts jtd-schema.ts vocabularies applicator additionalItems.ts additionalProperties.ts allOf.ts anyOf.ts contains.ts dependencies.ts dependentSchemas.ts if.ts index.ts items.ts items2020.ts not.ts oneOf.ts patternProperties.ts prefixItems.ts properties.ts propertyNames.ts thenElse.ts code.ts core id.ts index.ts ref.ts discriminator index.ts types.ts draft2020.ts draft7.ts dynamic dynamicAnchor.ts dynamicRef.ts index.ts recursiveAnchor.ts recursiveRef.ts errors.ts format format.ts index.ts jtd discriminator.ts elements.ts enum.ts error.ts index.ts metadata.ts nullable.ts optionalProperties.ts properties.ts ref.ts type.ts union.ts values.ts metadata.ts next.ts unevaluated index.ts unevaluatedItems.ts unevaluatedProperties.ts validation const.ts dependentRequired.ts enum.ts index.ts limitContains.ts limitItems.ts limitLength.ts limitNumber.ts limitProperties.ts multipleOf.ts pattern.ts required.ts uniqueItems.ts package.json json-schema-traverse .eslintrc.yml .github FUNDING.yml workflows build.yml publish.yml README.md index.d.ts index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json text-table .travis.yml example align.js center.js dotalign.js doubledot.js table.js index.js package.json test align.js ansi-colors.js center.js dotalign.js doubledot.js table.js tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json type-check README.md lib check.js index.js parse-type.js package.json type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts universal-url README.md browser.js index.js package.json uri-js README.md dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js ws.d.ts ws.js wss.d.ts wss.js uri.d.ts uri.js util.d.ts util.js package.json v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js word-wrap README.md index.d.ts index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json package-lock.json package.json | features not yet implemented issues with the tests differences between PCRE and JS regex | | | dist global.e50bbfba.css global.e50bbfba.js index.html index.js logo-black.eab7a939.svg logo-white.7fec831f.svg src.e31bb0bc.js package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) # fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # ShellJS - Unix shell commands for Node.js [![Travis](https://img.shields.io/travis/shelljs/shelljs/master.svg?style=flat-square&label=unix)](https://travis-ci.org/shelljs/shelljs) [![AppVeyor](https://img.shields.io/appveyor/ci/shelljs/shelljs/master.svg?style=flat-square&label=windows)](https://ci.appveyor.com/project/shelljs/shelljs/branch/master) [![Codecov](https://img.shields.io/codecov/c/github/shelljs/shelljs/master.svg?style=flat-square&label=coverage)](https://codecov.io/gh/shelljs/shelljs) [![npm version](https://img.shields.io/npm/v/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) [![npm downloads](https://img.shields.io/npm/dm/shelljs.svg?style=flat-square)](https://www.npmjs.com/package/shelljs) ShellJS is a portable **(Windows/Linux/OS X)** implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts! ShellJS is proudly tested on every node release since `v4`! The project is [unit-tested](http://travis-ci.org/shelljs/shelljs) and battle-tested in projects like: + [Firebug](http://getfirebug.com/) - Firefox's infamous debugger + [JSHint](http://jshint.com) & [ESLint](http://eslint.org/) - popular JavaScript linters + [Zepto](http://zeptojs.com) - jQuery-compatible JavaScript library for modern browsers + [Yeoman](http://yeoman.io/) - Web application stack and development tool + [Deployd.com](http://deployd.com) - Open source PaaS for quick API backend generation + And [many more](https://npmjs.org/browse/depended/shelljs). If you have feedback, suggestions, or need help, feel free to post in our [issue tracker](https://github.com/shelljs/shelljs/issues). Think ShellJS is cool? Check out some related projects in our [Wiki page](https://github.com/shelljs/shelljs/wiki)! Upgrading from an older version? Check out our [breaking changes](https://github.com/shelljs/shelljs/wiki/Breaking-Changes) page to see what changes to watch out for while upgrading. ## Command line use If you just want cross platform UNIX commands, checkout our new project [shelljs/shx](https://github.com/shelljs/shx), a utility to expose `shelljs` to the command line. For example: ``` $ shx mkdir -p foo $ shx touch foo/bar.txt $ shx rm -rf foo ``` ## Plugin API ShellJS now supports third-party plugins! You can learn more about using plugins and writing your own ShellJS commands in [the wiki](https://github.com/shelljs/shelljs/wiki/Using-ShellJS-Plugins). ## A quick note about the docs For documentation on all the latest features, check out our [README](https://github.com/shelljs/shelljs). To read docs that are consistent with the latest release, check out [the npm page](https://www.npmjs.com/package/shelljs) or [shelljs.org](http://documentup.com/shelljs/shelljs). ## Installing Via npm: ```bash $ npm install [-g] shelljs ``` ## Examples ```javascript var shell = require('shelljs'); if (!shell.which('git')) { shell.echo('Sorry, this script requires git'); shell.exit(1); } // Copy files to release dir shell.rm('-rf', 'out/Release'); shell.cp('-R', 'stuff/', 'out/Release'); // Replace macros in each .js file shell.cd('lib'); shell.ls('*.js').forEach(function (file) { shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file); shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file); shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file); }); shell.cd('..'); // Run external tool synchronously if (shell.exec('git commit -am "Auto-commit"').code !== 0) { shell.echo('Error: Git commit failed'); shell.exit(1); } ``` ## Exclude options If you need to pass a parameter that looks like an option, you can do so like: ```js shell.grep('--', '-v', 'path/to/file'); // Search for "-v", no grep options shell.cp('-R', '-dir', 'outdir'); // If already using an option, you're done ``` ## Global vs. Local We no longer recommend using a global-import for ShellJS (i.e. `require('shelljs/global')`). While still supported for convenience, this pollutes the global namespace, and should therefore only be used with caution. Instead, we recommend a local import (standard for npm packages): ```javascript var shell = require('shelljs'); shell.echo('hello world'); ``` <!-- DO NOT MODIFY BEYOND THIS POINT - IT'S AUTOMATICALLY GENERATED --> ## Command reference All commands run synchronously, unless otherwise stated. All commands accept standard bash globbing characters (`*`, `?`, etc.), compatible with the [node `glob` module](https://github.com/isaacs/node-glob). For less-commonly used commands and features, please check out our [wiki page](https://github.com/shelljs/shelljs/wiki). ### cat([options,] file [, file ...]) ### cat([options,] file_array) Available options: + `-n`: number all output lines Examples: ```javascript var str = cat('file*.txt'); var str = cat('file1', 'file2'); var str = cat(['file1', 'file2']); // same as above ``` Returns a string containing the given file, or a concatenated string containing the files if more than one file is given (a new line character is introduced between each file). ### cd([dir]) Changes to directory `dir` for the duration of the script. Changes to home directory if no argument is supplied. ### chmod([options,] octal_mode || octal_string, file) ### chmod([options,] symbolic_mode, file) Available options: + `-v`: output a diagnostic for every file processed + `-c`: like verbose, but report only when a change is made + `-R`: change files and directories recursively Examples: ```javascript chmod(755, '/Users/brandon'); chmod('755', '/Users/brandon'); // same as above chmod('u+x', '/Users/brandon'); chmod('-R', 'a-w', '/Users/brandon'); ``` Alters the permissions of a file or directory by either specifying the absolute permissions in octal form or expressing the changes in symbols. This command tries to mimic the POSIX behavior as much as possible. Notable exceptions: + In symbolic modes, `a-r` and `-r` are identical. No consideration is given to the `umask`. + There is no "quiet" option, since default behavior is to run silent. ### cp([options,] source [, source ...], dest) ### cp([options,] source_array, dest) Available options: + `-f`: force (default behavior) + `-n`: no-clobber + `-u`: only copy if `source` is newer than `dest` + `-r`, `-R`: recursive + `-L`: follow symlinks + `-P`: don't follow symlinks Examples: ```javascript cp('file1', 'dir1'); cp('-R', 'path/to/dir/', '~/newCopy/'); cp('-Rf', '/tmp/*', '/usr/local/*', '/home/tmp'); cp('-Rf', ['/tmp/*', '/usr/local/*'], '/home/tmp'); // same as above ``` Copies files. ### pushd([options,] [dir | '-N' | '+N']) Available options: + `-n`: Suppresses the normal change of directory when adding directories to the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `dir`: Sets the current working directory to the top of the stack, then executes the equivalent of `cd dir`. + `+N`: Brings the Nth directory (counting from the left of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. + `-N`: Brings the Nth directory (counting from the right of the list printed by dirs, starting with zero) to the top of the list by rotating the stack. Examples: ```javascript // process.cwd() === '/usr' pushd('/etc'); // Returns /etc /usr pushd('+1'); // Returns /usr /etc ``` Save the current directory on the top of the directory stack and then `cd` to `dir`. With no arguments, `pushd` exchanges the top two directories. Returns an array of paths in the stack. ### popd([options,] ['-N' | '+N']) Available options: + `-n`: Suppress the normal directory change when removing directories from the stack, so that only the stack is manipulated. + `-q`: Supresses output to the console. Arguments: + `+N`: Removes the Nth directory (counting from the left of the list printed by dirs), starting with zero. + `-N`: Removes the Nth directory (counting from the right of the list printed by dirs), starting with zero. Examples: ```javascript echo(process.cwd()); // '/usr' pushd('/etc'); // '/etc /usr' echo(process.cwd()); // '/etc' popd(); // '/usr' echo(process.cwd()); // '/usr' ``` When no arguments are given, `popd` removes the top directory from the stack and performs a `cd` to the new top directory. The elements are numbered from 0, starting at the first directory listed with dirs (i.e., `popd` is equivalent to `popd +0`). Returns an array of paths in the stack. ### dirs([options | '+N' | '-N']) Available options: + `-c`: Clears the directory stack by deleting all of the elements. + `-q`: Supresses output to the console. Arguments: + `+N`: Displays the Nth directory (counting from the left of the list printed by dirs when invoked without options), starting with zero. + `-N`: Displays the Nth directory (counting from the right of the list printed by dirs when invoked without options), starting with zero. Display the list of currently remembered directories. Returns an array of paths in the stack, or a single path if `+N` or `-N` was specified. See also: `pushd`, `popd` ### echo([options,] string [, string ...]) Available options: + `-e`: interpret backslash escapes (default) + `-n`: remove trailing newline from output Examples: ```javascript echo('hello world'); var str = echo('hello world'); echo('-n', 'no newline at end'); ``` Prints `string` to stdout, and returns string with additional utility methods like `.to()`. ### exec(command [, options] [, callback]) Available options: + `async`: Asynchronous execution. If a callback is provided, it will be set to `true`, regardless of the passed value (default: `false`). + `silent`: Do not echo program output to console (default: `false`). + `encoding`: Character encoding to use. Affects the values returned to stdout and stderr, and what is written to stdout and stderr when not in silent mode (default: `'utf8'`). + and any option available to Node.js's [`child_process.exec()`](https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback) Examples: ```javascript var version = exec('node --version', {silent:true}).stdout; var child = exec('some_long_running_process', {async:true}); child.stdout.on('data', function(data) { /* ... do something with data ... */ }); exec('some_long_running_process', function(code, stdout, stderr) { console.log('Exit code:', code); console.log('Program output:', stdout); console.log('Program stderr:', stderr); }); ``` Executes the given `command` _synchronously_, unless otherwise specified. When in synchronous mode, this returns a `ShellString` (compatible with ShellJS v0.6.x, which returns an object of the form `{ code:..., stdout:... , stderr:... }`). Otherwise, this returns the child process object, and the `callback` receives the arguments `(code, stdout, stderr)`. Not seeing the behavior you want? `exec()` runs everything through `sh` by default (or `cmd.exe` on Windows), which differs from `bash`. If you need bash-specific behavior, try out the `{shell: 'path/to/bash'}` option. ### find(path [, path ...]) ### find(path_array) Examples: ```javascript find('src', 'lib'); find(['src', 'lib']); // same as above find('.').filter(function(file) { return file.match(/\.js$/); }); ``` Returns array of all files (however deep) in the given paths. The main difference from `ls('-R', path)` is that the resulting file names include the base directories (e.g., `lib/resources/file1` instead of just `file1`). ### grep([options,] regex_filter, file [, file ...]) ### grep([options,] regex_filter, file_array) Available options: + `-v`: Invert `regex_filter` (only print non-matching lines). + `-l`: Print only filenames of matching files. + `-i`: Ignore case. Examples: ```javascript grep('-v', 'GLOBAL_VARIABLE', '*.js'); grep('GLOBAL_VARIABLE', '*.js'); ``` Reads input string from given files and returns a string containing all lines of the file that match the given `regex_filter`. ### head([{'-n': \<num\>},] file [, file ...]) ### head([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the first `<num>` lines of the files Examples: ```javascript var str = head({'-n': 1}, 'file*.txt'); var str = head('file1', 'file2'); var str = head(['file1', 'file2']); // same as above ``` Read the start of a file. ### ln([options,] source, dest) Available options: + `-s`: symlink + `-f`: force Examples: ```javascript ln('file', 'newlink'); ln('-sf', 'file', 'existing'); ``` Links `source` to `dest`. Use `-f` to force the link, should `dest` already exist. ### ls([options,] [path, ...]) ### ls([options,] path_array) Available options: + `-R`: recursive + `-A`: all files (include files beginning with `.`, except for `.` and `..`) + `-L`: follow symlinks + `-d`: list directories themselves, not their contents + `-l`: list objects representing each file, each with fields containing `ls -l` output fields. See [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) for more info Examples: ```javascript ls('projs/*.js'); ls('-R', '/users/me', '/tmp'); ls('-R', ['/users/me', '/tmp']); // same as above ls('-l', 'file.txt'); // { name: 'file.txt', mode: 33188, nlink: 1, ...} ``` Returns array of files in the given `path`, or files in the current directory if no `path` is provided. ### mkdir([options,] dir [, dir ...]) ### mkdir([options,] dir_array) Available options: + `-p`: full path (and create intermediate directories, if necessary) Examples: ```javascript mkdir('-p', '/tmp/a/b/c/d', '/tmp/e/f/g'); mkdir('-p', ['/tmp/a/b/c/d', '/tmp/e/f/g']); // same as above ``` Creates directories. ### mv([options ,] source [, source ...], dest') ### mv([options ,] source_array, dest') Available options: + `-f`: force (default behavior) + `-n`: no-clobber Examples: ```javascript mv('-n', 'file', 'dir/'); mv('file1', 'file2', 'dir/'); mv(['file1', 'file2'], 'dir/'); // same as above ``` Moves `source` file(s) to `dest`. ### pwd() Returns the current directory. ### rm([options,] file [, file ...]) ### rm([options,] file_array) Available options: + `-f`: force + `-r, -R`: recursive Examples: ```javascript rm('-rf', '/tmp/*'); rm('some_file.txt', 'another_file.txt'); rm(['some_file.txt', 'another_file.txt']); // same as above ``` Removes files. ### sed([options,] search_regex, replacement, file [, file ...]) ### sed([options,] search_regex, replacement, file_array) Available options: + `-i`: Replace contents of `file` in-place. _Note that no backups will be created!_ Examples: ```javascript sed('-i', 'PROGRAM_VERSION', 'v0.1.3', 'source.js'); sed(/.*DELETE_THIS_LINE.*\n/, '', 'source.js'); ``` Reads an input string from `file`s, and performs a JavaScript `replace()` on the input using the given `search_regex` and `replacement` string or function. Returns the new string after replacement. Note: Like unix `sed`, ShellJS `sed` supports capture groups. Capture groups are specified using the `$n` syntax: ```javascript sed(/(\w+)\s(\w+)/, '$2, $1', 'file.txt'); ``` ### set(options) Available options: + `+/-e`: exit upon error (`config.fatal`) + `+/-v`: verbose: show all commands (`config.verbose`) + `+/-f`: disable filename expansion (globbing) Examples: ```javascript set('-e'); // exit upon first error set('+e'); // this undoes a "set('-e')" ``` Sets global configuration variables. ### sort([options,] file [, file ...]) ### sort([options,] file_array) Available options: + `-r`: Reverse the results + `-n`: Compare according to numerical value Examples: ```javascript sort('foo.txt', 'bar.txt'); sort('-r', 'foo.txt'); ``` Return the contents of the `file`s, sorted line-by-line. Sorting multiple files mixes their content (just as unix `sort` does). ### tail([{'-n': \<num\>},] file [, file ...]) ### tail([{'-n': \<num\>},] file_array) Available options: + `-n <num>`: Show the last `<num>` lines of `file`s Examples: ```javascript var str = tail({'-n': 1}, 'file*.txt'); var str = tail('file1', 'file2'); var str = tail(['file1', 'file2']); // same as above ``` Read the end of a `file`. ### tempdir() Examples: ```javascript var tmp = tempdir(); // "/tmp" for most *nix platforms ``` Searches and returns string containing a writeable, platform-dependent temporary directory. Follows Python's [tempfile algorithm](http://docs.python.org/library/tempfile.html#tempfile.tempdir). ### test(expression) Available expression primaries: + `'-b', 'path'`: true if path is a block device + `'-c', 'path'`: true if path is a character device + `'-d', 'path'`: true if path is a directory + `'-e', 'path'`: true if path exists + `'-f', 'path'`: true if path is a regular file + `'-L', 'path'`: true if path is a symbolic link + `'-p', 'path'`: true if path is a pipe (FIFO) + `'-S', 'path'`: true if path is a socket Examples: ```javascript if (test('-d', path)) { /* do something with dir */ }; if (!test('-f', path)) continue; // skip if it's a regular file ``` Evaluates `expression` using the available primaries and returns corresponding value. ### ShellString.prototype.to(file) Examples: ```javascript cat('input.txt').to('output.txt'); ``` Analogous to the redirection operator `>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). _Like Unix redirections, `to()` will overwrite any existing file!_ ### ShellString.prototype.toEnd(file) Examples: ```javascript cat('input.txt').toEnd('output.txt'); ``` Analogous to the redirect-and-append operator `>>` in Unix, but works with `ShellStrings` (such as those returned by `cat`, `grep`, etc.). ### touch([options,] file [, file ...]) ### touch([options,] file_array) Available options: + `-a`: Change only the access time + `-c`: Do not create any files + `-m`: Change only the modification time + `-d DATE`: Parse `DATE` and use it instead of current time + `-r FILE`: Use `FILE`'s times instead of current time Examples: ```javascript touch('source.js'); touch('-c', '/path/to/some/dir/source.js'); touch({ '-r': FILE }, '/path/to/some/dir/source.js'); ``` Update the access and modification times of each `FILE` to the current time. A `FILE` argument that does not exist is created empty, unless `-c` is supplied. This is a partial implementation of [`touch(1)`](http://linux.die.net/man/1/touch). ### uniq([options,] [input, [output]]) Available options: + `-i`: Ignore case while comparing + `-c`: Prefix lines by the number of occurrences + `-d`: Only print duplicate lines, one for each group of identical lines Examples: ```javascript uniq('foo.txt'); uniq('-i', 'foo.txt'); uniq('-cd', 'foo.txt', 'bar.txt'); ``` Filter adjacent matching lines from `input`. ### which(command) Examples: ```javascript var nodeExec = which('node'); ``` Searches for `command` in the system's `PATH`. On Windows, this uses the `PATHEXT` variable to append the extension if it's not already executable. Returns string containing the absolute path to `command`. ### exit(code) Exits the current process with the given exit `code`. ### error() Tests if error occurred in the last command. Returns a truthy value if an error returned, or a falsy value otherwise. **Note**: do not rely on the return value to be an error message. If you need the last error message, use the `.stderr` attribute from the last command's return value instead. ### ShellString(str) Examples: ```javascript var foo = ShellString('hello world'); ``` Turns a regular string into a string-like object similar to what each command returns. This has special methods, like `.to()` and `.toEnd()`. ### env['VAR_NAME'] Object containing environment variables (both getter and setter). Shortcut to `process.env`. ### Pipes Examples: ```javascript grep('foo', 'file1.txt', 'file2.txt').sed(/o/g, 'a').to('output.txt'); echo('files with o\'s in the name:\n' + ls().grep('o')); cat('test.js').exec('node'); // pipe to exec() call ``` Commands can send their output to another command in a pipe-like fashion. `sed`, `grep`, `cat`, `exec`, `to`, and `toEnd` can appear on the right-hand side of a pipe. Pipes can be chained. ## Configuration ### config.silent Example: ```javascript var sh = require('shelljs'); var silentState = sh.config.silent; // save old silent state sh.config.silent = true; /* ... */ sh.config.silent = silentState; // restore old silent state ``` Suppresses all command output if `true`, except for `echo()` calls. Default is `false`. ### config.fatal Example: ```javascript require('shelljs/global'); config.fatal = true; // or set('-e'); cp('this_file_does_not_exist', '/dev/null'); // throws Error here /* more commands... */ ``` If `true`, the script will throw a Javascript error when any shell.js command encounters an error. Default is `false`. This is analogous to Bash's `set -e`. ### config.verbose Example: ```javascript config.verbose = true; // or set('-v'); cd('dir/'); rm('-rf', 'foo.txt', 'bar.txt'); exec('echo hello'); ``` Will print each command as follows: ``` cd dir/ rm -rf foo.txt bar.txt exec echo hello ``` ### config.globOptions Example: ```javascript config.globOptions = {nodir: true}; ``` Use this value for calls to `glob.sync()` instead of the default options. ### config.reset() Example: ```javascript var shell = require('shelljs'); // Make changes to shell.config, and do stuff... /* ... */ shell.config.reset(); // reset to original state // Do more stuff, but with original settings /* ... */ ``` Reset `shell.config` to the defaults: ```javascript { fatal: false, globOptions: {}, maxdepth: 255, noglob: false, silent: false, verbose: false, } ``` ## Team | [![Nate Fischer](https://avatars.githubusercontent.com/u/5801521?s=130)](https://github.com/nfischer) | [![Brandon Freitag](https://avatars1.githubusercontent.com/u/5988055?v=3&s=130)](http://github.com/freitagbr) | |:---:|:---:| | [Nate Fischer](https://github.com/nfischer) | [Brandon Freitag](http://github.com/freitagbr) | ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>. See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. You can install via npm `npm install prelude-ls` ### Development `make test` to test `make build` to build `lib` from `src` `make build-browser` to build browser versions # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js const rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> Like `chown -R`. Takes the same arguments as `fs.chown()` # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # flatted [![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) ![snow flake](./flatted.jpg) <sup>**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**</sup> ## Announcement 📣 There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general. The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax. However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍 - - - A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). Now available also for **[PHP](./php/flatted.php)**. ```js npm i flatted ``` Usable via [CDN](https://unpkg.com/flatted) or as regular module. ```js // ESM import {parse, stringify, toJSON, fromJSON} from 'flatted'; // CJS const {parse, stringify, toJSON, fromJSON} = require('flatted'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}] ``` ## toJSON and fromJSON If you'd like to implicitly survive JSON serialization, these two helpers helps: ```js import {toJSON, fromJSON} from 'flatted'; class RecursiveMap extends Map { static fromJSON(any) { return new this(fromJSON(any)); } toJSON() { return toJSON([...this.entries()]); } } const recursive = new RecursiveMap; const same = {}; same.same = same; recursive.set('same', same); const asString = JSON.stringify(recursive); const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); asMap.get('same') === asMap.get('same').same; // true ``` ## Flatted VS JSON As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. ### New in V1: Exact same JSON API * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. ### Compatibility All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. ### How does it work ? While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` Once parsed, all indexes will be replaced through the flattened collection. <sup><sub>`*` represented as string to avoid conflicts with numbers</sub></sup> ```js // logic example var a = [{one: 1}, {two: '2'}]; a[0].a = a; // a is the main object, will be at index '0' // {one: 1} is the second object, index '1' // {two: '2'} the third, in '2', and it has a string // which will be found at index '3' Flatted.stringify(a); // [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] // a[one,two] {one: 1, a} {two: '2'} '2' ``` # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg"> &nbsp; # Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). [![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-%2307b4b9)](https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2Fap4lMFzfXF8Hzmh-Vz0WNxp_1jKiOa-h%23MCowBQYDK2VuAyEAcdefddRvDfI8iAuBpztm_J3qFucj8MDZoVs_2EcMTzU%3D) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv sponsors [<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv) ## Contributing More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). ## Documentation All documentation is available on the [Ajv website](https://ajv.js.org). Some useful site links: - [Getting started](https://ajv.js.org/guide/getting-started.html) - [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) - [API reference](https://ajv.js.org/api.html) - [Strict mode](https://ajv.js.org/strict-mode.html) - [Standalone validation code](https://ajv.js.org/standalone.html) - [Security considerations](https://ajv.js.org/security.html) - [Command line interface](https://ajv.js.org/packages/ajv-cli.html) - [Frequently Asked Questions](https://ajv.js.org/faq.html) ## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a> ## Performance Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus&#x2F;schemasafe|is-my-json-valid|djv|@cfworker&#x2F;json-schema|jsonschema&chd=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) - support of recursive references between schemas - correct string lengths for strings with unicode pairs - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) - NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) - meta-schema for JTD schemas - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) - supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current - [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) - [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) - [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items - [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords - [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) - additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords ## Install To install version 8: ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://runkit.com/npm/ajv In JavaScript: ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false, } const data = { foo: 1, bar: "abc" } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) ## Changes history See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) **Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) [Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](./LICENSE) # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # regexpp [![npm version](https://img.shields.io/npm/v/regexpp.svg)](https://www.npmjs.com/package/regexpp) [![Downloads/month](https://img.shields.io/npm/dm/regexpp.svg)](http://www.npmtrends.com/regexpp) [![Build Status](https://github.com/mysticatea/regexpp/workflows/CI/badge.svg)](https://github.com/mysticatea/regexpp/actions) [![codecov](https://codecov.io/gh/mysticatea/regexpp/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/regexpp) [![Dependency Status](https://david-dm.org/mysticatea/regexpp.svg)](https://david-dm.org/mysticatea/regexpp) A regular expression parser for ECMAScript. ## 💿 Installation ```bash $ npm install regexpp ``` - require Node.js 8 or newer. ## 📖 Usage ```ts import { AST, RegExpParser, RegExpValidator, RegExpVisitor, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST } from "regexpp" ``` ### parseRegExpLiteral(source, options?) Parse a given regular expression literal then make AST object. This is equivalent to `new RegExpParser(options).parseLiteral(source)`. - **Parameters:** - `source` (`string | RegExp`) The source code to parse. - `options?` ([`RegExpParser.Options`]) The options to parse. - **Return:** - The AST of the regular expression. ### validateRegExpLiteral(source, options?) Validate a given regular expression literal. This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. - **Parameters:** - `source` (`string`) The source code to validate. - `options?` ([`RegExpValidator.Options`]) The options to validate. ### visitRegExpAST(ast, handlers) Visit each node of a given AST. This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. ### RegExpParser #### new RegExpParser(options?) - **Parameters:** - `options?` ([`RegExpParser.Options`]) The options to parse. #### parser.parseLiteral(source, start?, end?) Parse a regular expression literal. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression. #### parser.parsePattern(source, start?, end?, uFlag?) Parse a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"abc"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. - **Return:** - The AST of the regular expression pattern. #### parser.parseFlags(source, start?, end?) Parse a regular expression flags. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"gim"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression flags. ### RegExpValidator #### new RegExpValidator(options) - **Parameters:** - `options` ([`RegExpValidator.Options`]) The options to validate. #### validator.validateLiteral(source, start, end) Validate a regular expression literal. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. #### validator.validatePattern(source, start, end, uFlag) Validate a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. #### validator.validateFlags(source, start, end) Validate a regular expression flags. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. ### RegExpVisitor #### new RegExpVisitor(handlers) - **Parameters:** - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. #### visitor.visit(ast) Validate a regular expression literal. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. ## 📰 Changelog - [GitHub Releases](https://github.com/mysticatea/regexpp/releases) ## 🍻 Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. - `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. - `npm run lint` runs ESLint. - `npm run update:test` updates test fixtures. - `npm run update:ids` updates `src/unicode/ids.ts`. - `npm run watch` runs tests with `--watch` option. [`AST.Node`]: src/ast.ts#L4 [`RegExpParser.Options`]: src/parser.ts#L539 [`RegExpValidator.Options`]: src/validator.ts#L127 [`RegExpVisitor.Handlers`]: src/visitor.ts#L204 # assemblyscript-regex A regex engine for AssemblyScript. [AssemblyScript](https://www.assemblyscript.org/) is a new language, based on TypeScript, that runs on WebAssembly. AssemblyScript has a lightweight standard library, but lacks support for Regular Expression. The project fills that gap! This project exposes an API that mirrors the JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class: ```javascript const regex = new RegExp("fo*", "g"); const str = "table football, foul"; let match: Match | null = regex.exec(str); while (match != null) { // first iteration // match.index = 6 // match.matches[0] = "foo" // second iteration // match.index = 16 // match.matches[0] = "fo" match = regex.exec(str); } ``` ## Project status The initial focus of this implementation has been feature support and functionality over performance. It currently supports a sufficient number of regex features to be considered useful, including most character classes, common assertions, groups, alternations, capturing groups and quantifiers. The next phase of development will focussed on more extensive testing and performance. The project currently has reasonable unit test coverage, focussed on positive and negative test cases on a per-feature basis. It also includes a more exhaustive test suite with test cases borrowed from another regex library. ### Feature support Based on the classfication within the [MDN cheatsheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) **Character sets** - [x] . - [x] \d - [x] \D - [x] \w - [x] \W - [x] \s - [x] \S - [x] \t - [x] \r - [x] \n - [x] \v - [x] \f - [ ] [\b] - [ ] \0 - [ ] \cX - [x] \xhh - [x] \uhhhh - [ ] \u{hhhh} or \u{hhhhh} - [x] \ **Assertions** - [x] ^ - [x] $ - [ ] \b - [ ] \B **Other assertions** - [ ] x(?=y) Lookahead assertion - [ ] x(?!y) Negative lookahead assertion - [ ] (?<=y)x Lookbehind assertion - [ ] (?<!y)x Negative lookbehind assertion **Groups and ranges** - [x] x|y - [x] [xyz][a-c] - [x] [^xyz][^a-c] - [x] (x) capturing group - [ ] \n back reference - [ ] (?<Name>x) named capturing group - [x] (?:x) Non-capturing group **Quantifiers** - [x] x\* - [x] x+ - [x] x? - [x] x{n} - [x] x{n,} - [x] x{n,m} - [ ] x\*? / x+? / ... **RegExp** - [x] global - [ ] sticky - [x] case insensitive - [x] multiline - [x] dotAll - [ ] unicode ### Development This project is open source, MIT licenced and your contributions are very much welcomed. To get started, check out the repository and install dependencies: ``` $ npm install ``` A few general points about the tools and processes this project uses: - This project uses prettier for code formatting and eslint to provide additional syntactic checks. These are both run on `npm test` and as part of the CI build. - The unit tests are executed using [as-pect](https://github.com/jtenner/as-pect) - a native AssemblyScript test runner - The specification tests are within the `spec` folder. The `npm run test:generate` target transforms these tests into as-pect tests which execute as part of the standard build / test cycle - In order to support improved debugging you can execute this library as TypeScript (rather than WebAssembly), via the `npm run tsrun` target. # Optionator <a name="optionator" /> Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). [About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format) ## Why? The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. $ cmd --halp Invalid option '--halp' - perhaps you meant '--help'? $ cmd --count str Invalid value for option 'count' - expected type Int, received value: str. Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. ## About Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. MIT license. Version 0.9.1 npm install optionator For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. ## Usage `require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. ```js var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` ### parse(input, parseOptions) `parse` processes the `input` according to your settings, and returns an object with the results. ##### arguments * input - `[String] | Object | String` - the input you wish to parse * parseOptions - `{slice: Int}` - all options optional - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) ##### returns `Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. ##### example ```js parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} parse('--count 2 positional'); // {count: 2, _: ['positional']} parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} ``` ### parseArgv(input) `parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. ##### arguments * input - `[String]` - the input you wish to parse ##### returns See "returns" section in "parse" ##### example ```js parseArgv(process.argv); ``` ### generateHelp(helpOptions) `generateHelp` produces help text based on your settings. ##### arguments * helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` ##### returns `String` - the generated help text ##### example ```js generateHelp(); /* "Usage: cmd [options] positional -h, --help displays help -c, --count Int number of things Version 1.0.0 "*/ ``` ### generateHelpForOption(optionName) `generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. ##### arguments * optionName - `String` - the name of the option to display ##### returns `String` - the generated help text for the option ##### example ```js generateHelpForOption('count'); /* "-c, --count Int description: number of things example: cmd --count 2 "*/ ``` ## Settings Format When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: { prepend: String, append: String, options: [{heading: String} | { option: String, alias: [String] | String, type: String, enum: [String], default: String, restPositional: Boolean, required: Boolean, overrideRequired: Boolean, dependsOn: [String] | String, concatRepeatedArrays: Boolean | (Boolean, Object), mergeRepeatedObjects: Boolean, description: String, longDescription: String, example: [String] | String }], helpStyle: { aliasSeparator: String, typeSeparator: String, descriptionSeparator: String, initialIndent: Int, secondaryIndent: Int, maxPadFactor: Number }, mutuallyExclusive: [[String | [String]]], concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object mergeRepeatedObjects: Boolean, // deprecated, set in defaults object positionalAnywhere: Boolean, typeAliases: Object, defaults: Object } All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. ### Top Level Properties * `prepend` is an optional string to be placed before the options in the help text * `append` is an optional string to be placed after the options in the help text * `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified * `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text * `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present * `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` * `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` * `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property #### Heading Properties * `heading` a required string, the name of the heading #### Option Properties * `option` the required name of the option - use dash-case, without the leading dashes * `alias` is an optional string or array of strings which specify any aliases for the option * `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it * `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` * `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` * `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument * `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined * `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags * `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. * `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` * `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set * `description` is an optional string, which will be displayed next to the option in the help text * `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used * `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used #### Help Style Properties * `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' * `typeSeparator` is an optional string, separates the type from the names - default: ' ' * `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' * `initialIndent` is an optional int - the amount of indent for options - default: 2 * `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 * `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 ## Argument Format At the highest level there are two types of arguments: named, and positional. Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. Everything after an `--` is positional, even if it looks like a named argument. You may optionally use `=` to separate option names from values, for example: `--count=2`. If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. If duplicate named arguments are present, the last one will be taken. ## Technical About `optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. # type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) <a name="type-check" /> `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). npm install type-check ## Quick Examples ```js // Basic types: var typeCheck = require('type-check').typeCheck; typeCheck('Number', 1); // true typeCheck('Number', 'str'); // false typeCheck('Error', new Error); // true typeCheck('Undefined', undefined); // true // Comment typeCheck('count::Number', 1); // true // One type OR another type: typeCheck('Number | String', 2); // true typeCheck('Number | String', 'str'); // true // Wildcard, matches all types: typeCheck('*', 2) // true // Array, all elements of a single type: typeCheck('[Number]', [1, 2, 3]); // true typeCheck('[Number]', [1, 'str', 3]); // false // Tuples, or fixed length arrays with elements of different types: typeCheck('(String, Number)', ['str', 2]); // true typeCheck('(String, Number)', ['str']); // false typeCheck('(String, Number)', ['str', 2, 5]); // false // Object properties: typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true typeCheck('{x: Number, y: Boolean}', {x: 2}); // false typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true // A particular type AND object properties: typeCheck('RegExp{source: String, ...}', /re/i); // true typeCheck('RegExp{source: String, ...}', {source: 're'}); // false // Custom types: var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; typeCheck('Even', 2, opt); // true // Nested: var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true ``` Check out the [type syntax format](#syntax) and [guide](#guide). ## Usage `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. ```js // typeCheck(type, input, options); typeCheck('Number', 2); // true // parseType(type); var parsedType = parseType('Number'); // object // parsedTypeCheck(parsedType, input, options); parsedTypeCheck(parsedType, 2); // true ``` ### typeCheck(type, input, options) `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js typeCheck('Number', 2); // true ``` ### parseType(type) `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to parse ##### returns `Object` - an object in the parsed type format representing the parsed type ##### example ```js parseType('Number'); // [{type: 'Number'}] ``` ### parsedTypeCheck(parsedType, input, options) `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js parsedTypeCheck([{type: 'Number'}], 2); // true var parsedType = parseType('String'); parsedTypeCheck(parsedType, 'str'); // true ``` <a name="type-format" /> ## Type Format ### Syntax White space is ignored. The root node is a __Types__. * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` ### Guide `type-check` uses `Object.toString` to find out the basic type of a value. Specifically, ```js {}.toString.call(VALUE).slice(8, -1) {}.toString.call(true).slice(8, -1) // 'Boolean' ``` A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. The wildcard `*` matches all types. There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. ## Options Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. <a name="custom-types" /> ### Custom Types __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; } } } }; typeCheck('Even', 2, options); // true typeCheck('Even', 3, options); // false ``` `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. ## Technical About `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. <h1 align="center">Enquirer</h1> <p align="center"> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version"> </a> <a href="https://travis-ci.org/enquirer/enquirer"> <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis"> </a> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br> <sub>>_ Prompts should be more like conversations than inquisitions▌</sub> </p> <br> <p align="center"> <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br> <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br> <a href="#built-in-prompts"><strong>See more prompt examples</strong></a> </p> <br> <br> Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases. * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_) * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb). * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement. * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos. * **Intuitive** - Keypress combos are available to simplify usage. * **Flexible** - All prompts can be used standalone or chained together. * **Stylish** - Easily override semantic styles and symbols for any part of the prompt. * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts). * **Pluggable** - Add advanced features to Enquirer using plugins. * **Validation** - Optionally validate user input with any prompt. * **Well tested** - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values. * **Examples** - There are numerous [examples](examples) available to help you get started. If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks! <br> <p align="center"> <b>>_ Ready to start making prompts your users will love? ▌</b><br> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750"> </p> <br> <br> ## ❯ Getting started Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts. * [Install](#-install) * [Usage](#-usage) * [Enquirer](#-enquirer) * [Prompts](#-prompts) - [Built-in Prompts](#-prompts) - [Custom Prompts](#-custom-prompts) * [Key Bindings](#-key-bindings) * [Options](#-options) * [Release History](#-release-history) * [Performance](#-performance) * [About](#-about) <br> ## ❯ Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install enquirer --save ``` Install with [yarn](https://yarnpkg.com/en/): ```sh $ yarn add enquirer ``` <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750"> </p> _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_ <br> ## ❯ Usage ### Single prompt The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method. ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); // { username: 'jonschlinkert' } ``` _(Examples with `await` need to be run inside an `async` function)_ ### Multiple prompts Pass an array of ["question" objects](#prompt-options) to run a series of prompts. ```js const response = await prompt([ { type: 'input', name: 'name', message: 'What is your name?' }, { type: 'input', name: 'username', message: 'What is your username?' } ]); console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' } ``` ### Different ways to run enquirer #### 1. By importing the specific `built-in prompt` ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Did you like enquirer?' }); prompt.run() .then(answer => console.log('Answer:', answer)); ``` #### 2. By passing the options to `prompt` ```js const { prompt } = require('enquirer'); prompt({ type: 'confirm', name: 'question', message: 'Did you like enquirer?' }) .then(answer => console.log('Answer:', answer)); ``` **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings) <br> ## ❯ Enquirer **Enquirer is a prompt runner** Add Enquirer to your JavaScript project with following line of code. ```js const Enquirer = require('enquirer'); ``` The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts. ```js const { prompt } = require('enquirer'); const question = [ { type: 'input', name: 'username', message: 'What is your username?' }, { type: 'password', name: 'password', message: 'What is your password?' } ]; let answers = await prompt(question); console.log(answers); ``` **Prompts control how values are rendered and returned** Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application. **How can I customize prompts?** Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt. All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`. Use this approach if you need to modify a prompt instance, or listen for events on the prompt. **Example** ```js const { Input } = require('enquirer'); const prompt = new Input({ name: 'username', message: 'What is your username?' }); prompt.run() .then(answer => console.log('Username:', answer)) .catch(console.error); ``` ### [Enquirer](index.js#L20) Create an instance of `Enquirer`. **Params** * `options` **{Object}**: (optional) Options to use with all prompts. * `answers` **{Object}**: (optional) Answers object to initialize with. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` ### [register()](index.js#L42) Register a custom prompt type. **Params** * `type` **{String}** * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class. * `returns` **{Object}**: Returns the Enquirer instance **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); enquirer.register('customType', require('./custom-prompt')); ``` ### [prompt()](index.js#L78) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const response = await enquirer.prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` ### [use()](index.js#L160) Use an enquirer plugin. **Params** * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer. * `returns` **{Object}**: Returns the Enquirer instance. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const plugin = enquirer => { // do stuff to enquire instance }; enquirer.use(plugin); ``` ### [Enquirer#prompt](index.js#L210) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` <br> ## ❯ Prompts This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept. **Getting started with Enquirer's prompts** * [Prompt](#prompt) - The base `Prompt` class used by other prompts - [Prompt Options](#prompt-options) * [Built-in prompts](#built-in-prompts) * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts * [Custom prompts](#%E2%9D%AF-custom-prompts) - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use. ### Prompt The base `Prompt` class is used to create all other prompts. ```js const { Prompt } = require('enquirer'); class MyCustomPrompt extends Prompt {} ``` See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works. #### Prompt Options Each prompt takes an options object (aka "question" object), that implements the following interface: ```js { // required type: string | function, name: string | function, message: string | function | async function, // optional skip: boolean | function | async function, initial: string | function | async function, format: function | async function, result: function | async function, validate: function | async function, } ``` Each property of the options object is described below: | **Property** | **Required?** | **Type** | **Description** | | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. | | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. | | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. | | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. | | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. | | `format` | no | `function` | Function to format user input in the terminal. | | `result` | no | `function` | Function to format the final submitted value before it's returned. | | `validate` | no | `function` | Function to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message. | **Example usage** ```js const { prompt } = require('enquirer'); const question = { type: 'input', name: 'username', message: 'What is your username?' }; prompt(question) .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` <br> ### Built-in prompts * [AutoComplete Prompt](#autocomplete-prompt) * [BasicAuth Prompt](#basicauth-prompt) * [Confirm Prompt](#confirm-prompt) * [Form Prompt](#form-prompt) * [Input Prompt](#input-prompt) * [Invisible Prompt](#invisible-prompt) * [List Prompt](#list-prompt) * [MultiSelect Prompt](#multiselect-prompt) * [Numeral Prompt](#numeral-prompt) * [Password Prompt](#password-prompt) * [Quiz Prompt](#quiz-prompt) * [Survey Prompt](#survey-prompt) * [Scale Prompt](#scale-prompt) * [Select Prompt](#select-prompt) * [Sort Prompt](#sort-prompt) * [Snippet Prompt](#snippet-prompt) * [Toggle Prompt](#toggle-prompt) ### AutoComplete Prompt Prompt that auto-completes as the user types, and returns the selected value as a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750"> </p> **Example Usage** ```js const { AutoComplete } = require('enquirer'); const prompt = new AutoComplete({ name: 'flavor', message: 'Pick your favorite flavor', limit: 10, initial: 2, choices: [ 'Almond', 'Apple', 'Banana', 'Blackberry', 'Blueberry', 'Cherry', 'Chocolate', 'Cinnamon', 'Coconut', 'Cranberry', 'Grape', 'Nougat', 'Orange', 'Pear', 'Pineapple', 'Raspberry', 'Strawberry', 'Vanilla', 'Watermelon', 'Wintergreen' ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **AutoComplete Options** | Option | Type | Default | Description | | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. | | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. | | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. | | `initial` | `number` | 0 | Preselected item in the list of choices. | | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) | **Related prompts** * [Select](#select-prompt) * [MultiSelect](#multiselect-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### BasicAuth Prompt Prompt that asks for username and password to authenticate the user. The default implementation of `authenticate` function in `BasicAuth` prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the `authenticate` function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750"> </p> **Example Usage** ```js const { BasicAuth } = require('enquirer'); const prompt = new BasicAuth({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '123', showPassword: true }); prompt .run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Confirm Prompt Prompt that returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750"> </p> **Example Usage** ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Want to answer?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Form Prompt Prompt that allows the user to enter and submit multiple values on a single terminal screen. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750"> </p> **Example Usage** ```js const { Form } = require('enquirer'); const prompt = new Form({ name: 'user', message: 'Please provide the following information:', choices: [ { name: 'firstname', message: 'First Name', initial: 'Jon' }, { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' }, { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' } ] }); prompt.run() .then(value => console.log('Answer:', value)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Input Prompt Prompt that takes user input and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750"> </p> **Example Usage** ```js const { Input } = require('enquirer'); const prompt = new Input({ message: 'What is your username?', initial: 'jonschlinkert' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.log); ``` You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)). **Related prompts** * [Confirm](#confirm-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Invisible Prompt Prompt that takes user input, hides it from the terminal, and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750"> </p> **Example Usage** ```js const { Invisible } = require('enquirer'); const prompt = new Invisible({ name: 'secret', message: 'What is your secret?' }); prompt.run() .then(answer => console.log('Answer:', { secret: answer })) .catch(console.error); ``` **Related prompts** * [Password](#password-prompt) * [Input](#input-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### List Prompt Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750"> </p> **Example Usage** ```js const { List } = require('enquirer'); const prompt = new List({ name: 'keywords', message: 'Type comma-separated keywords' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Sort](#sort-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### MultiSelect Prompt Prompt that allows the user to select multiple items from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750"> </p> **Example Usage** ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: ['aqua', 'blue', 'fuchsia'] ``` **Example key-value pairs** Optionally, pass a `result` function and use the `.map` method to return an object of key-value pairs of the selected names and values: [example](./examples/multiselect/option-result.js) ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ], result(names) { return this.map(names); } }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' } ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Numeral Prompt Prompt that takes a number as input. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750"> </p> **Example Usage** ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ name: 'number', message: 'Please enter a number' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Confirm](#confirm-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Password Prompt Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt) <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750"> </p> **Example Usage** ```js const { Password } = require('enquirer'); const prompt = new Password({ name: 'password', message: 'What is your password?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Invisible](#invisible-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Quiz Prompt Prompt that allows the user to play multiple-choice quiz questions. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750"> </p> **Example Usage** ```js const { Quiz } = require('enquirer'); const prompt = new Quiz({ name: 'countries', message: 'How many countries are there in the world?', choices: ['165', '175', '185', '195', '205'], correctChoice: 3 }); prompt .run() .then(answer => { if (answer.correct) { console.log('Correct!'); } else { console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); } }) .catch(console.error); ``` **Quiz Options** | Option | Type | Required | Description | | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | | `choices` | `array` | Yes | The list of possible answers to the quiz question. | | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. | **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Survey Prompt Prompt that allows the user to provide feedback for a list of questions. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"> </p> **Example Usage** ```js const { Survey } = require('enquirer'); const prompt = new Survey({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.' }, { name: 'navigation', message: 'The website is easy to navigate.' }, { name: 'images', message: 'The website usually has good images.' }, { name: 'upload', message: 'The website makes it easy to upload images.' }, { name: 'colors', message: 'The website has a pleasing color palette.' } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [Scale](#scale-prompt) * [Snippet](#snippet-prompt) * [Select](#select-prompt) *** ### Scale Prompt A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale). <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750"> </p> **Example Usage** ```js const { Scale } = require('enquirer'); const prompt = new Scale({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.', initial: 2 }, { name: 'navigation', message: 'The website is easy to navigate.', initial: 2 }, { name: 'images', message: 'The website usually has good images.', initial: 2 }, { name: 'upload', message: 'The website makes it easy to upload images.', initial: 2 }, { name: 'colors', message: 'The website has a pleasing color palette.', initial: 2 } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Select Prompt Prompt that allows the user to select from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750"> </p> **Example Usage** ```js const { Select } = require('enquirer'); const prompt = new Select({ name: 'color', message: 'Pick a flavor', choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [MultiSelect](#multiselect-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Sort Prompt Prompt that allows the user to sort items in a list. **Example** In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750"> </p> **Example Usage** ```js const colors = require('ansi-colors'); const { Sort } = require('enquirer'); const prompt = new Sort({ name: 'colors', message: 'Sort the colors in order of preference', hint: 'Top is best, bottom is worst', numbered: true, choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ name: n, message: colors[n](n) })) }); prompt.run() .then(function(answer = []) { console.log(answer); console.log('Your preferred order of colors is:'); console.log(answer.map(key => colors[key](key)).join('\n')); }) .catch(console.error); ``` **Related prompts** * [List](#list-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Snippet Prompt Prompt that allows the user to replace placeholders in a snippet of code or text. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750"> </p> **Example Usage** ```js const semver = require('semver'); const { Snippet } = require('enquirer'); const prompt = new Snippet({ name: 'username', message: 'Fill out the fields in package.json', required: true, fields: [ { name: 'author_name', message: 'Author Name' }, { name: 'version', validate(value, state, item, index) { if (item && item.name === 'version' && !semver.valid(value)) { return prompt.styles.danger('version should be a valid semver value'); } return true; } } ], template: `{ "name": "\${name}", "description": "\${description}", "version": "\${version}", "homepage": "https://github.com/\${username}/\${name}", "author": "\${author_name} (https://github.com/\${username})", "repository": "\${username}/\${name}", "license": "\${license:ISC}" } ` }); prompt.run() .then(answer => console.log('Answer:', answer.result)) .catch(console.error); ``` **Related prompts** * [Survey](#survey-prompt) * [AutoComplete](#autocomplete-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Toggle Prompt Prompt that allows the user to toggle between two values then returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750"> </p> **Example Usage** ```js const { Toggle } = require('enquirer'); const prompt = new Toggle({ message: 'Want to answer?', enabled: 'Yep', disabled: 'Nope' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Confirm](#confirm-prompt) * [Input](#input-prompt) * [Sort](#sort-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Prompt Types There are 5 (soon to be 6!) type classes: * [ArrayPrompt](#arrayprompt) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [Choices](#choices) - [Defining choices](#defining-choices) - [Choice properties](#choice-properties) - [Related prompts](#related-prompts) * [AuthPrompt](#authprompt) * [BooleanPrompt](#booleanprompt) * DatePrompt (Coming Soon!) * [NumberPrompt](#numberprompt) * [StringPrompt](#stringprompt) Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how. ### ArrayPrompt The `ArrayPrompt` class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the [Select](#select) and [Survey](#survey) prompts. #### Options In addition to the [options](#options) available to all prompts, Array prompts also support the following options. | **Option** | **Required?** | **Type** | **Description** | | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | | | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. | | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. | | | #### Properties Array prompts have the following instance properties and getters. | **Property name** | **Type** | **Description** | | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. | | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. | | `enabled` | `array` | Returns an array of enabled choices. | | `focused` | `array` | Returns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is _focused_, the list will scroll to the focused choice and re-render. | | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. | | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. | | `limit` | `number` | The number of choices to display on-screen. | | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. | | `visible` | `string` | | #### Methods | **Method** | **Description** | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pointer()` | Returns the visual symbol to use to identify the choice that currently has focus. The `❯` symbol is often used for this. The pointer is not always visible, as with the `autocomplete` prompt. | | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. | | `focus()` | Sets focus on a choice, if it can be focused. | #### Choices Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal. **Type**: `string|object` **Example** ```js const { prompt } = require('enquirer'); const questions = [{ type: 'select', name: 'color', message: 'Favorite color?', initial: 1, choices: [ { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object ] }]; let answers = await prompt(questions); console.log('Answer:', answers.color); ``` #### Defining choices Whether defined as a string or object, choices are normalized to the following interface: ```js { name: string; message: string | undefined; value: string | undefined; hint: string | undefined; disabled: boolean | string | undefined; } ``` **Example** ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: ['Apple', 'Orange', 'Raspberry'] }; ``` Normalizes to the following when the prompt is run: ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: [ { name: 'Apple', message: 'Apple', value: 'Apple' }, { name: 'Orange', message: 'Orange', value: 'Orange' }, { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } ] }; ``` #### Choice properties The following properties are supported on `choice` objects. | **Option** | **Type** | **Description** | | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The unique key to identify a choice | | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. | | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. | | `choices` | `array` | Array of "child" choices. | | `hint` | `string` | Help message to display next to a choice. | | `role` | `string` | Determines how the choice will be displayed. Currently the only role supported is `separator`. Additional roles may be added in the future (like `heading`, etc). Please create a [feature request] | | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). | | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. | | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). | #### Related prompts * [AutoComplete](#autocomplete-prompt) * [Form](#form-prompt) * [MultiSelect](#multiselect-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) *** ### AuthPrompt The `AuthPrompt` is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the [BasicAuth Prompt](#basicauth-prompt). You can also find prompt examples in `examples/auth/` folder that utilizes `AuthPrompt` to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others. `AuthPrompt` has a factory function that creates an instance of `AuthPrompt` class and it expects an `authenticate` function, as an argument, which overrides the `authenticate` function of the `AuthPrompt` class. #### Methods | **Method** | **Description** | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticate()` | Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default `authenticate` function throws an error if no other function is provided. | #### Choices Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt). **Example** ```js const { AuthPrompt } = require('enquirer'); function authenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } const CustomAuthPrompt = AuthPrompt.create(authenticate); const prompt = new CustomAuthPrompt({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '1234567', choices: [ { name: 'username', message: 'username' }, { name: 'password', message: 'password' } ] }); prompt .run() .then(answer => console.log('Authenticated?', answer)) .catch(console.error); ``` #### Related prompts * [BasicAuth Prompt](#basicauth-prompt) *** ### BooleanPrompt The `BooleanPrompt` class is used for creating prompts that display and return a boolean value. ```js const { BooleanPrompt } = require('enquirer'); const prompt = new BooleanPrompt({ header: '========================', message: 'Do you love enquirer?', footer: '========================', }); prompt.run() .then(answer => console.log('Selected:', answer)) .catch(console.error); ``` **Returns**: `boolean` *** ### NumberPrompt The `NumberPrompt` class is used for creating prompts that display and return a numerical value. ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ header: '************************', message: 'Input the Numbers:', footer: '************************', }); prompt.run() .then(answer => console.log('Numbers are:', answer)) .catch(console.error); ``` **Returns**: `string|number` (number, or number formatted as a string) *** ### StringPrompt The `StringPrompt` class is used for creating prompts that display and return a string value. ```js const { StringPrompt } = require('enquirer'); const prompt = new StringPrompt({ header: '************************', message: 'Input the String:', footer: '************************' }); prompt.run() .then(answer => console.log('String is:', answer)) .catch(console.error); ``` **Returns**: `string` <br> ## ❯ Custom prompts With Enquirer 2.0, custom prompts are easier than ever to create and use. **How do I create a custom prompt?** Custom prompts are created by extending either: * Enquirer's `Prompt` class * one of the built-in [prompts](#-prompts), or * low-level [types](#-types). <!-- Example: HaiKarate Custom Prompt --> ```js const { Prompt } = require('enquirer'); class HaiKarate extends Prompt { constructor(options = {}) { super(options); this.value = options.initial || 0; this.cursorHide(); } up() { this.value++; this.render(); } down() { this.value--; this.render(); } render() { this.clear(); // clear previously rendered prompt from the terminal this.write(`${this.state.message}: ${this.value}`); } } // Use the prompt by creating an instance of your custom prompt class. const prompt = new HaiKarate({ message: 'How many sprays do you want?', initial: 10 }); prompt.run() .then(answer => console.log('Sprays:', answer)) .catch(console.error); ``` If you want to be able to specify your prompt by `type` so that it may be used alongside other prompts, you will need to first create an instance of `Enquirer`. ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` Then use the `.register()` method to add your custom prompt. ```js enquirer.register('haikarate', HaiKarate); ``` Now you can do the following when defining "questions". ```js let spritzer = require('cologne-drone'); let answers = await enquirer.prompt([ { type: 'haikarate', name: 'cologne', message: 'How many sprays do you need?', initial: 10, async onSubmit(name, value) { await spritzer.activate(value); //<= activate drone return value; } } ]); ``` <br> ## ❯ Key Bindings ### All prompts These key combinations may be used with all prompts. | **command** | **description** | | -------------------------------- | -------------------------------------- | | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. | | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. | <br> ### Move cursor These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>left</kbd> | Move the cursor back one character. | | <kbd>right</kbd> | Move the cursor forward one character. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> ### Edit Input These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> | **command (Mac)** | **command (Windows)** | **description** | | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. | | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. | | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | ### Select choices These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true. | **command** | **description** | | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. | | <kbd>i</kbd> | Invert the current selection of choices. | | <kbd>g</kbd> | Toggle the current choice group. | <br> ### Hide/show choices | **command** | **description** | | ------------------------------- | ---------------------------------------------- | | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. | | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. | <br> ### Move/lock Pointer | **command** | **description** | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>up</kbd> | Move the pointer up. | | <kbd>down</kbd> | Move the pointer down. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. | | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). | | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). | <br> | **command (Mac)** | **command (Windows)** | **description** | | -------------------------------- | --------------------- | ---------------------------------------------------------- | | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. | | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. | <br> ## ❯ Release History Please see [CHANGELOG.md](CHANGELOG.md). ## ❯ Performance ### System specs MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB. ### Load time Time it takes for the module to load the first time (average of 3 runs): ``` enquirer: 4.013ms inquirer: 286.717ms ``` <br> ## ❯ About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Todo We're currently working on documentation for the following items. Please star and watch the repository for updates! * [ ] Customizing symbols * [ ] Customizing styles (palette) * [ ] Customizing rendered input * [ ] Customizing returned values * [ ] Customizing key bindings * [ ] Question validation * [ ] Choice validation * [ ] Skipping questions * [ ] Async choices * [ ] Async timers: loaders, spinners and other animations * [ ] Links to examples </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ```sh $ yarn && yarn test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> #### Contributors | **Commits** | **Contributor** | | --- | --- | | 283 | [jonschlinkert](https://github.com/jonschlinkert) | | 82 | [doowb](https://github.com/doowb) | | 32 | [rajat-sr](https://github.com/rajat-sr) | | 20 | [318097](https://github.com/318097) | | 15 | [g-plane](https://github.com/g-plane) | | 12 | [pixelass](https://github.com/pixelass) | | 5 | [adityavyas611](https://github.com/adityavyas611) | | 5 | [satotake](https://github.com/satotake) | | 3 | [tunnckoCore](https://github.com/tunnckoCore) | | 3 | [Ovyerus](https://github.com/Ovyerus) | | 3 | [sw-yx](https://github.com/sw-yx) | | 2 | [DanielRuf](https://github.com/DanielRuf) | | 2 | [GabeL7r](https://github.com/GabeL7r) | | 1 | [AlCalzone](https://github.com/AlCalzone) | | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) | | 1 | [danieldelcore](https://github.com/danieldelcore) | | 1 | [ImgBotApp](https://github.com/ImgBotApp) | | 1 | [jsonkao](https://github.com/jsonkao) | | 1 | [knpwrs](https://github.com/knpwrs) | | 1 | [yeskunall](https://github.com/yeskunall) | | 1 | [mischah](https://github.com/mischah) | | 1 | [renarsvilnis](https://github.com/renarsvilnis) | | 1 | [sbugert](https://github.com/sbugert) | | 1 | [stephencweiss](https://github.com/stephencweiss) | | 1 | [skellock](https://github.com/skellock) | | 1 | [whxaxes](https://github.com/whxaxes) | #### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) #### Credit Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts. #### License Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` ## assemblyscript-temporal An implementation of temporal within AssemblyScript, with an initial focus on non-timezone-aware classes and functionality. ### Why? AssemblyScript has minimal `Date` support, however, the JS Date API itself is terrible and people tend not to use it that often. As a result libraries like moment / luxon have become staple replacements. However, there is now a [relatively mature TC39 proposal](https://github.com/tc39/proposal-temporal) that adds greatly improved date support to JS. The goal of this project is to implement Temporal for AssemblyScript. ### Usage This library currently supports the following types: #### `PlainDateTime` A `PlainDateTime` represents a calendar date and wall-clock time that does not carry time zone information, e.g. December 7th, 1995 at 3:00 PM (in the Gregorian calendar). For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindatetime.html), this implementation follows the specification as closely as possible. You can create a `PlainDateTime` from individual components, a string or an object literal: ```javascript datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.year; // 2019; datetime.month; // 11; // ... datetime.nanosecond; // 789; datetime = PlainDateTime.from("1976-11-18T12:34:56"); datetime.toString(); // "1976-11-18T12:34:56" datetime = PlainDateTime.from({ year: 1966, month: 3, day: 3 }); datetime.toString(); // "1966-03-03T00:00:00" ``` There are various ways you can manipulate a date: ```javascript // use 'with' to copy a date but with various property values overriden datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.with({ year: 2019 }).toString(); // "2019-11-18T15:23:30.123456789" // use 'add' or 'substract' to add / subtract a duration datetime = PlainDateTime.from("2020-01-12T15:00"); datetime.add({ months: 1 }).toString(); // "2020-02-12T15:00:00"); // add / subtract support Duration objects or object literals datetime.add(new Duration(1)).toString(); // "2021-01-12T15:00:00"); ``` You can compare dates and check for equality ```javascript dt1 = PlainDateTime.from("1976-11-18"); dt2 = PlainDateTime.from("2019-10-29"); PlainDateTime.compare(dt1, dt1); // 0 PlainDateTime.compare(dt1, dt2); // -1 dt1.equals(dt1); // true ``` Currently `PlainDateTime` only supports the ISO 8601 (Gregorian) calendar. #### `PlainDate` A `PlainDate` object represents a calendar date that is not associated with a particular time or time zone, e.g. August 24th, 2006. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindate.html), this implementation follows the specification as closely as possible. The `PlainDate` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainTime` A `PlainTime` object represents a wall-clock time that is not associated with a particular date or time zone, e.g. 7:39 PM. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaintime.html), this implementation follows the specification as closely as possible. The `PlainTime` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainMonthDay` A date without a year component. This is useful to express things like "Bastille Day is on the 14th of July". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainmonthday.html) , this implementation follows the specification as closely as possible. ```javascript const monthDay = PlainMonthDay.from({ month: 7, day: 14 }); // => 07-14 const date = monthDay.toPlainDate({ year: 2030 }); // => 2030-07-14 date.dayOfWeek; // => 7 ``` The `PlainMonthDay` API is almost identical to `PlainDateTime`, so see above for more API usage examples. #### `PlainYearMonth` A date without a day component. This is useful to express things like "the October 2020 meeting". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainyearmonth.html) , this implementation follows the specification as closely as possible. The `PlainYearMonth` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `now` The `now` object has several methods which give information about the current time and date. ```javascript dateTime = now.plainDateTimeISO(); dateTime.toString(); // 2021-04-01T12:05:47.357 ``` ## Contributing This project is open source, MIT licensed and your contributions are very much welcomed. There is a [brief document that outlines implementation progress and priorities](./development.md). # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) [![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## Enterprise support json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # flat-cache > A stupidly simple key/value storage using files to persist the data [![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) [![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache) ## install ```bash npm i --save flat-cache ``` ## Usage ```js var flatCache = require('flat-cache') // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var cache = flatCache.load('cacheId'); // sets a key on the cache cache.setKey('key', { foo: 'var' }); // get a key from the cache cache.getKey('key') // { foo: 'var' } // fetch the entire persisted object cache.all() // { 'key': { foo: 'var' } } // remove a key cache.removeKey('key'); // removes a key from the cache // save it to disk cache.save(); // very important, if you don't save no changes will be persisted. // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys // loads the cache from a given directory, if one does // not exists for the given Id a new one will be prepared to be created var cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); // The following methods are useful to clear the cache // delete a given cache flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists. // delete all cache flatCache.clearAll(); // remove the cache directory ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` storage was needed and Bam! this module was born. ## Important notes - If no directory is especified when the `load` method is called, a folder named `.cache` will be created inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you might want to ignore the default `.cache` folder, or specify a custom directory. - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references - All the changes to the cache state are done to memory - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module intentionally dumb and simple - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call like: `cache.save( true /* noPrune */ )`. ## License MIT ## Changelog [changelog](./changelog.md) # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # eslint-utils [![npm version](https://img.shields.io/npm/v/eslint-utils.svg)](https://www.npmjs.com/package/eslint-utils) [![Downloads/month](https://img.shields.io/npm/dm/eslint-utils.svg)](http://www.npmtrends.com/eslint-utils) [![Build Status](https://github.com/mysticatea/eslint-utils/workflows/CI/badge.svg)](https://github.com/mysticatea/eslint-utils/actions) [![Coverage Status](https://codecov.io/gh/mysticatea/eslint-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-utils) [![Dependency Status](https://david-dm.org/mysticatea/eslint-utils.svg)](https://david-dm.org/mysticatea/eslint-utils) ## 🏁 Goal This package provides utility functions and classes for make ESLint custom rules. For examples: - [getStaticValue](https://eslint-utils.mysticatea.dev/api/ast-utils.html#getstaticvalue) evaluates static value on AST. - [ReferenceTracker](https://eslint-utils.mysticatea.dev/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. ## 📖 Usage See [documentation](https://eslint-utils.mysticatea.dev/). ## 📰 Changelog See [releases](https://github.com/mysticatea/eslint-utils/releases). ## ❤️ Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run clean` removes the coverage result of `npm test` command. - `npm run coverage` shows the coverage result of the last `npm test` command. - `npm run lint` runs ESLint. - `npm run watch` runs tests on each file change. # `asbuild` [![Stars](https://img.shields.io/github/stars/AssemblyScript/asbuild.svg?style=social&maxAge=3600&label=Star)](https://github.com/AssemblyScript/asbuild/stargazers) *A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.* ## 🚩 Table of Contents - [Installing](#-installing) - [Usage](#-usage) - [`asb init`](#asb-init---create-an-empty-project) - [`asb test`](#asb-test---run-as-pect-tests) - [`asb fmt`](#asb-fmt---format-as-files-using-eslint) - [`asb run`](#asb-run---run-a-wasi-binary) - [`asb build`](#asb-build---compile-the-project-using-asc) - [Background](#-background) ## 🔧 Installing Install it globally ``` npm install -g asbuild ``` Or, locally as dev dependencies ``` npm install --save-dev asbuild ``` ## 💡 Usage ``` Build tool for AssemblyScript projects. Usage: asb [command] [options] Commands: asb Alias of build command, to maintain back-ward compatibility [default] asb build Compile a local package and all of its dependencies [aliases: compile, make] asb init [baseDir] Create a new AS package in an given directory asb test Run as-pect tests asb fmt [paths..] This utility formats current module using eslint. [aliases: format, lint] Options: --version Show version number [boolean] --help Show help [boolean] ``` ### `asb init` - Create an empty project ``` asb init [baseDir] Create a new AS package in an given directory Positionals: baseDir Create a sample AS project in this directory [string] [default: "."] Options: --version Show version number [boolean] --help Show help [boolean] --yes Skip the interactive prompt [boolean] [default: false] ``` ### `asb test` - Run as-pect tests ``` asb test Run as-pect tests USAGE: asb test [options] -- [aspect_options] Options: --version Show version number [boolean] --help Show help [boolean] --verbose, --vv Print out arguments passed to as-pect [boolean] [default: false] ``` ### `asb fmt` - Format AS files using ESlint ``` asb fmt [paths..] This utility formats current module using eslint. Positionals: paths Paths to format [array] [default: ["."]] Initialisation: --init Generates recommended eslint config for AS Projects [boolean] Miscellaneous --lint, --dry-run Tries to fix problems without saving the changes to the file system [boolean] [default: false] Options: --version Show version number [boolean] --help Show help ``` ### `asb run` - Run a WASI binary ``` asb run Run a WASI binary USAGE: asb run [options] [binary path] -- [binary options] Positionals: binary path to Wasm binary [string] [required] Options: --version Show version number [boolean] --help Show help [boolean] --preopen, -p comma separated list of directories to open. [default: "."] ``` ### `asb build` - Compile the project using asc ``` asb build Compile a local package and all of its dependencies USAGE: asb build [entry_file] [options] -- [asc_options] Options: --version Show version number [boolean] --help Show help [boolean] --baseDir, -d Base directory of project. [string] [default: "."] --config, -c Path to asconfig file [string] [default: "./asconfig.json"] --wat Output wat file to outDir [boolean] [default: false] --outDir Directory to place built binaries. Default "./build/<target>/" [string] --target Target for compilation [string] [default: "release"] --verbose Print out arguments passed to asc [boolean] [default: false] Examples: asb build Build release of 'assembly/index.ts to build/release/packageName.wasm asb build --target release Build a release binary asb build -- --measure Pass argument to 'asc' ``` #### Defaults ##### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ##### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./tests/build_test) ## 📖 Background Asbuild started as wrapper around `asc` to provide an easier CLI interface and now has been extened to support other commands like `init`, `test` and `fmt` just like `cargo` to become a one stop build tool for AS Projects. ## 📜 License This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/). # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Aliases Create custom aliases for styles. ```js const colors = require('ansi-colors'); colors.alias('primary', colors.yellow); colors.alias('secondary', colors.bold); console.log(colors.primary.secondary('Foo')); ``` ## Themes A theme is an object of custom aliases. ```js const colors = require('ansi-colors'); colors.theme({ danger: colors.red, dark: colors.dim.gray, disabled: colors.gray, em: colors.italic, heading: colors.bold.underline, info: colors.cyan, muted: colors.dim, primary: colors.blue, strong: colors.bold, success: colors.green, underline: colors.underline, warning: colors.yellow }); // Now, we can use our custom styles alongside the built-in styles! console.log(colors.danger.strong.em('Error!')); console.log(colors.warning('Heads up!')); console.log(colors.info('Did you know...')); console.log(colors.success.bold('It worked!')); ``` ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 48 | [jonschlinkert](https://github.com/jonschlinkert) | | 42 | [doowb](https://github.com/doowb) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._ <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.mjs': '/absolute/path/to/interpret/mjs-stub.js', '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', 'sucrase/register/ts', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', 'sucrase/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg [![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) [![Build Status](https://travis-ci.org/eslint/espree.svg?branch=master)](https://travis-ci.org/eslint/espree) [![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) # Espree Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. ## Usage Install: ``` npm i espree ``` And in your Node.js code: ```javascript const espree = require("espree"); const ast = espree.parse(code); ``` ## API ### `parse()` `parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). ```javascript const espree = require("espree"); const ast = espree.parse(code, options); ``` **Example :** ```js const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); console.log(ast); ``` <details><summary>Output</summary> <p> ``` Node { type: 'Program', start: 0, end: 15, body: [ Node { type: 'VariableDeclaration', start: 0, end: 15, declarations: [Array], kind: 'let' } ], sourceType: 'script' } ``` </p> </details> ### `tokenize()` `tokenize` returns the tokens of a given code. It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array **Example :** ```js const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); console.log(tokens); ``` <details><summary>Output</summary> <p> ``` Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, Token { type: 'String', value: '"bar"', start: 10, end: 15 } ``` </p> </details> ### `version` Returns the current `espree` version ### `VisitorKeys` Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) ### `latestEcmaVersion` Returns the latest ECMAScript supported by `espree` ### `supportedEcmaVersions` Returns an array of all supported ECMAScript versions ## Options ```js const options = { // attach range information to each node range: false, // attach line/column location information to each node loc: false, // create a top-level comments array containing all comments comment: false, // create a top-level tokens array containing all tokens tokens: false, // Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming. ecmaVersion: 5, // specify which type of script you're parsing ("script" or "module") sourceType: "script", // specify additional language features ecmaFeatures: { // enable JSX parsing jsx: false, // enable return in global scope globalReturn: false, // enable implied strict mode (if ecmaVersion >= 5) impliedStrict: false } } ``` ## Esprima Compatibility Going Forward The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. Espree may also deviate from Esprima in the interface it exposes. ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). Espree is licensed under a permissive BSD 2-clause license. ## Security Policy We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting * `npm run browserify` - creates a version of Espree that is usable in a browser ## Differences from Espree 2.x * The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. * Trailing whitespace no longer is counted as part of a node. * `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. * The `esparse` and `esvalidate` binary scripts have been removed. * There is no `tolerant` option. We will investigate adding this back in the future. ## Known Incompatibilities In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. ### Esprima 1.2.2 * Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. * Espree does not parse `let` and `const` declarations by default. * Error messages returned for parsing errors are different. * There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. ### Esprima 2.x * Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. ## Frequently Asked Questions ### Why another parser [ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. ### Have you tried working with Esprima? Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. ### Why don't you just use Acorn? Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. ### What ECMAScript features do you support? Espree supports all ECMAScript 2020 features and partially supports ECMAScript 2021 features. Because ECMAScript 2021 is still under development, we are implementing features as they are finalized. Currently, Espree supports: * [Logical Assignment Operators](https://github.com/tc39/proposal-logical-assignment) * [Numeric Separators](https://github.com/tc39/proposal-numeric-separator) See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. ### How do you determine which experimental features to support? In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. functional-red-black-tree ========================= A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. # Install npm install functional-red-black-tree # Example Here is an example of some basic usage: ```javascript //Load the library var createTree = require("functional-red-black-tree") //Create a tree var t1 = createTree() //Insert some items into the tree var t2 = t1.insert(1, "foo") var t3 = t2.insert(2, "bar") //Remove something var t4 = t3.remove(1) ``` # API ```javascript var createTree = require("functional-red-black-tree") ``` ## Overview - [Tree methods](#tree-methods) - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) - [`tree.keys`](#treekeys) - [`tree.values`](#treevalues) - [`tree.length`](#treelength) - [`tree.get(key)`](#treegetkey) - [`tree.insert(key, value)`](#treeinsertkey-value) - [`tree.remove(key)`](#treeremovekey) - [`tree.find(key)`](#treefindkey) - [`tree.ge(key)`](#treegekey) - [`tree.gt(key)`](#treegtkey) - [`tree.lt(key)`](#treeltkey) - [`tree.le(key)`](#treelekey) - [`tree.at(position)`](#treeatposition) - [`tree.begin`](#treebegin) - [`tree.end`](#treeend) - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) - [`tree.root`](#treeroot) - [Node properties](#node-properties) - [`node.key`](#nodekey) - [`node.value`](#nodevalue) - [`node.left`](#nodeleft) - [`node.right`](#noderight) - [Iterator methods](#iterator-methods) - [`iter.key`](#iterkey) - [`iter.value`](#itervalue) - [`iter.node`](#iternode) - [`iter.tree`](#itertree) - [`iter.index`](#iterindex) - [`iter.valid`](#itervalid) - [`iter.clone()`](#iterclone) - [`iter.remove()`](#iterremove) - [`iter.update(value)`](#iterupdatevalue) - [`iter.next()`](#iternext) - [`iter.prev()`](#iterprev) - [`iter.hasNext`](#iterhasnext) - [`iter.hasPrev`](#iterhasprev) ## Tree methods ### `var tree = createTree([compare])` Creates an empty functional tree * `compare` is an optional comparison function, same semantics as array.sort() **Returns** An empty tree ordered by `compare` ### `tree.keys` A sorted array of all the keys in the tree ### `tree.values` An array array of all the values in the tree ### `tree.length` The number of items in the tree ### `tree.get(key)` Retrieves the value associated to the given key * `key` is the key of the item to look up **Returns** The value of the first node associated to `key` ### `tree.insert(key, value)` Creates a new tree with the new pair inserted. * `key` is the key of the item to insert * `value` is the value of the item to insert **Returns** A new tree with `key` and `value` inserted ### `tree.remove(key)` Removes the first item with `key` in the tree * `key` is the key of the item to remove **Returns** A new tree with the given item removed if it exists ### `tree.find(key)` Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. ### `tree.ge(key)` Find the first item in the tree whose key is `>= key` * `key` is the key to search for **Returns** An iterator at the given element. ### `tree.gt(key)` Finds the first item in the tree whose key is `> key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.lt(key)` Finds the last item in the tree whose key is `< key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.le(key)` Finds the last item in the tree whose key is `<= key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.at(position)` Finds an iterator starting at the given element * `position` is the index at which the iterator gets created **Returns** An iterator starting at position ### `tree.begin` An iterator pointing to the first element in the tree ### `tree.end` An iterator pointing to the last element in the tree ### `tree.forEach(visitor(key,value)[, lo[, hi]])` Walks a visitor function over the nodes of the tree in order. * `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. * `lo` is an optional start of the range to visit (inclusive) * `hi` is an optional end of the range to visit (non-inclusive) **Returns** The last value returned by the callback ### `tree.root` Returns the root node of the tree ## Node properties Each node of the tree has the following properties: ### `node.key` The key associated to the node ### `node.value` The value associated to the node ### `node.left` The left subtree of the node ### `node.right` The right subtree of the node ## Iterator methods ### `iter.key` The key of the item referenced by the iterator ### `iter.value` The value of the item referenced by the iterator ### `iter.node` The value of the node at the iterator's current position. `null` is iterator is node valid. ### `iter.tree` The tree associated to the iterator ### `iter.index` Returns the position of this iterator in the sequence. ### `iter.valid` Checks if the iterator is valid ### `iter.clone()` Makes a copy of the iterator ### `iter.remove()` Removes the item at the position of the iterator **Returns** A new binary search tree with `iter`'s item removed ### `iter.update(value)` Updates the value of the node in the tree at this iterator **Returns** A new binary search tree with the corresponding node updated ### `iter.next()` Advances the iterator to the next position ### `iter.prev()` Moves the iterator backward one element ### `iter.hasNext` If true, then the iterator is not at the end of the sequence ### `iter.hasPrev` If true, then the iterator is not at the beginning of the sequence # Credits (c) 2013 Mikola Lysenko. MIT License # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. # file-entry-cache > Super simple cache for file metadata, useful for process that work o a given series of files > and that only need to repeat the job on the changed ones since the previous run of the process — Edit [![NPM Version](http://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) [![Build Status](http://img.shields.io/travis/royriojas/file-entry-cache.svg?style=flat)](https://travis-ci.org/royriojas/file-entry-cache) ## install ```bash npm i --save file-entry-cache ``` ## Usage The module exposes two functions `create` and `createFromFile`. ## `create(cacheName, [directory, useCheckSum])` - **cacheName**: the name of the cache to be created - **directory**: Optional the directory to load the cache from - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ## `createFromFile(pathToCache, [useCheckSum])` - **pathToCache**: the path to the cache file (this combines the cache name and directory) - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ```js // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var fileEntryCache = require('file-entry-cache'); var cache = fileEntryCache.create('testCache'); var files = expand('../fixtures/*.txt'); // the first time this method is called, will return all the files var oFiles = cache.getUpdatedFiles(files); // this will persist this to disk checking each file stats and // updating the meta attributes `size` and `mtime`. // custom fields could also be added to the meta object and will be persisted // in order to retrieve them later cache.reconcile(); // use this if you want the non visited file entries to be kept in the cache // for more than one execution // // cache.reconcile( true /* noPrune */) // on a second run var cache2 = fileEntryCache.create('testCache'); // will return now only the files that were modified or none // if no files were modified previous to the execution of this function var oFiles = cache.getUpdatedFiles(files); // if you want to prevent a file from being considered non modified // something useful if a file failed some sort of validation // you can then remove the entry from the cache doing cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` // that will effectively make the file to appear again as modified until the validation is passed. In that // case you should not remove it from the cache // if you need all the files, so you can determine what to do with the changed ones // you can call var oFiles = cache.normalizeEntries(files); // oFiles will be an array of objects like the following entry = { key: 'some/name/file', the path to the file changed: true, // if the file was changed since previous run meta: { size: 3242, // the size of the file mtime: 231231231, // the modification time of the file data: {} // some extra field stored for this file (useful to save the result of a transformation on the file } } ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with optional file persistance. The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, then store the new state of the files. The next time this module request for `getChangedFiles` will return only the files that were modified. Making the process to end faster. This module could also be used by processes that modify the files applying a transform, in that case the result of the transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed the transformed stored data could be used instead of actually applying the transformation, saving time in case of only a few files changed. In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. ## Important notes - The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values - All the changes to the cache state are done to memory first and only persisted after reconcile. ## License MIT [![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) This package is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy to use and powerful. It was first released in 2010 and is tested against big data sets by a large community. ## Documentation * [Project homepage](http://csv.js.org/stringify/) * [API](http://csv.js.org/stringify/api/) * [Options](http://csv.js.org/stringify/options/) * [Examples](http://csv.js.org/stringify/examples/) ## Main features * Follow the Node.js streaming API * Simplicity with the optional callback API * Support for custom formatters, delimiters, quotes, escape characters and header * Support big datasets * Complete test coverage and samples for inspiration * Only 1 external dependency * to be used conjointly with `csv-generate`, `csv-parse` and `stream-transform` * MIT License ## Usage The module is built on the Node.js Stream API. For the sake of simplicity, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: ```javascript const stringify = require('csv-stringify') const assert = require('assert') // import stringify from 'csv-stringify' // import assert from 'assert/strict' const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] stringify(input, function(err, output) { const expected = '1,2,3,4\na,b,c,d\n' assert.strictEqual(output, expected, `output.should.eql ${expected}`) console.log("Passed.", output) }) ``` ## Development Tests are executed with mocha. To install it, run `npm install` followed by `npm test`. It will install mocha and its dependencies in your project "node_modules" directory and run the test suite. The tests run against the CoffeeScript source files. To generate the JavaScript files, run `npm run build`. The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node-csv-stringify). See the [Travis definition file](https://github.com/adaltas/node-csv-stringify/blob/master/.travis.yml) to view the tested Node.js version. ## Contributors * David Worms: <https://github.com/wdavidw> [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform [examples]: http://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv [![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) [![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) [![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) <br /> [![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) [![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) [![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) # ESLint [Website](https://eslint.org) | [Configuring](https://eslint.org/docs/user-guide/configuring) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | [Code of Conduct](https://eslint.org/conduct) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://eslint.org/chat) ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. ## Table of Contents 1. [Installation and Usage](#installation-and-usage) 2. [Configuration](#configuration) 3. [Code of Conduct](#code-of-conduct) 4. [Filing Issues](#filing-issues) 5. [Frequently Asked Questions](#faq) 6. [Releases](#releases) 7. [Security Policy](#security-policy) 8. [Semantic Versioning Policy](#semantic-versioning-policy) 9. [Stylistic Rule Updates](#stylistic-rule-updates) 10. [License](#license) 11. [Team](#team) 12. [Sponsors](#sponsors) 13. [Technology Sponsors](#technology-sponsors) ## <a name="installation-and-usage"></a>Installation and Usage Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install ESLint using npm: ``` $ npm install eslint --save-dev ``` You should then set up a configuration file: ``` $ ./node_modules/.bin/eslint --init ``` After that, you can run ESLint on any file or directory like this: ``` $ ./node_modules/.bin/eslint yourfile.js ``` ## <a name="configuration"></a>Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: ```json { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). ## <a name="code-of-conduct"></a>Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://eslint.org/conduct). ## <a name="filing-issues"></a>Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: * [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) * [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) ## <a name="faq"></a>Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. ### Why can't ESLint find my plugins? * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. * Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. ### What ECMAScript versions does ESLint support? ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). ### What about experimental features? ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). ### Why doesn't ESLint lock dependency versions? Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. ## <a name="releases"></a>Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. ## <a name="security-policy"></a>Security Policy ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## <a name="semantic-versioning-policy"></a>Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: * Patch release (intended to not break your lint build) * A bug fix in a rule that results in ESLint reporting fewer linting errors. * A bug fix to the CLI or core (including formatters). * Improvements to documentation. * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). * Minor release (might break your lint build) * A bug fix in a rule that results in ESLint reporting more linting errors. * A new rule is created. * A new option to an existing rule that does not result in ESLint reporting more linting errors by default. * A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. * An existing rule is deprecated. * A new CLI capability is created. * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). * A new formatter is created. * `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). * Major release (likely to break your lint build) * `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). * A new option to an existing rule that results in ESLint reporting more linting errors by default. * An existing formatter is removed. * Part of the public API is removed or changed in an incompatible way. The public API includes: * Rule schemas * Configuration schema * Command-line options * Node.js API * Rule, formatter, parser, plugin APIs According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. ## <a name="stylistic-rule-updates"></a>Stylistic Rule Updates Stylistic rules are frozen according to [our policy](https://eslint.org/blog/2020/05/changes-to-rules-policies) on how we evaluate new rules and rule changes. This means: * **Bug fixes**: We will still fix bugs in stylistic rules. * **New ECMAScript features**: We will also make sure stylistic rules are compatible with new ECMAScript features. * **New options**: We will **not** add any new options to stylistic rules unless an option is the only way to fix a bug or support a newly-added ECMAScript feature. ## <a name="license"></a>License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) ## <a name="team"></a>Team These folks keep the project moving and are resources for help. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--teamstart--> ### Technical Steering Committee (TSC) The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/nzakas"> <img src="https://github.com/nzakas.png?s=75" width="75" height="75"><br /> Nicholas C. Zakas </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/btmills"> <img src="https://github.com/btmills.png?s=75" width="75" height="75"><br /> Brandon Mills </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/mdjermanovic"> <img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br /> Milos Djermanovic </a> </td></tr></tbody></table> ### Reviewers The people who review and implement new features. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/mysticatea"> <img src="https://github.com/mysticatea.png?s=75" width="75" height="75"><br /> Toru Nagashima </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/aladdin-add"> <img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br /> 薛定谔的猫 </a> </td></tr></tbody></table> ### Committers The people who review and fix bugs and help triage issues. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/brettz9"> <img src="https://github.com/brettz9.png?s=75" width="75" height="75"><br /> Brett Zamir </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/bmish"> <img src="https://github.com/bmish.png?s=75" width="75" height="75"><br /> Bryan Mishkin </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/g-plane"> <img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br /> Pig Fang </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/anikethsaha"> <img src="https://github.com/anikethsaha.png?s=75" width="75" height="75"><br /> Anix </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/yeonjuan"> <img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br /> YeonJuan </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/snitin315"> <img src="https://github.com/snitin315.png?s=75" width="75" height="75"><br /> Nitin Kumar </a> </td></tr></tbody></table> <!--teamend--> ## <a name="sponsors"></a>Sponsors The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--sponsorsstart--> <h3>Platinum Sponsors</h3> <p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3> <p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p> <!--sponsorsend--> ## <a name="technology-sponsors"></a>Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) * Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) * Password management is sponsored by [1Password](https://www.1password.com) # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Timezone support In order to provide support for timezones, without relying on the JavaScript host or any other time-zone aware environment, this library makes use of teh IANA Timezone Database directly: https://www.iana.org/time-zones The database files are parsed by the scripts in this folder, which emit AssemblyScript code which is used to process the various rules at runtime. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) ### Status: Work in progress Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP/HTTPS Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true ### WS/WSS Support URI.parse("wss://example.com/foo?bar=baz"); //returns: //{ // scheme : "wss", // host: "example.com", // resourceName: "/foo?bar=baz", // secure: true, //} URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "uuid", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: npm install uri-js # OR yarn add uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind Shims used when bundling asc for browser usage. discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` # AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation Node.js version 8 and up: `$ npm install cross-spawn` Node.js version 7 and under: `$ npm install cross-spawn@6` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: [demo](https://estools.github.io/esquery/) The following selectors are supported: * AST node type: `ForStatement` * [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` * [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` * [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` * attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` * attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` * nested attribute: `[attr.level2="foo"]` * field: `FunctionDeclaration > Identifier.id` * [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` * [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` * [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` * [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` * [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` * [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` * [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` * [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` * [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)` * [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` * [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` * class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` [![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) # is-core-module <sup>[![Version Badge][2]][1]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module [codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module [actions-url]: https://github.com/inspect-js/is-core-module/actions # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0,4.1,4.2?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. [![build status](https://app.travis-ci.com/dankogai/js-base64.svg)](https://app.travis-ci.com/github/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.encode(latin, true)); // ZGFua29nYWk skips padding Base64.encodeURI(latin)); // ZGFua29nYWk Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.decode( 'ZGFua29nYWk'); // dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend Uint8Array.prototype Base64.extendUint8Array(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IEs before 11. Do the following in your shell. ```shell $ make base64.es5.js ``` ## Brief History * Since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. * Since version 3.7 `base64.js` is ES5-compatible again (hence IE11-compabile). * Since 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above) [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # rechoir [![Build Status](https://secure.travis-ci.org/tkellen/js-rechoir.png)](http://travis-ci.org/tkellen/js-rechoir) > Require any supported file as a node module. [![NPM](https://nodei.co/npm/rechoir.png)](https://nodei.co/npm/rechoir/) ## What is it? This module, in conjunction with [interpret]-like objects can register any file type the npm ecosystem has a module loader for. This library is a dependency of [Liftoff]. ## API ### prepare(config, filepath, requireFrom) Look for a module loader associated with the provided file and attempt require it. If necessary, run any setup required to inject it into [require.extensions](http://nodejs.org/api/globals.html#globals_require_extensions). `config` An [interpret]-like configuration object. `filepath` A file whose type you'd like to register a module loader for. `requireFrom` An optional path to start searching for the module required to load the requested file. Defaults to the directory of `filepath`. If calling this method is successful (aka: it doesn't throw), you can now require files of the type you requested natively. An error with a `failures` property will be thrown if the module loader(s) configured for a given extension cannot be registered. If a loader is already registered, this will simply return `true`. **Note:** While rechoir will automatically load and register transpilers like `coffee-script`, you must provide a local installation. The transpilers are **not** bundled with this module. #### Usage ```js const config = require('interpret').extensions; const rechoir = require('rechoir'); rechoir.prepare(config, './test/fixtures/test.coffee'); rechoir.prepare(config, './test/fixtures/test.csv'); rechoir.prepare(config, './test/fixtures/test.toml'); console.log(require('./test/fixtures/test.coffee')); console.log(require('./test/fixtures/test.csv')); console.log(require('./test/fixtures/test.toml')); ``` [interpret]: http://github.com/tkellen/js-interpret [Liftoff]: http://github.com/tkellen/js-liftoff ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) calificaciones ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `calificaciones.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `calificaciones.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account calificaciones.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'calificaciones.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages ## Test Strategy - tests are copied from the [polyfill implementation](https://github.com/tc39/proposal-temporal/tree/main/polyfill/test) - tests should be removed if they relate to features that do not make sense for TS/AS, i.e. tests that validate the shape of an object do not make sense in a language with compile-time type checking - tests that fail because a feature has not been implemented yet should be left as failures. Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/eslint/doctrine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/doctrine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Doctrine Doctrine is a [JSDoc](http://usejsdoc.org) parser that parses documentation comments from JavaScript (you need to pass in the comment, not a whole JavaScript file). ## Installation You can install Doctrine using [npm](https://npmjs.com): ``` $ npm install doctrine --save-dev ``` Doctrine can also be used in web browsers using [Browserify](http://browserify.org). ## Usage Require doctrine inside of your JavaScript: ```js var doctrine = require("doctrine"); ``` ### parse() The primary method is `parse()`, which accepts two arguments: the JSDoc comment to parse and an optional options object. The available options are: * `unwrap` - set to `true` to delete the leading `/**`, any `*` that begins a line, and the trailing `*/` from the source text. Default: `false`. * `tags` - an array of tags to return. When specified, Doctrine returns only tags in this array. For example, if `tags` is `["param"]`, then only `@param` tags will be returned. Default: `null`. * `recoverable` - set to `true` to keep parsing even when syntax errors occur. Default: `false`. * `sloppy` - set to `true` to allow optional parameters to be specified in brackets (`@param {string} [foo]`). Default: `false`. * `lineNumbers` - set to `true` to add `lineNumber` to each node, specifying the line on which the node is found in the source. Default: `false`. * `range` - set to `true` to add `range` to each node, specifying the start and end index of the node in the original comment. Default: `false`. Here's a simple example: ```js var ast = doctrine.parse( [ "/**", " * This function comment is parsed by doctrine", " * @param {{ok:String}} userName", "*/" ].join('\n'), { unwrap: true }); ``` This example returns the following AST: { "description": "This function comment is parsed by doctrine", "tags": [ { "title": "param", "description": null, "type": { "type": "RecordType", "fields": [ { "type": "FieldType", "key": "ok", "value": { "type": "NameExpression", "name": "String" } } ] }, "name": "userName" } ] } See the [demo page](http://eslint.org/doctrine/demo/) more detail. ## Team These folks keep the project moving and are resources for help: * Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) - project lead * Yusuke Suzuki ([@constellation](https://github.com/constellation)) - reviewer ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/doctrine/issues). ## Frequently Asked Questions ### Can I pass a whole JavaScript file to Doctrine? No. Doctrine can only parse JSDoc comments, so you'll need to pass just the JSDoc comment to Doctrine in order to work. ### License #### doctrine Copyright JS Foundation and other contributors, https://js.foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #### esprima some of functions is derived from esprima Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #### closure-compiler some of extensions is derived from closure-compiler Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ ### Where to ask for help? Join our [Chatroom](https://gitter.im/eslint/doctrine) [npm-image]: https://img.shields.io/npm/v/doctrine.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/doctrine [travis-image]: https://img.shields.io/travis/eslint/doctrine/master.svg?style=flat-square [travis-url]: https://travis-ci.org/eslint/doctrine [coveralls-image]: https://img.shields.io/coveralls/eslint/doctrine/master.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/eslint/doctrine?branch=master [downloads-image]: http://img.shields.io/npm/dm/doctrine.svg?style=flat-square [downloads-url]: https://www.npmjs.com/package/doctrine [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png [1]: https://travis-ci.org/litejs/natural-compare-lite [2]: https://coveralls.io/r/litejs/natural-compare-lite [npm package]: https://npmjs.org/package/natural-compare-lite [GitHub repo]: https://github.com/litejs/natural-compare-lite @version 1.4.0 @date 2015-10-26 @stability 3 - Stable Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2] =============== Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering". ```text Standard sorting: Natural order sorting: img1.png img1.png img10.png img2.png img12.png img10.png img2.png img12.png ``` String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function. ### Installation - In browser ```html <script src=min.natural-compare.js></script> ``` - In node.js: `npm install natural-compare-lite` ```javascript require("natural-compare-lite") ``` ### Usage ```javascript // Simple case sensitive example var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; a.sort(String.naturalCompare); // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] // Use wrapper function for case insensitivity a.sort(function(a, b){ return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); }) // In most cases we want to sort an array of objects var a = [ {"street":"350 5th Ave", "room":"A-1021"} , {"street":"350 5th Ave", "room":"A-21046-b"} ]; // sort by street, then by room a.sort(function(a, b){ return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); }) // When text transformation is needed (eg toLowerCase()), // it is best for performance to keep // transformed key in that object. // There are no need to do text transformation // on each comparision when sorting. var a = [ {"make":"Audi", "model":"A6"} , {"make":"Kia", "model":"Rio"} ]; // sort by make, then by model a.map(function(car){ car.sort_key = (car.make + " " + car.model).toLowerCase(); }) a.sort(function(a, b){ return String.naturalCompare(a.sort_key, b.sort_key); }) ``` - Works well with dates in ISO format eg "Rev 2012-07-26.doc". ### Custom alphabet It is possible to configure a custom alphabet to achieve a desired order. ```javascript // Estonian alphabet String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" ["t", "z", "x", "õ"].sort(String.naturalCompare) // ["z", "t", "õ", "x"] // Russian alphabet String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" ["Ё", "А", "Б"].sort(String.naturalCompare) // ["А", "Б", "Ё"] ``` External links -------------- - [GitHub repo][https://github.com/litejs/natural-compare-lite] - [jsperf test](http://jsperf.com/natural-sort-2/12) Licence ------- Copyright (c) 2012-2015 Lauri Rooden &lt;[email protected]&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value = <JSON.Value>valueOrNull; // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let innerString = (<JSON.Str>value).valueOf(); let jsonString = (<JSON.Str>value).stringify(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: string = encoder.stringify(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i64): void { // Handle field } setFloat(name: string, value: f64): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) # line-column [![Build Status](https://travis-ci.org/io-monad/line-column.svg?branch=master)](https://travis-ci.org/io-monad/line-column) [![Coverage Status](https://coveralls.io/repos/github/io-monad/line-column/badge.svg?branch=master)](https://coveralls.io/github/io-monad/line-column?branch=master) [![npm version](https://badge.fury.io/js/line-column.svg)](https://badge.fury.io/js/line-column) Node module to convert efficiently index to/from line-column in a string. ## Install npm install line-column ## Usage ### lineColumn(str, options = {}) Returns a `LineColumnFinder` instance for given string `str`. #### Options | Key | Description | Default | | ------- | ----------- | ------- | | `origin` | The origin value of line number and column number | `1` | ### lineColumn(str, index) This is just a shorthand for `lineColumn(str).fromIndex(index)`. ### LineColumnFinder#fromIndex(index) Find line and column from index in the string. Parameters: - `index` - `number` Index in the string. (0-origin) Returns: - `{ line: x, col: y }` Found line number and column number. - `null` if the given index is out of range. ### LineColumnFinder#toIndex(line, column) Find index from line and column in the string. Parameters: - `line` - `number` Line number in the string. - `column` - `number` Column number in the string. or - `{ line: x, col: y }` - `Object` line and column numbers in the string.<br>A key name `column` can be used instead of `col`. or - `[ line, col ]` - `Array` line and column numbers in the string. Returns: - `number` Found index in the string. - `-1` if the given line or column is out of range. ## Example ```js var lineColumn = require("line-column"); var testString = [ "ABCDEFG\n", // line:0, index:0 "HIJKLMNOPQRSTU\n", // line:1, index:8 "VWXYZ\n", // line:2, index:23 "日本語の文字\n", // line:3, index:29 "English words" // line:4, index:36 ].join(""); // length:49 lineColumn(testString).fromIndex(3) // { line: 1, col: 4 } lineColumn(testString).fromIndex(33) // { line: 4, col: 5 } lineColumn(testString).toIndex(1, 4) // 3 lineColumn(testString).toIndex(4, 5) // 33 // Shorthand of .fromIndex (compatible with find-line-column) lineColumn(testString, 33) // { line:4, col: 5 } // Object or Array is also acceptable lineColumn(testString).toIndex({ line: 4, col: 5 }) // 33 lineColumn(testString).toIndex({ line: 4, column: 5 }) // 33 lineColumn(testString).toIndex([4, 5]) // 33 // You can cache it for the same string. It is so efficient. (See benchmark) var finder = lineColumn(testString); finder.fromIndex(33) // { line: 4, column: 5 } finder.toIndex(4, 5) // 33 // For 0-origin line and column numbers var oneOrigin = lineColumn(testString, { origin: 0 }); oneOrigin.fromIndex(33) // { line: 3, column: 4 } oneOrigin.toIndex(3, 4) // 33 ``` ## Testing npm test ## Benchmark The popular package [find-line-column](https://www.npmjs.com/package/find-line-column) provides the same "index to line-column" feature. Here is some benchmarking on `line-column` vs `find-line-column`. You can run this benchmark by `npm run benchmark`. See [benchmark/](benchmark/) for the source code. ``` long text + line-column (not cached) x 72,989 ops/sec ±0.83% (89 runs sampled) long text + line-column (cached) x 13,074,242 ops/sec ±0.32% (89 runs sampled) long text + find-line-column x 33,887 ops/sec ±0.54% (84 runs sampled) short text + line-column (not cached) x 1,636,766 ops/sec ±0.77% (82 runs sampled) short text + line-column (cached) x 21,699,686 ops/sec ±1.04% (82 runs sampled) short text + find-line-column x 382,145 ops/sec ±1.04% (85 runs sampled) ``` As you might have noticed, even not cached version of `line-column` is 2x - 4x faster than `find-line-column`, and cached version of `line-column` is remarkable 50x - 380x faster. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT (See LICENSE) # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` # Acorn-JSX [![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) [![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. ## Transpiler Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. ## Usage Requiring this module provides you with an Acorn plugin that you can use like this: ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');"); ``` Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `[email protected]`. If you still want to opt-in to support of such constructions, you can pass the following option: ```javascript acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) ``` Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: ```javascript acorn.Parser.extend(jsx({ allowNamespaces: false })) ``` Note that by default `allowNamespaces` is enabled for spec compliancy. ## License This plugin is issued under the [MIT license](./LICENSE). # word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 10.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # lodash.merge v4.6.2 The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.merge ``` In Node.js: ```js var merge = require('lodash.merge'); ``` See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 (2020, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 10. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ``` <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv v7 beta is released [Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: - to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. - to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. - to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. - schemas are compiled to ES6 code (ES5 code generation is supported with an option). - to improve reliability and maintainability the code is migrated to TypeScript. **Please note**: - the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). - all formats are separated to ajv-formats package - they have to be explicitely added if you use them. See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. To install the new version: ```bash npm install ajv@beta ``` See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. ## Mozilla MOSS grant and OpenJS Foundation [<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. # lodash.truncate v4.4.2 The [lodash](https://lodash.com/) method `_.truncate` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.truncate ``` In Node.js: ```js var truncate = require('lodash.truncate'); ``` See the [documentation](https://lodash.com/docs#truncate) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.truncate) for more details. # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # node-supports-preserve-symlinks-flag <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] Determine if the current node version supports the `--preserve-symlinks` flag. ## Example ```js var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); var assert = require('assert'); assert.equal(supportsPreserveSymlinks, null); // in a browser assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag [npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag [dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg [dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies [npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg [downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag [codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag [actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions <a name="table"></a> # Table > Produces a string that represents array data in a text table. [![Github action status](https://github.com/gajus/table/actions/workflows/main.yml/badge.svg)](https://github.com/gajus/table/actions) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) [![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical) [![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas) * [Table](#table) * [Features](#table-features) * [Install](#table-install) * [Usage](#table-usage) * [API](#table-api) * [table](#table-api-table-1) * [createStream](#table-api-createstream) * [getBorderCharacters](#table-api-getbordercharacters) ![Demo of table displaying a list of missions to the Moon.](./.README/demo.png) <a name="table-features"></a> ## Features * Works with strings containing [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) characters. * Works with strings containing [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). * Configurable border characters. * Configurable content alignment per column. * Configurable content padding per column. * Configurable column width. * Text wrapping. <a name="table-install"></a> ## Install ```bash npm install table ``` [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) [![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) <a name="table-usage"></a> ## Usage ```js import { table } from 'table'; // Using commonjs? // const { table } = require('table'); const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; console.log(table(data)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ ``` <a name="table-api"></a> ## API <a name="table-api-table-1"></a> ### table Returns the string in the table format **Parameters:** - **_data_:** The data to display - Type: `any[][]` - Required: `true` - **_config_:** Table configuration - Type: `object` - Required: `false` <a name="table-api-table-1-config-border"></a> ##### config.border Type: `{ [type: string]: string }`\ Default: `honeywell` [template](#getbordercharacters) Custom borders. The keys are any of: - `topLeft`, `topRight`, `topBody`,`topJoin` - `bottomLeft`, `bottomRight`, `bottomBody`, `bottomJoin` - `joinLeft`, `joinRight`, `joinBody`, `joinJoin` - `bodyLeft`, `bodyRight`, `bodyJoin` - `headerJoin` ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: { topBody: `─`, topJoin: `┬`, topLeft: `┌`, topRight: `┐`, bottomBody: `─`, bottomJoin: `┴`, bottomLeft: `└`, bottomRight: `┘`, bodyLeft: `│`, bodyRight: `│`, bodyJoin: `│`, joinBody: `─`, joinLeft: `├`, joinRight: `┤`, joinJoin: `┼` } }; console.log(table(data, config)); ``` ``` ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ ``` <a name="table-api-table-1-config-drawverticalline"></a> ##### config.drawVerticalLine Type: `(lineIndex: number, columnCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a vertical line. This callback is called for each vertical border of the table. If the table has `n` columns, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawVerticalLine: (lineIndex, columnCount) => { return lineIndex === 0 || lineIndex === columnCount; } }; console.log(table(data, config)); ``` ``` ╔════════════╗ ║ 0A 0B 0C ║ ╟────────────╢ ║ 1A 1B 1C ║ ╟────────────╢ ║ 2A 2B 2C ║ ╟────────────╢ ║ 3A 3B 3C ║ ╟────────────╢ ║ 4A 4B 4C ║ ╚════════════╝ ``` <a name="table-api-table-1-config-drawhorizontalline"></a> ##### config.drawHorizontalLine Type: `(lineIndex: number, rowCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a horizontal line. This callback is called for each horizontal border of the table. If the table has `n` rows, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. If the table has `n` rows and contains the header, then the range will be `[0, n+1]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawHorizontalLine: (lineIndex, rowCount) => { return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount - 1 || lineIndex === rowCount; } }; console.log(table(data, config)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ║ 2A │ 2B │ 2C ║ ║ 3A │ 3B │ 3C ║ ╟────┼────┼────╢ ║ 4A │ 4B │ 4C ║ ╚════╧════╧════╝ ``` <a name="table-api-table-1-config-singleline"></a> ##### config.singleLine Type: `boolean`\ Default: `false` If `true`, horizontal lines inside the table are not drawn. This option also overrides the `config.drawHorizontalLine` if specified. ```js const data = [ ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], ]; const config = { singleLine: true }; console.log(table(data, config)); ``` ``` ╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ ║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ ║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ ║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ ║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ ║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ ║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ ╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ ``` <a name="table-api-table-1-config-columns"></a> ##### config.columns Type: `Column[] | { [columnIndex: number]: Column }` Column specific configurations. <a name="table-api-table-1-config-columns-config-columns-width"></a> ###### config.columns[*].width Type: `number`\ Default: the maximum cell widths of the column Column width (excluding the paddings). ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: { 1: { width: 10 } } }; console.log(table(data, config)); ``` ``` ╔════╤════════════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────────────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────────────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════════════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-alignment"></a> ###### config.columns[*].alignment Type: `'center' | 'justify' | 'left' | 'right'`\ Default: `'left'` Cell content horizontal alignment ```js const data = [ ['0A', '0B', '0C', '0D 0E 0F'], ['1A', '1B', '1C', '1D 1E 1F'], ['2A', '2B', '2C', '2D 2E 2F'], ]; const config = { columnDefault: { width: 10, }, columns: [ { alignment: 'left' }, { alignment: 'center' }, { alignment: 'right' }, { alignment: 'justify' } ], }; console.log(table(data, config)); ``` ``` ╔════════════╤════════════╤════════════╤════════════╗ ║ 0A │ 0B │ 0C │ 0D 0E 0F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C │ 1D 1E 1F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C │ 2D 2E 2F ║ ╚════════════╧════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-verticalalignment"></a> ###### config.columns[*].verticalAlignment Type: `'top' | 'middle' | 'bottom'`\ Default: `'top'` Cell content vertical alignment ```js const data = [ ['A', 'B', 'C', 'DEF'], ]; const config = { columnDefault: { width: 1, }, columns: [ { verticalAlignment: 'top' }, { verticalAlignment: 'middle' }, { verticalAlignment: 'bottom' }, ], }; console.log(table(data, config)); ``` ``` ╔═══╤═══╤═══╤═══╗ ║ A │ │ │ D ║ ║ │ B │ │ E ║ ║ │ │ C │ F ║ ╚═══╧═══╧═══╧═══╝ ``` <a name="table-api-table-1-config-columns-config-columns-paddingleft"></a> ###### config.columns[*].paddingLeft Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the left. <a name="table-api-table-1-config-columns-config-columns-paddingright"></a> ###### config.columns[*].paddingRight Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the right. The `paddingLeft` and `paddingRight` options do not count on the column width. So the column has `width = 5`, `paddingLeft = 2` and `paddingRight = 2` will have the total width is `9`. ```js const data = [ ['0A', 'AABBCC', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: [ { paddingLeft: 3 }, { width: 2, paddingRight: 3 } ] }; console.log(table(data, config)); ``` ``` ╔══════╤══════╤════╗ ║ 0A │ AA │ 0C ║ ║ │ BB │ ║ ║ │ CC │ ║ ╟──────┼──────┼────╢ ║ 1A │ 1B │ 1C ║ ╟──────┼──────┼────╢ ║ 2A │ 2B │ 2C ║ ╚══════╧══════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-truncate"></a> ###### config.columns[*].truncate Type: `number`\ Default: `Infinity` The number of characters is which the content will be truncated. To handle a content that overflows the container width, `table` package implements [text wrapping](#config.columns[*].wrapWord). However, sometimes you may want to truncate content that is too long to be displayed in the table. ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20, truncate: 100 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convall… ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-wrapword"></a> ###### config.columns[*].wrapWord Type: `boolean`\ Default: `false` The `table` package implements auto text wrapping, i.e., text that has the width greater than the container width will be separated into multiple lines at the nearest space or one of the special characters: `\|/_.,;-`. When `wrapWord` is `false`: ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convallis ║ ║ dapibus. Nunc venena ║ ║ tis tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` When `wrapWord` is `true`: ``` ╔══════════════════════╗ ║ Lorem ipsum dolor ║ ║ sit amet, ║ ║ consectetur ║ ║ adipiscing elit. ║ ║ Phasellus pulvinar ║ ║ nibh sed mauris ║ ║ convallis dapibus. ║ ║ Nunc venenatis ║ ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columndefault"></a> ##### config.columnDefault Type: `Column`\ Default: `{}` The default configuration for all columns. Column-specific settings will overwrite the default values. <a name="table-api-table-1-config-header"></a> ##### config.header Type: `object` Header configuration. *Deprecated in favor of the new spanning cells API.* The header configuration inherits the most of the column's, except: - `content` **{string}**: the header content. - `width:` calculate based on the content width automatically. - `alignment:` `center` be default. - `verticalAlignment:` is not supported. - `config.border.topJoin` will be `config.border.topBody` for prettier. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ]; const config = { columnDefault: { width: 10, }, header: { alignment: 'center', content: 'THE HEADER\nThis is the table about something', }, } console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════╗ ║ THE HEADER ║ ║ This is the table about something ║ ╟────────────┬────────────┬────────────╢ ║ 0A │ 0B │ 0C ║ ╟────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C ║ ╟────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C ║ ╚════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-spanningcells"></a> ##### config.spanningCells Type: `SpanningCellConfig[]` Spanning cells configuration. The configuration should be straightforward: just specify an array of minimal cell configurations including the position of top-left cell and the number of columns and/or rows will be expanded from it. The content of overlap cells will be ignored to make the `data` shape be consistent. By default, the configuration of column that the top-left cell belongs to will be applied to the whole spanning cell, except: * The `width` will be summed up of all spanning columns. * The `paddingRight` will be received from the right-most column intentionally. Advances customized column-like styles can be configurable to each spanning cell to overwrite the default behavior. ```js const data = [ ['Test Coverage Report', '', '', '', '', ''], ['Module', 'Component', 'Test Cases', 'Failures', 'Durations', 'Success Rate'], ['Services', 'User', '50', '30', '3m 7s', '60.0%'], ['', 'Payment', '100', '80', '7m 15s', '80.0%'], ['Subtotal', '', '150', '110', '10m 22s', '73.3%'], ['Controllers', 'User', '24', '18', '1m 30s', '75.0%'], ['', 'Payment', '30', '24', '50s', '80.0%'], ['Subtotal', '', '54', '42', '2m 20s', '77.8%'], ['Total', '', '204', '152', '12m 42s', '74.5%'], ]; const config = { columns: [ { alignment: 'center', width: 12 }, { alignment: 'center', width: 10 }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' } ], spanningCells: [ { col: 0, row: 0, colSpan: 6 }, { col: 0, row: 2, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 4, colSpan: 2, alignment: 'right'}, { col: 0, row: 5, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 7, colSpan: 2, alignment: 'right' }, { col: 0, row: 8, colSpan: 2, alignment: 'right' } ], }; console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Test Coverage Report ║ ╟──────────────┬────────────┬────────────┬──────────┬───────────┬──────────────╢ ║ Module │ Component │ Test Cases │ Failures │ Durations │ Success Rate ║ ╟──────────────┼────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 50 │ 30 │ 3m 7s │ 60.0% ║ ║ Services ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 100 │ 80 │ 7m 15s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 150 │ 110 │ 10m 22s │ 73.3% ║ ╟──────────────┬────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 24 │ 18 │ 1m 30s │ 75.0% ║ ║ Controllers ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 30 │ 24 │ 50s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 54 │ 42 │ 2m 20s │ 77.8% ║ ╟───────────────────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Total │ 204 │ 152 │ 12m 42s │ 74.5% ║ ╚═══════════════════════════╧════════════╧══════════╧═══════════╧══════════════╝ ``` <a name="table-api-createstream"></a> ### createStream `table` package exports `createStream` function used to draw a table and append rows. **Parameter:** - _**config:**_ the same as `table`'s, except `config.columnDefault.width` and `config.columnCount` must be provided. ```js import { createStream } from 'table'; const config = { columnDefault: { width: 50 }, columnCount: 1 }; const stream = createStream(config); setInterval(() => { stream.write([new Date()]); }, 500); ``` ![Streaming current date.](./.README/api/stream/streaming.gif) `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { createStream } from 'table'; import _ from 'lodash'; const config = { columnDefault: { width: 50 }, columnCount: 3, columns: [ { width: 10, alignment: 'right' }, { alignment: 'center' }, { width: 10 } ] }; const stream = createStream(config); let i = 0; setInterval(() => { let random; random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/api/stream/streaming-random.gif) <a name="table-api-getbordercharacters"></a> ### getBorderCharacters **Parameter:** - **_template_** - Type: `'honeywell' | 'norc' | 'ramac' | 'void'` - Required: `true` You can load one of the predefined border templates using `getBorderCharacters` function. ```js import { table, getBorderCharacters } from 'table'; const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: getBorderCharacters(`name of the template`) }; console.log(table(data, config)); ``` ``` # honeywell ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ # norc ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ # ramac (ASCII; for use in terminals that do not support Unicode characters) +----+----+----+ | 0A | 0B | 0C | |----|----|----| | 1A | 1B | 1C | |----|----|----| | 2A | 2B | 2C | +----+----+----+ # void (no borders; see "borderless table" section of the documentation) 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` Raise [an issue](https://github.com/gajus/table/issues) if you'd like to contribute a new border template. <a name="table-api-getbordercharacters-borderless-table"></a> #### Borderless Table Simply using `void` border character template creates a table with a lot of unnecessary spacing. To create a more pleasant to the eye table, reset the padding and remove the joining rows, e.g. ```js const output = table(data, { border: getBorderCharacters('void'), columnDefault: { paddingLeft: 0, paddingRight: 1 }, drawHorizontalLine: () => false } ); console.log(output); ``` ``` 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` # levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" /> __Light ECMAScript (JavaScript) Value Notation__ Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. __How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. npm install levn For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). ## Quick Examples ```js var parse = require('levn').parse; parse('Number', '2'); // 2 parse('String', '2'); // '2' parse('String', 'levn'); // 'levn' parse('String', 'a b'); // 'a b' parse('Boolean', 'true'); // true parse('Date', '#2011-11-11#'); // (Date object) parse('Date', '2011-11-11'); // (Date object) parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi parse('RegExp', 're'); // /re/ parse('Int', '2'); // 2 parse('Number | String', 'str'); // 'str' parse('Number | String', '2'); // 2 parse('[Number]', '[1,2,3]'); // [1,2,3] parse('(String, Boolean)', '(hi, false)'); // ['hi', false] parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} // at the top level, you can ommit surrounding delimiters parse('[Number]', '1,2,3'); // [1,2,3] parse('(String, Boolean)', 'hi, false'); // ['hi', false] parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} // wildcard - auto choose type parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] ``` ## Usage `require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. ```js // parse(type, input, options); parse('[Number]', '1,2,3'); // [1, 2, 3] // parsedTypeParse(parsedType, input, options); var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ### parse(type, input, options) `parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. ##### arguments * type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js parse('[Number]', '1,2,3'); // [1, 2, 3] ``` ### parsedTypeParse(parsedType, input, options) `parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ## Levn Format Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). * `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` * `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` * `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` * `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents * `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. * `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). * `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. * Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: * If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. * If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. * If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. * If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. * If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). * If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. Whitespace between special characters and elements is inconsequential. ## Options Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. ### Explicit A `Boolean`. By default it is `false`. __Example:__ ```js parse('RegExp', 're', {explicit: false}); // /re/ parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... parse('RegExp | String', 're', {explicit: true}); // 're' ``` `explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. ### customTypes An `Object`. Empty `{}` by default. __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function (x) { return x % 2 === 0; }, cast: function (x) { return {type: 'Just', value: parseInt(x)}; } } } } parse('Even', '2', options); // 2 parse('Even', '3', options); // Error: Value: "3" does not type check... ``` __Another Example:__ ```js function Person(name, age){ this.name = name; this.age = age; } var options = { customTypes: { Person: { typeOf: 'Object', validate: function (x) { x instanceof Person; }, cast: function (value, options, typesCast) { var name, age; if ({}.toString.call(value).slice(8, -1) !== 'Object') { return {type: 'Nothing'}; } name = typesCast(value.name, [{type: 'String'}], options); age = typesCast(value.age, [{type: 'Numger'}], options); return {type: 'Just', value: new Person(name, age)}; } } } parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} ``` `customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. `cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. ## Technical About `levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(low: `number`, high: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. calificaciones Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` ## Enterprise support fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore). Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module. ##### Tested on - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - [Guide for 2.x -> 3.x](#upgrade-2x---3x) - [Guide for 3.x -> 4.x](#upgrade-3x---4x) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array<Pathname>): Array<Pathname> ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory. ```js // WRONG ig.ignores('./abc') // WRONG, for it will never happen. // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js ig.add('config/') // `ig` does NOT know if 'config' is a normal file, directory or something ig.ignores('config') // And it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` **** # Upgrade Guide ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
mesh-chat_chat-contract
.idea modules.xml vcs.xml README.md chat .gitpod.yml contract Cargo.toml build.sh deploy.sh src lib.rs package.json
# chat-contract
josefophe_nearcontract
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
noopponent18_-nearpractice-II
starter--near-sdk-as README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts index.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
# `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ``` ## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068)
near_queryapi
.github ISSUE_TEMPLATE bug_report.md epic-template-.md feature-request-.md secondary-focus-area-.md workflows block-streamer-ci.yml close-completed-issues.yml coordinator-ci.yml deploy-dev-widgets.yml deploy-prod-widgets.yml deploy-widgets.yml runner-ci.yml README.md block-server handler.js serverless.yml block-streamer Cargo.toml build.rs data 000093085141 block.json shard_0.json shard_1.json shard_2.json shard_3.json 000107503704 block.json list_objects.xml shard_0.json shard_1.json shard_2.json shard_3.json 000107503705 block.json list_objects.xml shard_0.json shard_1.json shard_2.json shard_3.json invalid block.json list_objects.xml examples list_streams.rs start_stream.rs stop_stream.rs src block_stream.rs delta_lake_client.rs indexer_config.rs lake_s3_client.rs lib.rs main.rs metrics.rs redis.rs rules matcher.rs mod.rs outcomes_reducer.rs types.rs s3_client.rs server block_streamer_service.rs mod.rs test_utils.rs utils.rs coordinator Cargo.toml build.rs src block_streams handler.rs mod.rs synchronise.rs executors handler.rs mod.rs synchronise.rs indexer_config.rs indexer_state.rs main.rs redis.rs registry.rs server indexer_manager_service.rs mod.rs utils.rs docker-compose.yml frontend .eslintrc.json README.md jest.config.js next.config.js package-lock.json package.json postcss.config.js primitives.d.ts replacement.dev.json replacement.local.json replacement.mainnet.json src classes ValidationError.js components CreateNewIndexer CreateNewIndexer.js index.js Editor GlyphContainer.js __tests__ Editor.test.js validator.test.js block_details.js index.js Playground index.js constants RegexExp.js Strings.js contexts IndexerDetailsContext.js ModalContext.js pages create-new-indexer index.js global.css query-api-editor index.js utils debounce.js fetchBlock.js formatters.js formatters.test.js getLatestBlockHeight.js indexerRunner.js pgSchemaTypeGen.js queryIndexerFunction.js resize.js validators.js tailwind.config.js tsconfig.json widgets src NearQueryApi.metadata.json QueryApi.App.metadata.json QueryApi.Dashboard.metadata.json QueryApi.Editor.metadata.json QueryApi.IndexerStatus.metadata.json props.json hasura-authentication-service Cargo.toml src main.rs services.rs hasura migrations default 1691364619300_init down.sql up.sql postgres init.sql prometheus.yml registry contract Cargo.toml README.md build.sh deploy-dev.sh deploy-local-testing.sh deploy-prod.sh src lib.rs types Cargo.toml src lib.rs runner-client Cargo.toml build.rs examples list_executors.rs start_executor.rs stop_executor.rs src lib.rs runner .eslintrc.js examples list-executors.ts start-executor.ts stop-executor.ts jest.config.js package-lock.json package.json src dml-handler dml-handler.test.ts dml-handler.ts index.ts globals.d.ts hasura-client hasura-client.test.ts hasura-client.ts index.ts index.ts indexer-config index.ts indexer-config.test.ts indexer-config.ts indexer-meta index.ts indexer-meta.test.ts indexer-meta.ts log-entry.test.ts log-entry.ts indexer index.ts indexer.test.ts indexer.ts instrumentation index.ts tracer.ts lake-client index.ts lake-client.test.ts lake-client.ts logger.ts metrics.ts pg-client.ts provisioner index.ts provisioner.test.ts provisioner.ts schemas logs-table.ts metadata-table.ts redis-client index.ts redis-client.test.ts redis-client.ts server index.ts runner-client.ts runner-server.ts runner-service.test.ts runner-service.ts stream-handler index.ts stream-handler.ts worker.ts utility.ts tests blocks 00115185109 streamer_message.json integration.test.ts testcontainers hasura.ts postgres.ts utils.ts tsconfig.build.json tsconfig.json scripts wipe-database.sh
# IndexerFunction Registry A registry of indexer functions that are run by QueryAPI <br /> When an IndexerFunction is added to the registry the calling user's account is prepended to the name of the function. Example: `developer.near` calls `register_indexer_function("index_all_the_things", "bunch of code here" })` the function will be registered as `developer.near/index_all_the_things`. It can then be read by calling `read_indexer_function("developer.near/index_all_the_things")`. ## Methods ``` register_indexer_function({ function_name, code }) // Note that the name will be prefixed with the calling account read_indexer_function({ function_name }) remove_indexer_function({ function_name }) // Note that the name will be prefixed with the calling account list_indexer_functions() ``` <br/> ### Example Calls ```bash near view registry.queryapi.testnet read_indexer_function '{"function_name":"developer.testnet/log"}' near view registry.queryapi.testnet list_indexer_functions near call registry.queryapi.testnet register_indexer_function '{"function_name":"log", "code": "console.log(`Block #${streamerMessage.block.header.height});"}' --accountId <ACCOUNT_ID> near call registry.queryapi.testnet remove_indexer_function '{"function_name":"log"}' --accountId <ACCOUNT_ID> ``` TODO: Add multisig deployment administration for Data team and SREs (DAO?). ## Deployment commands ```bash ./build.sh near deploy --wasmFile ./target/wasm32-unknown-unknown/release/registry.wasm --accountId registry.queryapi.testnet ``` ## What is this repo? Frontend for Near QueryAPI that allows users to create, manage, and explore indexers stored on-chain. You can visit the app [here](https://near.org/dataplatform.near/widget/QueryApi.App) BOS widgets are stored in the `widgets/` folder while the main NextJS application lives in the root. ## Getting Started First, download the bos-loader cli by following this guide [here](https://docs.near.org/bos/dev/bos-loader). From the root of QueryAPI Frontend repo, run the following command ```bash yarn serve:widgets:local // for running local enviornment yarn serve:widgets:dev // for running dev enviornment yarn serve:widgets:prod // for running prod enviornment ``` > Near.org or any other BOS gateway queries the blockchain state to pull the latest widgets code and renders it. If we would like to test our BOS widgets, we need to override the path at which the gateway (near.org) queries for the widget code. We do this using the Bos-loader tool (the underlying CLI tool used in the `yarn serve:widgets:dev` command) which allows us to serve out widgets locally (http://127.0.0.1:3030 by default). ** This command replaces all keys found in `replacement.dev.json` object with the their values in the widgets directory when serving the widgets **. At this point, we have served our widgets locally but have not yet told the BOS gateway (near.org) where to load our local widgets from. **Then, Head to `near.org/flags` and enter `http://127.0.0.1:3030`** > In order to tell our BOS gateway (near.org), where to load the local widgets from, we head to `near.org/flags` and enter the local path we got from running the previous command. If you have not changed any configurations then the default should be `http://127.0.0.1:3030` **Finally**, run the following to serve the local NextJS frontend ```bash yarn dev ``` **Now, head to the path where the widgets are served on the BOS.** - Prod App: `https://near.org/dataplatform.near/widget/QueryApi.App` ### ENV variables The React app does not use the replacement files. Instead, we need to provide an `.env` file to make sure we are accessing the right enviornment By default, the React app will use the `dev` enviornment vars ``` Prod: NEXT_PUBLIC_HASURA_ENDPOINT=https://near-queryapi.api.pagoda.co NEXT_PUBLIC_REGISTRY_CONTRACT_ID=queryapi.dataplatform.near ``` ``` Dev: NEXT_PUBLIC_HASURA_ENDPOINT=https://near-queryapi.dev.api.pagoda.co NEXT_PUBLIC_REGISTRY_CONTRACT_ID=dev-queryapi.dataplatform.near # QueryApi With QueryApi you can * Write your own custom indexer function at https://near.org/dataplatform.near/widget/QueryApi.Dashboard; * Specify the schema for your own custom hosted database and write to it with your indexer function; * Retrieve that data through a GraphQL API. ## 🧩 Components 1. [Coordinator](./coordinator) Continuously reads latest registry and attempts to synchronise that configuration across the system, i.e. starting relevant Block Streams and Executors. 1. [Runner](./runner) Manages "Executors" which, retrieves messages from Redis Streams, fetches matching blocks, and executes Indexer code against that block. Retrieves messages from Redis Stream, fetching matching block and executes the IndexerFunction. 1. [Block Streamer](./block-streamer) Manages "Block Streams" which, use the configured contract filter to fetch relevant blocks from S3 and publish those blocks to Redis Streams. 1. [IndexerFunction Editor UI](./frontend) Serves the editor UI within the dashboard widget and mediates some communication with the GraphQL DB and block server. 1. [Hasura Authentication Service](./hasura-authentication-service) Provides authentication for the Hasura GraphQL server. 1. [IndexerFunction Registry Contract](./registry) Stores IndexerFunctions, their schemas and execution parameters like start block height. 1. [Lake Block server](./block-server) Serves blocks from the S3 lake for in browser testing of IndexerFunctions. ## 🚀 Getting Started The majority of the QueryApi components can be set up locally using Docker. For this purpose, a [Docker Compose file](./docker-compose.yml) has been provided. However, the local system still relies on the NEAR Mainnet, rather than running on a localnet. ### Requirements - [Docker](https://docs.docker.com/engine/install/) - [Docker Compose](https://docs.docker.com/compose/install/) - [Hasura CLI](https://hasura.io/docs/latest/hasura-cli/install-hasura-cli/) - AWS Access Keys ### AWS Credentials Setup QueryApi requires AWS credentials to stream blocks from [NEAR Lake](https://github.com/near/near-lake-indexer). Credentials are exposed via the following environment variables, which can be found in the Docker Compose file: Runner: - `AWS_ACCESS_KEY_ID` - `AWS_SECRET_ACCESS_KEY` Coordinator: - `LAKE_AWS_ACCESS_KEY` - `LAKE_AWS_SECRET_ACCESS_KEY` - `QUEUE_AWS_ACCESS_KEY` - `QUEUE_AWS_SECRET_ACCESS_KEY` These should be populated with your credentials. In most cases, the same key pair can be used for all 3 sets of credentials. Just ensure the keys have permissions to access S3 for handling [Requestor Pays](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RequesterPaysBuckets.html) in Near Lake. ### Hasura Configuration Hasura contains shared tables for e.g. logging and setting arbitrary state. These tables must be configured prior to running the entire QueryApi application. Configuration is stored in the `hasura/` directory and deployed through the Hasura CLI. To configure Hasura, first start it with: ```sh docker compose up hasura-graphql --detach ``` And apply the configuration with: ```sh cd ./hasura && hasura deploy ``` ### Running QueryApi With everything configured correctly, we can now start all components of QueryApi with: ```sh docker compose up ``` ### Local Configuration - Coordinator watches the dev registry contract by default (`dev-queryapi.dataplatform.near`). To use a different contract, you can update the `REGISTRY_CONTRACT_ID` environment variable. ### Known Issues It is expected to see some provisioning errors from `Runner` when starting QueryAPI for the first time. These occur when multiple indexers under the same account attempt to provision the same shared infrastructure. These should self resolve after a few seconds.
mahmudsudo_resource_bank
Cargo.toml README.md build.sh deploy.sh neardev dev-account.env src lib.rs target .rustc_info.json debug .fingerprint Inflector-096ef7a664058f4c lib-inflector.json ahash-1ee028f97380bada build-script-build-script-build.json ahash-f5f08e763352a8f2 run-build-script-build-script-build.json ahash-fac2729da91bcf57 lib-ahash.json arrayref-ffd1e1fb1d72d9e0 lib-arrayref.json arrayvec-1c2ee51b97a456f8 lib-arrayvec.json arrayvec-8fca423e1f17eafa lib-arrayvec.json autocfg-94258bf7e34286ad lib-autocfg.json base64-509cc9ab38858115 lib-base64.json base64-6d162bc0128e07c3 lib-base64.json bitvec-04b3636dfd4a1733 lib-bitvec.json blake2-ff5a89db32caf4c9 lib-blake2.json block-buffer-b8e8ae2ee80bc2de lib-block-buffer.json block-buffer-d190f8565e9ba31c lib-block-buffer.json borsh-derive-17e18a2dd3a4f8b0 lib-borsh-derive.json borsh-derive-internal-3a3d930f0d375a26 lib-borsh-derive-internal.json borsh-ed3d31941ec6f797 lib-borsh.json borsh-schema-derive-internal-d7b4d6aae6443312 lib-borsh-schema-derive-internal.json bs58-514ab14a70788ae9 lib-bs58.json byte-slice-cast-7b4235fd3c578264 lib-byte-slice-cast.json byteorder-ee2dad0db84dd90d lib-byteorder.json bytesize-6842e7706ec74a2d lib-bytesize.json c2-chacha-eb2171d5b9027561 lib-c2-chacha.json cc-04136cd84633e8c8 lib-cc.json cfg-if-8cdd395f1b3ffcd6 lib-cfg-if.json cfg-if-a1581cd1abd57635 lib-cfg-if.json cfg-if-f12289233c059448 lib-cfg-if.json chrono-0b1c22072f36250b lib-chrono.json cipher-4833e5b497ca3cde lib-cipher.json convert_case-abefc1e17fa32bf1 lib-convert_case.json cpufeatures-6f2fecdfdae3204d lib-cpufeatures.json crunchy-1a363bc78a3ce39d build-script-build-script-build.json crunchy-879f759bc1918bfd run-build-script-build-script-build.json crunchy-f19ecb45e6c18c4b lib-crunchy.json crypto-common-0d256c85f06a0d04 lib-crypto-common.json crypto-mac-950482c1d863c53a lib-crypto-mac.json curve25519-dalek-37a60ac6c1bc4f5e lib-curve25519-dalek.json derive_more-f7aa8e98066835c3 lib-derive_more.json digest-1552dc43ae9a6795 lib-digest.json digest-cf45ab41721971c1 lib-digest.json dyn-clone-e10d6d2cd9ca5d67 lib-dyn-clone.json easy-ext-921b426d244e6e86 lib-easy-ext.json ed25519-b9919e34b4ac4a55 lib-ed25519.json ed25519-dalek-60a2964c12c45937 lib-ed25519-dalek.json fixed-hash-ae8fb43a53b01b81 lib-fixed-hash.json funty-0c01ecbc5328faef lib-funty.json generic-array-5388f7676b84fd26 build-script-build-script-build.json generic-array-593fd74244db13c6 lib-generic_array.json generic-array-ae616f54b789a46b run-build-script-build-script-build.json getrandom-56f1a51e9c07988f lib-getrandom.json getrandom-88287c8617a90619 lib-getrandom.json getrandom-a807e0eaf89e7ee9 build-script-build-script-build.json getrandom-b63e5e8c30778443 run-build-script-build-script-build.json hashbrown-ff761aec2d197673 lib-hashbrown.json heck-bcd9d1104899e84c lib-heck.json hello_near-d47d29c451aa6ff7 test-lib-hello_near.json hello_near-d747485753fab817 lib-hello_near.json hex-889bdc259c6ddcf0 lib-hex.json iana-time-zone-6d9a934fae07b1be lib-iana-time-zone.json impl-codec-1338e9998abc6587 lib-impl-codec.json impl-trait-for-tuples-4b3a8235fe057da0 lib-impl-trait-for-tuples.json itoa-482a7d05ae39b8e8 lib-itoa.json keccak-10b41e0921291c69 lib-keccak.json lazy_static-a9a3da33bf225690 lib-lazy_static.json libc-858878d1c129282c run-build-script-build-script-build.json libc-94179e7399e08fa6 build-script-build-script-build.json libc-b2461d25a10bc78c lib-libc.json memory_units-a25a89310b01d317 lib-memory_units.json near-abi-bd9c94aee6c53b21 lib-near-abi.json near-account-id-1741a38b7a1a535c lib-near-account-id.json near-crypto-666f934cb0bd401f lib-near-crypto.json near-primitives-c1c1c7989426d296 lib-near-primitives.json near-primitives-core-3e9b1a6655f65c03 lib-near-primitives-core.json near-rpc-error-core-d8ed489667202b23 lib-near-rpc-error-core.json near-rpc-error-macro-b0b3c09def003982 lib-near-rpc-error-macro.json near-sdk-a63a107c89aabaa8 lib-near-sdk.json near-sdk-macros-656a2a8a66ebb8bb lib-near-sdk-macros.json near-sys-ad38013e7e5462a0 lib-near-sys.json near-vm-errors-e4e82e73ac00de25 lib-near-vm-errors.json near-vm-logic-3d63f3f3139e3c1c lib-near-vm-logic.json num-bigint-2c4c87a44942632a lib-num-bigint.json num-bigint-9c86ee56d57e5d1e run-build-script-build-script-build.json num-bigint-f2c6021bf59a8060 build-script-build-script-build.json num-integer-3b5639074aac30d6 build-script-build-script-build.json num-integer-919f229e7b35c8db run-build-script-build-script-build.json num-integer-a703a02996112c95 lib-num-integer.json num-rational-2d098ca5b5a364f2 build-script-build-script-build.json num-rational-7a28e079ee79612c lib-num-rational.json num-rational-8a84305734f818db run-build-script-build-script-build.json num-traits-671aa5bdd6073a42 build-script-build-script-build.json num-traits-6fe643d4143fecb9 run-build-script-build-script-build.json num-traits-edd5ed7548e6b475 lib-num-traits.json once_cell-3c5bcbc6d537eb21 lib-once_cell.json once_cell-eab76c691b3370a2 lib-once_cell.json opaque-debug-5b2efdcd07d38fb9 lib-opaque-debug.json parity-scale-codec-derive-29f29180a251f19e lib-parity-scale-codec-derive.json parity-scale-codec-ee35d2e4e13d673d lib-parity-scale-codec.json parity-secp256k1-3bf427b1ba4d3e51 lib-secp256k1.json parity-secp256k1-ad7f743821fdf6f9 run-build-script-build-script-build.json parity-secp256k1-df3b8ae649a153b4 build-script-build-script-build.json ppv-lite86-9e3f3d40a34f04dd lib-ppv-lite86.json primitive-types-efdeee48b8445a2b lib-primitive-types.json proc-macro-crate-adc9b8541167196d lib-proc-macro-crate.json proc-macro-crate-c8f12530ee920648 lib-proc-macro-crate.json proc-macro2-974070b9dd05cd17 run-build-script-build-script-build.json proc-macro2-bdb41e3236f28368 lib-proc-macro2.json proc-macro2-e8bba211f18a0098 build-script-build-script-build.json quote-0468857aa685046e run-build-script-build-script-build.json quote-5abe62efddb7ba9d lib-quote.json quote-98c34dc13fa0c8fa build-script-build-script-build.json radium-1d8b227536a79b41 build-script-build-script-build.json radium-7b3136e5f648e379 lib-radium.json radium-868429534dae2fd1 run-build-script-build-script-build.json rand-8ad5d4a418b09b53 lib-rand.json rand-dd1fd8a34cae5bc4 lib-rand.json rand_chacha-438dba79afc51a8f lib-rand_chacha.json rand_chacha-a4c104422fbd27cc lib-rand_chacha.json rand_core-4ff66ec9e40052b8 lib-rand_core.json rand_core-79aeacd1cb52fe64 lib-rand_core.json reed-solomon-erasure-6e584c485dbfb895 run-build-script-build-script-build.json reed-solomon-erasure-865589ee66b6152d lib-reed-solomon-erasure.json reed-solomon-erasure-a6dbd0e1d2e804b4 build-script-build-script-build.json ripemd-c937500ceb2d6c14 lib-ripemd.json rustc-hex-627433cd59e51c53 lib-rustc-hex.json rustversion-38cf41a90deb78b1 build-script-build-script-build.json rustversion-66f1a4c615de5fc1 lib-rustversion.json rustversion-9c10ce2d1e06b56c run-build-script-build-script-build.json ryu-6bf76fb2c5a0751c lib-ryu.json schemars-0a338873ff5a8a30 lib-schemars.json schemars-50c23252c24903bf build-script-build-script-build.json schemars-fe340890a9aa8df1 run-build-script-build-script-build.json schemars_derive-c62e67697ff052a8 lib-schemars_derive.json semver-5df4c4f197bfb8a1 build-script-build-script-build.json semver-80602b512cc0e9f3 lib-semver.json semver-dda6bc268a897968 run-build-script-build-script-build.json serde-2e6b9a685a124ddb lib-serde.json serde-b2dc2aee22f9d79a lib-serde.json serde-c14691925adb1e61 build-script-build-script-build.json serde-c97dadb92038b6fa run-build-script-build-script-build.json serde-ec681a3e74f4bb48 build-script-build-script-build.json serde-f921f72f43fb474c run-build-script-build-script-build.json serde_derive-6aed83d7cd46aa30 lib-serde_derive.json serde_derive-bd173a4928f9cb26 run-build-script-build-script-build.json serde_derive-c9292ffc36ac3572 build-script-build-script-build.json serde_derive_internals-5fdc2dbbaaba93ef lib-serde_derive_internals.json serde_json-2337cd48f2dc6bcd lib-serde_json.json serde_json-7190d031263b9f75 build-script-build-script-build.json serde_json-c2d0b82ee8288c3d run-build-script-build-script-build.json sha2-9102cdafdc3ee685 lib-sha2.json sha2-cf04215290eb08ee lib-sha2.json sha3-98ae851e320ad64b lib-sha3.json signature-0a6be634196478be lib-signature.json smallvec-a8968718b20e06ff lib-smallvec.json smart-default-80685bed5444504d lib-smart-default.json spin-d174d5709bfe53dc lib-spin.json static_assertions-311f8ca35052edef lib-static_assertions.json strum-760e3b1fd5a55a9a lib-strum.json strum_macros-ca19b45d029286a7 lib-strum_macros.json subtle-fb56107c994622d5 lib-subtle.json syn-6592b28a98e938e6 lib-syn.json syn-bb87fec9267ab694 build-script-build-script-build.json syn-f5d72645070e4af5 run-build-script-build-script-build.json synstructure-91acb1aa19508ed0 lib-synstructure.json tap-2da2f09567be6518 lib-tap.json thiserror-7a2a5435a89809d8 lib-thiserror.json thiserror-95934396700d0aa5 run-build-script-build-script-build.json thiserror-f1e0e0c722de948f lib-thiserror.json thiserror-f8ab7330959d2b92 build-script-build-script-build.json thiserror-impl-4237a4ae32b2bd81 lib-thiserror-impl.json time-f0184de49b0941af lib-time.json toml-096a18ffd245f4ef lib-toml.json typenum-b72fcb131ce6ea8f run-build-script-build-script-main.json typenum-bcd2fa2b9e5a1121 lib-typenum.json typenum-d71709435b6bfe8d build-script-build-script-main.json uint-e8ab722f4c2b7ac8 lib-uint.json unicode-ident-607cf2386ba4fb20 lib-unicode-ident.json unicode-xid-267c9ebc6ab172f7 lib-unicode-xid.json version_check-f3ba2af17f7828eb lib-version_check.json wee_alloc-638e611679b1a3d9 build-script-build-script-build.json wee_alloc-be092c95e46d2349 run-build-script-build-script-build.json wee_alloc-f0267874299ad171 lib-wee_alloc.json wyz-268304cae0b1724c lib-wyz.json zeroize-19813e93aee3bf9e lib-zeroize.json zeroize_derive-d51f9e067cb49aaa lib-zeroize_derive.json zeropool-bn-429bf49a6c157e71 lib-zeropool-bn.json build crunchy-879f759bc1918bfd out lib.rs num-bigint-9c86ee56d57e5d1e out radix_bases.rs parity-secp256k1-ad7f743821fdf6f9 out flag_check.c reed-solomon-erasure-6e584c485dbfb895 out table.rs thiserror-95934396700d0aa5 out probe.rs typenum-b72fcb131ce6ea8f out consts.rs op.rs tests.rs wee_alloc-be092c95e46d2349 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint Inflector-f13c978d1aadb31b lib-inflector.json ahash-585ee5915143711e build-script-build-script-build.json borsh-derive-5d8e3e690a704c58 lib-borsh-derive.json borsh-derive-internal-987b0e15713ff7dd lib-borsh-derive-internal.json borsh-schema-derive-internal-7ac9b6b06730187f lib-borsh-schema-derive-internal.json crunchy-4aea0594f90fa7a8 build-script-build-script-build.json near-sdk-macros-3745f63548038921 lib-near-sdk-macros.json proc-macro-crate-59ce7cc3c633390f lib-proc-macro-crate.json proc-macro2-4285eee214e776e7 lib-proc-macro2.json proc-macro2-6afb81fa8313a0a6 run-build-script-build-script-build.json proc-macro2-b0db05a18fdd060a build-script-build-script-build.json quote-13a8d32fe124988e lib-quote.json quote-4f109f35fffae2b0 run-build-script-build-script-build.json quote-bf57674ebeff5b89 build-script-build-script-build.json schemars-311a02be9654297b build-script-build-script-build.json schemars_derive-e8904347689e5862 lib-schemars_derive.json semver-093dc8cdeff206ce build-script-build-script-build.json serde-281b7b3b763a261a build-script-build-script-build.json serde-3aca90b5d66dafa1 build-script-build-script-build.json serde-50b4abda624d35e9 run-build-script-build-script-build.json serde-f7502c286aad6aef lib-serde.json serde_derive-4ec12993f787c226 run-build-script-build-script-build.json serde_derive-6d1508c655af3cba lib-serde_derive.json serde_derive-742b90324875daaf build-script-build-script-build.json serde_derive_internals-f0a9f68e2c5c01b0 lib-serde_derive_internals.json serde_json-940f6ffaf8245ede build-script-build-script-build.json syn-1b53236001990edb run-build-script-build-script-build.json syn-4af4bd0bc918a78a build-script-build-script-build.json syn-64799755ebe285c6 lib-syn.json toml-e804673d3f048140 lib-toml.json unicode-ident-51be5dfdc102386a lib-unicode-ident.json version_check-28922478539c9cad lib-version_check.json wee_alloc-10c79473ba7c8522 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-c1dbdff08e52ddac lib-ahash.json ahash-e9c8d9fc5a0f9a13 run-build-script-build-script-build.json base64-d9edbd2f2dc2d956 lib-base64.json borsh-35360294a1d69e78 lib-borsh.json bs58-9f10c4b1b3984643 lib-bs58.json byteorder-9bfc0a7b6bd12f32 lib-byteorder.json cfg-if-051471ea479febcb lib-cfg-if.json crunchy-5f68feb4877f62f7 run-build-script-build-script-build.json crunchy-e2de7fd44095dfb1 lib-crunchy.json dyn-clone-08384b4209913bac lib-dyn-clone.json hashbrown-c765772b21efb6c4 lib-hashbrown.json hello_near-00ca379cccdf6430 lib-hello_near.json hex-5d60733e3d120d80 lib-hex.json itoa-462fd4b8d8e08994 lib-itoa.json memory_units-16900eb0f3221f3f lib-memory_units.json near-abi-25b4bb9c23cef507 lib-near-abi.json near-sdk-29516a2788490be7 lib-near-sdk.json near-sys-8155e02f70b6f85e lib-near-sys.json once_cell-8137368909678986 lib-once_cell.json ryu-2864b9f286b1e2ac lib-ryu.json schemars-de5d78a9b7ea4ebb run-build-script-build-script-build.json schemars-e293184c216fd02f lib-schemars.json semver-d22de4968044da7f lib-semver.json semver-e9ad1a8740d679c7 run-build-script-build-script-build.json serde-135657c210b7d506 lib-serde.json serde-1794fd4a728aa6bf run-build-script-build-script-build.json serde_json-ad10cac7e8bc659e lib-serde_json.json serde_json-c6878b0a3b5e59b2 run-build-script-build-script-build.json static_assertions-d95c8c5a77238f05 lib-static_assertions.json uint-2a4f9a92f50eacb4 lib-uint.json wee_alloc-019678edf7d788ed run-build-script-build-script-build.json wee_alloc-c5fdfac1f46cc75c lib-wee_alloc.json build crunchy-5f68feb4877f62f7 out lib.rs wee_alloc-019678edf7d788ed out wee_alloc_static_array_backend_size_bytes.txt
# Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
hasankokes_near-contract-deployment-test
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) www.patika.dev <img width="881" alt="Ekran Resmi 2022-03-29 00 10 40" src="https://user-images.githubusercontent.com/102430083/160487971-5488d524-3fd7-4536-9a67-9f4c10a6be84.png"> Deployed Contract Link : https://explorer.testnet.near.org/transactions/Gu847My9WgvQWSQGbDeJx7Fv612Wy2VqyUW1dYm1pY1a # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ```
near_introverse
README.md babel.config.js build.sh docs asset-manifest.json index.html manifest.json precache-manifest.dee0e4b52c8abe5b717a373a3f0d170e.js robots.txt service-worker.js static css main.0db44818.chunk.css js 2.bb4cc122.chunk.js main.fc8e2684.chunk.js runtime-main.477fb16a.js media logo.5d5d9eef.svg near.53ae53eb.svg gulpfile.js package-lock.json package.json public index.html manifest.json robots.txt src App.css App.js App.test.js Connections.js UploadCSV.js __mocks__ fileMock.js assets gray_near_logo.svg logo.svg near.svg config.js fake.js index.js jest.init.js main.test.js utils.js wallet login index.html
# Welcome to the ~INTROVERSE~ sasha.services ## Template for NEAR dapps ### Features * Create NEAR dapps with a React frontend 🐲 * We got Gulp! 💦 ### Requirements ##### IMPORTANT: Make sure you have the latest version of NEAR Shell and Node Version > 10.x 1. node and npm 2. near shell ``` npm i -g near-shell ``` 3.(optional) install yarn to build ``` npm i -g yarn ``` ### To run on testnet #### Step 1: Create account for the contract and deploy the contract. You'll now want to authorize NEAR shell on your NEAR account, which will allow NEAR Shell to deploy contracts on your NEAR account's behalf \(and spend your NEAR account balance to do so\). Type the command `near login` which should return a url: ```bash Please navigate to this url and follow the instructions to log in: https://wallet.nearprotocol.com/login/?title=NEAR+Shell&public_key={publicKey} ``` From there enter in your terminal the same account ID that you authorized: `Please enter the accountId that you logged in with: <asdfasdf>` Once you have entered your account ID, it will display the following message: `Missing public key for <asdfasdf> in default` `Logged in with masternode24` This message is not an error, it just means that it will create a public key for you. #### Step 2: Modify src/config.js line that sets the contractName. Set it to id from step 1. ```javascript (function() { const CONTRACT_NAME = 'react-template'; /* TODO: Change this to your contract's name! */ const DEFAULT_ENV = 'development'; ... })(); ``` #### Step 3: Finally, run the command in your terminal. ``` npm install && npm start ``` with yarn: ``` yarn install && yarn start ``` The server that starts is for static assets and by default serves them to localhost:3000. Navigate there in your browser to see the app running! ### Deploy Check the scripts in the package.json, for frontend and backend both, run the command: ```bash npm run(yarn) deploy ``` ### Test For test file src/App.test.js, it works for the template after finishing step 3 above. If smart contract and index.js change, user should change to their functions to test. The command is: ```bash npm run(yarn) test ``` ### To Explore - `assembly/main.ts` for the contract code - `public/index.html` for the front-end HTML - `src/index.js` for the JavaScript front-end code and how to integrate contracts - `src/App.js` for the first react component
Learn-NEAR-Club_Simple_DAO
simple_dao .gitpod.yml README.md contract Cargo.toml README.md compile.js src lib.rs target .rustc_info.json debug .fingerprint Inflector-ff0f2cb78506b672 lib-inflector.json ahash-252d8c6f417c01b4 lib-ahash.json aho-corasick-645709f84eca6179 lib-aho_corasick.json autocfg-b490ecf0efe2c3d3 lib-autocfg.json base64-fcc8a078a1bd323e lib-base64.json block-buffer-2d5e4f3a28bc70b3 lib-block-buffer.json block-buffer-a4a188d7c3d00823 lib-block-buffer.json block-padding-4d7f6a405c78e981 lib-block-padding.json borsh-99dd82d0c9895ca2 lib-borsh.json borsh-derive-bad6fa58483e1d2e lib-borsh-derive.json borsh-derive-internal-7d2ca7c7350ecb4c lib-borsh-derive-internal.json borsh-schema-derive-internal-60c10cc67a947c2d lib-borsh-schema-derive-internal.json bs58-87cd685b55d121d8 lib-bs58.json byte-tools-39f40a1ed7dce120 lib-byte-tools.json byteorder-375a29e98e5cbb92 lib-byteorder.json byteorder-60eab144e4d2d8c4 build-script-build-script-build.json byteorder-bfc54946cd2944f2 run-build-script-build-script-build.json cfg-if-899c9fa66f35d20d lib-cfg-if.json cfg-if-91c199bbc5a73d3a lib-cfg-if.json convert_case-03bdd3845b961360 lib-convert_case.json derive_more-8ab27024e75f4718 lib-derive_more.json digest-0fa901388f9b1093 lib-digest.json digest-1dc010239664a351 lib-digest.json generic-array-67fdaa0d94436fd7 run-build-script-build-script-build.json generic-array-73f850477afb8b54 build-script-build-script-build.json generic-array-79c927cfc5de402e lib-generic_array.json generic-array-d96dc902509ac7df lib-generic_array.json greeter-e73b70aba9da893c lib-greeter.json hashbrown-132fd098cda2f188 lib-hashbrown.json hashbrown-383df19846fc5c9c run-build-script-build-script-build.json hashbrown-6170a10cd0d6d3c8 lib-hashbrown.json hashbrown-6f8b47b1755848ac lib-hashbrown.json hashbrown-d0053e514da2111d build-script-build-script-build.json hex-c01aa1935a4bc7eb lib-hex.json indexmap-530b792b073b7de1 lib-indexmap.json indexmap-550ff641b7cf1f79 build-script-build-script-build.json indexmap-a7117f09460202d8 lib-indexmap.json indexmap-cfdcedd2db9ae7f8 run-build-script-build-script-build.json itoa-55c3aae34396a661 lib-itoa.json itoa-8b07d3071c508a06 lib-itoa.json keccak-6c7ceeecc335d65b lib-keccak.json lazy_static-a43172d2b06b430d lib-lazy_static.json libc-18f4b2dd85429f4e lib-libc.json libc-df99ad5bafe0ea3b run-build-script-build-script-build.json libc-e712d380a74eb19a build-script-build-script-build.json memchr-3ef49f144c41efb3 lib-memchr.json memchr-b7f9ea615378b21e run-build-script-build-script-build.json memchr-de022f9424ba12d9 build-script-build-script-build.json memory_units-b557fcdf5fc070e9 lib-memory_units.json near-primitives-core-182a543bea92590f lib-near-primitives-core.json near-rpc-error-core-4d41c8ca3d9df6f6 lib-near-rpc-error-core.json near-rpc-error-macro-40e1d697ccd25934 lib-near-rpc-error-macro.json near-runtime-utils-bc9b978d2d338ff7 lib-near-runtime-utils.json near-sdk-c7491728d774ec7d lib-near-sdk.json near-sdk-core-39b533403fb80f2c lib-near-sdk-core.json near-sdk-macros-20b5bcf0adc177dd lib-near-sdk-macros.json near-vm-errors-5664416cd2115c34 lib-near-vm-errors.json near-vm-logic-da9fda3d8f37fca7 lib-near-vm-logic.json num-bigint-08d38b8716dc60be run-build-script-build-script-build.json num-bigint-78eee61db7b9dd7b lib-num-bigint.json num-bigint-9a1bbde145b54a63 build-script-build-script-build.json num-integer-519bfb691d18d642 run-build-script-build-script-build.json num-integer-5262044c3af9bc8f lib-num-integer.json num-integer-a0f63a7245abb4b8 build-script-build-script-build.json num-rational-390de319a7107976 build-script-build-script-build.json num-rational-d178c01a89114946 lib-num-rational.json num-rational-d8b02ae48db65584 run-build-script-build-script-build.json num-traits-5dcc147091caa3f0 run-build-script-build-script-build.json num-traits-7c5baeb594325aa3 lib-num-traits.json num-traits-abd00c2aa3ae3e22 build-script-build-script-build.json opaque-debug-06311b62cc47522f lib-opaque-debug.json opaque-debug-a61a38e8df12100d lib-opaque-debug.json proc-macro-crate-6b720730bd8cfe4d lib-proc-macro-crate.json proc-macro2-3a2618d790c36686 run-build-script-build-script-build.json proc-macro2-bcd9052443155c01 lib-proc-macro2.json proc-macro2-dcad26e58664e3c8 build-script-build-script-build.json quote-7e5f4106029c93dd lib-quote.json regex-35e9250dd75a63db lib-regex.json regex-syntax-8b0f030222551989 lib-regex-syntax.json ryu-29eb4a99c5da19a5 run-build-script-build-script-build.json ryu-56af728ccdeea280 lib-ryu.json ryu-9d9e808350b50e15 lib-ryu.json ryu-c408ed21c61ceb88 build-script-build-script-build.json serde-3a6148c8b0c96d50 lib-serde.json serde-4e30308fcfd704b4 run-build-script-build-script-build.json serde-9852f7d0003c3898 lib-serde.json serde-f080a14bb4895204 build-script-build-script-build.json serde_derive-76505adf9e956fc0 run-build-script-build-script-build.json serde_derive-89529827627af66d build-script-build-script-build.json serde_derive-ad3768099d4842a0 lib-serde_derive.json serde_json-07056d969eaa75af lib-serde_json.json serde_json-669b63539220ecc9 run-build-script-build-script-build.json serde_json-70f36ffeb774c818 build-script-build-script-build.json serde_json-769044184537367c lib-serde_json.json sha2-7e50244f1dd22e1c lib-sha2.json sha3-03dd9aee796b5231 lib-sha3.json syn-297cfebc74c2cbe5 run-build-script-build-script-build.json syn-4051f3d489331688 lib-syn.json syn-a003b890383149cf build-script-build-script-build.json toml-8b838c0fedbc9783 lib-toml.json typenum-3851627e4bcffce4 build-script-build-script-main.json typenum-38cdd45ffdf5d0c6 run-build-script-build-script-main.json typenum-a22e44474a0947e2 lib-typenum.json unicode-xid-cdd78c48aa1d5753 lib-unicode-xid.json version_check-2150defe3ba68575 lib-version_check.json wee_alloc-0b148cabf7fdf1fa lib-wee_alloc.json wee_alloc-5b35ec18b68697c8 run-build-script-build-script-build.json wee_alloc-9388bf6f243d9e40 build-script-build-script-build.json build num-bigint-08d38b8716dc60be out radix_bases.rs typenum-38cdd45ffdf5d0c6 out consts.rs op.rs tests.rs wee_alloc-5b35ec18b68697c8 out wee_alloc_static_array_backend_size_bytes.txt package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
simple_dao ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `simple_dao.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `simple_dao.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account simple_dao.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'simple_dao.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages simple_dao Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
NEAR-Analytics_SOCIAL_DB_CODE_TOOLKIT
dev_commit.py get_dev_list.py helpers.py query_engine __init__.py client.py readme.md
mikolajroszak_awesome-makerdao
AMD-MAINTENANCE-GUIDE.md Japanese.md README.md kod źródłowy stron internetowych #pressrelease.txt
# Awesome MakerDAO Awesome-MakerDAO (AMD) is a community-driven project, designed to be a resource people can use to familiarize themselves with Dai and MakerDAO. All are welcome to contribute. **Get Started** Those interested in MakerDAO are invited to explore AMD's collection of resources below. Get to know Maker with the help of beginner guides, official documentation, analysis pieces, tools, partnership announcements, AMAs, podcasts, and third-party apps, and more. **Please Be Advised** Users are ***strongly encouraged*** to perform their own due diligence before trusting third-party services listed below. Despite MakerDAO's best efforts to provide a clean resource, given the nature of the cryptocurrency realm, scams do exist, and even great projects are frequently compromised. The Maker Foundation grants program offers bounties to community members who bring attention to compromised third-party apps and services. --- ## Table of Contents <!-- TOC --> ### Official - [Properties](#properties) - [Channels](#channels) - [Meetings](#meetings) - [Events](#upcoming-events) - [Partnerships](#partnerships) ### Frequently Asked Questions - [FAQs](#faqs) ### Basics - [Onboarding Guides](#onboarding-guides) - [Beginner Guides](#beginner-guides) - [Tutorials](#tutorials) - [Stablecoins in General](#stablecoins-in-general) - [In-Depth Analysis:](#in-depth-analysis) [101](#makerdao-101) | [201](#makerdao-201) - [Maker Protocol](#maker-protocol) ### Governance | Risk - [Overview](#governance-and-risk) - [Governance Resources](#governance-resources) - [Key Votes](#key-votes) - [Important Forum Threads](#important-forum-threads) - [Governance call presentations](#governance-call-presentations) - [Analytics](#analytics) - [Meetings and Discussions](#meetings-and-discussions) ### Voting - [Overview](#voting-basics) - [Onboarding](#voter-onboarding) - [Dashboard](#voting-dashboard) - [Voting Contract](#voting-contract) ### Dai - [Generate Dai](#generate-dai) - [Earn Dai](#earn-dai) - [Hold Dai](#hold-dai) - [Use Dai](#use-dai) - [Spend Dai](#spend-dai) - [Lend Dai](#lend-dai) - [Trade Dai](#trade-dai) - [Watch Dai](#watch-dai) ### Milestones - [2020](#2020) - [2019](#2019) - [2018](#2018) - [2017](#2017) - [2016](#2016) ### Media Coverage - [Interviews](#interviews) - [Podcasts](#podcasts) - [Videos](#videos) - [Mentions](#dai-and-makerdao-mentions) - [Speculation](#speculation) - [Criticism](#criticism) ### Audits | Security - [Multi-Collateral Dai](#multi-collateral-dai) - [Single-Collateral Dai](#single-collateral-dai) - [Dappsys](#dappsys) ### Developer - [Developer Resources](#developer-resources) ### Translations - [Translated Resources](#translated-resources) ### Archive - [Archived Resources](#archived-resources) <!-- /TOC --> --- ## Official ### Properties - [MakerDAO Website](https://makerdao.com/) - [Whitepaper](https://makerdao.com/whitepaper/) - [Vault Portal](https://oasis.app/borrow/) - [Community Portal](https://community-development.makerdao.com/) - [Developer Portal](https://docs.makerdao.com/mcd-developer-guides/developer-guides-and-tutorials) - [Governance Portal](https://vote.makerdao.com/) - [Maker Documentation Portal](https://docs.makerdao.com/) - [Oasis](https://oasis.app) ### Channels - [Blog](https://blog.makerdao.com/) - [Forum](https://forum.makerdao.com/) - [Kakaotalk](https://open.kakao.com/o/giWg6J2) - [Reddit](https://www.reddit.com/r/MakerDAO) - [RocketChat](https://chat.makerdao.com/) - [Soundcloud](https://soundcloud.com/makerdao) - [Telegram](https://t.me/makerdaoofficial) - [Twitter](https://twitter.com/MakerDAO) - [WeChat (Makershequ)](https://web.wechat.com/) - [YouTube](https://www.youtube.com/MakerDAO) ### Meetings - Community Meetings [Join \*](https://meet.google.com/idg-znme-kvt) | [Calendar](https://calendar.google.com/calendar/embed?src=makerdao.com_3efhm2ghipksegl009ktniomdk%40group.calendar.google.com&ctz=America%2FLos_Angeles) | [Video Playlist](https://www.youtube.com/playlist?list=PLLzkWCj8ywWP1NPbyf69PUUCus_KsG7FI) - Scientific Governance and Risk Meetings [Join \*](https://zoom.us/j/697074715) | [Calendar](https://calendar.google.com/calendar/embed?src=makerdao.com_3efhm2ghipksegl009ktniomdk%40group.calendar.google.com&ctz=America%2FLos_Angeles) | [Video Playlist](https://www.youtube.com/playlist?list=PLLzkWCj8ywWNq5-90-Id6VPSsrk4OWVan) | [Audio Playlist](https://soundcloud.com/makerdao) | [Transcripts](https://community-development.makerdao.com/governance/governance-and-risk-meetings/transcripts) | [Minutes (Archive)](https://github.com/scottrepreneur/maker-minutes) **\* Note:** Public meetings are now password protected. Reach out to an admin on the [#general](https://chat.makerdao.com/channel/general) channel on Maker's Rocket.Chat to request access. ### Upcoming Events - [Events and Meetups Schedule](https://makerdao.com/en/events/) ### Partnerships - [Maker Partnerships](https://blog.makerdao.com/category/partnerships/) ## FAQs [_Glossary of Terms_](https://community-development.makerdao.com/en/faqs/glossary) - [All](https://community-development.makerdao.com/en/faqs) - [Dai](https://community-development.makerdao.com/en/faqs/dai) - [Dai Savings Rate](https://community-development.makerdao.com/en/faqs/dsr) - [Emergency Shutdown](https://community-development.makerdao.com/en/faqs/emergency-shutdown) - [Governance](https://community-development.makerdao.com/en/faqs/governance) - [Liquidation](https://community-development.makerdao.com/en/faqs/liquidation) - [MakerDAO(old)](https://community-development.makerdao.com/makerdao-scd-faqs/scd-faqs/makerdao): new coming soon - [MKR Token](https://community-development.makerdao.com/en/faqs/mkr-token) - [Oracles](https://community-development.makerdao.com/en/faqs/oracles) - [Stability Fees](https://community-development.makerdao.com/en/faqs/stability-fee) - [Vaults](https://community-development.makerdao.com/en/faqs/vault) - [Special FAQ: Where does the name "Dai" come from?](https://www.reddit.com/r/MakerDAO/comments/5q98b1/%E8%B2%B8_dai/) ## Basics ### Onboarding Guides - Dai Onboarding Guide: _coming soon_ - [Vault Onboarding Guide](https://community-development.makerdao.com/onboarding/vault-onboarding) - [Voter Onboarding Guide](https://community-development.makerdao.com/onboarding/voter-onboarding) ### Beginner Guides - [What is Pooled ETH (PETH)? The Fuel of the MakerDAO System](https://www.youtube.com/watch?v=icV3VOK2qYU) *Video by Chris Blec (August 2019)* - [What is Dai, and how does it work?](https://medium.com/mycrypto/what-is-dai-and-how-does-it-work-742d09ba25d6) *Medium Post by Sharon Manrique (February 2019)* - [What is MakerDAO? Understanding The Essential Mechanism](https://www.youtube.com/watch?v=50_htPDkZ4U) *Video by Ivan-on-Tech (November 2018)* - [What I Learned by Getting a Loan From a Robot (Ethereum, MakerDAO, Stablecoins)](https://youtube.com/watch?v=wwHqPjg8P9s&) *Video by Blockhead Media (September 2018)* - [How to Use the Dai Platform](https://medium.com/ethex-market/using-the-dai-platform-ac7c54df7a1e) *Medium Post by Jordan Randolph (August 2018)* - [A Stable Coin to Kill Traditional Secured Loans: Meet Maker Dai](https://medium.com/@chelinho1397/a-stable-coin-to-kill-traditional-secured-loans-ladies-and-gents-meet-dai-d17774a39f2e) *Medium Post by Chelo Cavazzoli (July 2018)* - [MakerDAO (MKR): Replacing Federal Reserve With Lines of Code](https://londonletter.org/makerdao/) *Article by Londonletter (June 2018)* - [Primer on Stablecoins: Part 1](https://blog.makerdao.com/part-1-why-stablecoins-matter-2/) | [Part 2](https://blog.makerdao.com/part-2-a-primer-on-dai-2/) | [Part 3](https://blog.makerdao.com/part-3-the-strengths-weaknesses-of-stablecoins/) *Blog Series by MakerDAO (June 2018)* - [Intro to MakerDAO Part 1](https://blockgeeks.com/guides/intro-to-makerdao-stablecoins-part-1/) | [Part 2](https://blockgeeks.com/guides/makerdao-stablecoin-blockgeeks-part-2/) *Articles by Blockgeeks (May 2018)* - [Messari: MakerDAO Analysis](https://bit.ly/2UGLLDS) *Analysis by Roy Learner (April 2018)* - [The Dai Stablecoin is a Game Changer](https://medium.com/@james_3093/the-dai-stablecoin-is-a-game-changer-for-ethereum-and-the-entire-cryptocurrency-ecosystem-13fb412d1e75) *Medium Post by James Seibel (April 2018)* - [What is Maker Dai? | Beginner's Guide](https://coincentral.com/maker-dai-beginner-guide/) *Coin Central Article by Johnny Sessa (February 2018)* - [TL:DR; A Snappy Guide to MakerDAO and Dai Tokens](https://medium.com/@shaunsauve/tl-dr-guide-to-makerdao-and-dai-tokens-228a11fab6a2) *Medium Post by Shaunsuave (December 2017)* - [MakerDAO for Dummies: Part 1](https://medium.com/cryptolinks/maker-for-dummies-a-plain-english-explanation-of-the-dai-stablecoin-e4481d79b90) | [Part 2](https://medium.com/@greg_10160/maker-for-dummies-part-2-3b364f86bbfd) *Medium Series by Gregory DiPrisco (November 2017 | July 2018)* ### Tutorials #### Written Tutorials - [An Intro To DaiJS: Build Applications on Top of MakerDAO](https://medium.com/quiknode/an-intro-to-daijs-b44f0080c5df) *Medium Post by Gaurav Agrawal (April 2019)* - [Get Started with MakerDAO CDPs and Dai.js](https://medium.com/@rossbulat/get-started-with-makerdao-cdps-and-dai-js-447c8f5eb1fa) *Medium Post by Ross Bulat (February 2019)* - [Opening a CDP using InstaDapp's CDP Portal](https://blog.goodaudience.com/first-loan-355d3c84d0ae) *Medium Post by Vishva Dave (December 2018)* - [Opening a CDP with the New MakerDAO CDP Portal](https://medium.com/@deepitag/opening-a-cdp-with-the-new-makerdao-portal-c2f009b0f5fd) *Medium Post by Deepit AG (November 2018)* - [Seamless Dai Integration in Existing DApps](https://blog.scintillating.us/2018/08/15/seamless-dai-integration-in-an-existing-dapp/) *Blog Post by Kevin Liu (August 2018)* - [How to Setup Dai for Local Development](https://medium.com/@matthewblack/how-to-setup-dai-for-local-development-37bfba5212fc) *Medium Post by Matthew Black (June 2018)* - [Managing CDPs Directly in MyEtherWallet (For Hardware Wallets)](https://www.reddit.com/r/MakerDAO/comments/8a1fmw/managing_cdps_directly_in_myetherwallet_for/) *Reddit Post by u/zarigis (April 2018)* #### Video Tutorials - [Executive Vote Audit Tutorial with Chris Mooney](https://youtu.be/Gjx7PkHf_6o) *Video by MakerDAO (April 2020)* - [Governance Dashboard Video Walkthroughs: Voting with a Linked Wallet](https://www.youtube.com/watch?v=-zq6_ZJ0MpI) *Video by MakerDAO (May 2019)* - [Governance Dashboard Video Walkthroughs: Voting with a Single Wallet](https://www.youtube.com/watch?v=nWhLzyhZV-Q) *Video by MakerDAO (May 2019)* - [Spanish Tutorial on Using the CDP Portal: MakerDAO Step by Step](https://www.youtube.com/watch?v=LGJ4h-pdvlw&t=1s) *Video by Marcin Jagodziński. Narrated by Luis Lozada (April 2019)* - [Polish Tutorial on Using the CDP Portal: MakerDAO Krok Po Kroku](https://youtu.be/eKbmSoNF2rc) *Video by Marcin Jagodziński (March 2019)* - [English Tutorial on Using the CDP Portal: MakerDAO Step by Step](https://www.youtube.com/watch?v=jQoBIVssz2s&feature=youtu.be) *Video by Marcin Jagodziński. Narrated by Kenny Rowe (March 2019)* - [MakerDAO CDP Tutorial - What is it and why is it awesome?](https://youtu.be/fr0mgjDwZ5c) *Video by Crypto Bobby (February 2019)* - [MakerDAO Tutorial - How To Create A Loan CPD](https://www.youtube.com/watch?v=sLRDWTtNC04) *Video by Nuggets News (Novermber 2018)* ### Stablecoins in General #### Media - [Stablecoins in 2019: Reliable, Proliferating, Liquid, and Global](https://media.consensys.net/stablecoins-in-2019-reliable-proliferating-liquid-and-global-6ec443586bf5) *Medium Post by ConsenSys (March 2019)* - [Stablecoin Overview: A Condensed Version](https://blog.coinmarketcap.com/2018/11/16/stablecoin-overview-a-condensed-version/) *Post by the CoinMarketCap Blog (November 2018)* - [A Taxonomy of Stablecoins - Token Daily](https://www.tokendaily.co/blog/a-taxonomy-of-stablecoins) *Post by Cyrus Younessi of Scalar Capital (October 2018)* - [A Brief History of Stablecoins (Part 1)](https://blog.bitmex.com/a-brief-history-of-stablecoins-part-1/) *Post by Bitmex Research (July 2018)* - [The Instability of Stablecoins](https://hackernoon.com/the-instability-of-stablecoins-69e2c8e1729e) *Hackernoon Post by Anthony Xie (May 2018)* - [Introduction to Stable Coins](https://medium.com/@blockspace.info/introduction-to-stable-coins-f8553d3a0feb) *Medium Post by By Victor Hogrefe, Aviv Milner, of Blockspace Solutions (April 2018)* - [The Case for Central Bank Electronic Money and The Non-Case for Central Bank Cryptocurrencies](https://research.stlouisfed.org/publications/review/2018/02/13/the-case-for-central-bank-electronic-money-and-the-non-case-for-central-bank-cryptocurrencies) *Post by A. Berentsen and F. Schar of The St. Louis Federal Reserve Bank (April 2018)* - [The Rise of Stablecoins](https://coinjournal.net/the-rise-of-stablecoins/) *Post by Alex T. (April 2018)* - [Blockchain After the Gold Rush](https://hackernoon.com/blockchain-after-the-gold-rush-e1c6d3044dae) *Hackernoon Post by Abram Symons (April 2018)* - [_Satire:_ Announcing World Trade Francs: The Official Ethereum Stablecoin](https://blog.ethereum.org/2018/04/01/announcing-world-trade-francs-official-ethereum-stablecoin/) *Post by Vitalik Buterin (April 2018)* - [Race for Stable Cryptos Heats Up as Volatility and Demand Surge](https://www.bloomberg.com/news/articles/2018-02-21/race-for-stable-cryptos-heats-up-as-volatility-and-demand-surge?) *Post by Camila Russo (February 2018)* - [Stablecoins: Designing a Price-Stable Cryptocurrency](https://hackernoon.com/stablecoins-designing-a-price-stable-cryptocurrency-6bf24e2689e5) *Hackernoon Post by Haseeb Qureshi (February 2018)* - [Stablecoins 101: Why the Crypto Market Needs Fiat Stability](https://cryptoslate.com/stablecoins-101-crypto-market-needs-fiat-stability/) *Post by Reuben Jackson (February 2018)* - [An Overview of Stablecoins - Multicoin Capital](https://multicoin.capital/2018/01/17/an-overview-of-stablecoins/) *Post by Myles Snider of MultiCoin Capital (January 2018)* - [Can a Blockchain Help Charities?](https://www.viget.com/articles/can-a-blockchain-help-charities/) *Post by Leo Bauza (October 2017)* #### Other Stablecoin Projects - [AMPL: Ampleforth](https://www.ampleforth.org): Algorithmic Stability - [CUSD: Carbon](https://www.carbon.money/): Algorithmic Stability - [USDC: Coinbase](https://www.centre.io/usdc/): USD Backed - [GUSD: Gemini](https://gemini.com/dollar/): USD Backed - [NUSD: Neutral](https://dapp.neutralproject.com/): Metastable Stablecoin Basket - [PAX: Paxos](https://www.paxos.com/pax/): USD Backed - [RSV: Reserve](https://www.reserve.org/): Collateral Backed - [SU: StableUnit](https://stableunit.org/): Collateral Backed - [SUSD: Synthetix](https://www.synthetix.io/): Collateral Backed - [TUSD: TrustToken](https://www.trusttoken.com/trueusd/): USD Backed - [USDT: Tether](https://tether.to/): USD Backed ### In-Depth Analysis #### MakerDAO 101 - [How Dai Addresses Centralization and Counterparty Risk](https://blog.makerdao.com/how-dai-addresses-centralization-and-counterparty-risk/) *Blog Post by MakerDAO (April 2018)* - [Ether Deflation Caused by MakerDAO Part 1](https://medium.com/@deepitag/ether-deflation-as-caused-by-makerdao-part-1-723b89bb24f7) | [Part 2](https://medium.com/@deepitag/ether-deflation-as-caused-by-makerdao-part-2-8e5a12f1d34e) | [Part 3](https://medium.com/@deepitag/ether-deflation-as-caused-by-makerdao-part-3-a-spur-of-the-moment-analysis-39d0d0d51720) *Medium Post by Deepit AG (September 2018)* - [Maker DAO Network Analysis](https://santiment.net/blog/makerdao-network-analysis/) *Post by Santiment (October 2018)* - [The Role of Ether in Multi-Collateral Dai](https://medium.com/@TrustlessState/the-role-of-ether-in-multi-collateral-dai-cfc8b43ab50c) *Medium Post by David Hoffman (December 2018)* - [MakerDAO Token Economics: An Independent Research Report](https://www.economicsdesign.com/portfolio/makerdao/) *Research Report by Lisa JY Tan (September 2019)* - [Rise of the Cryptodollar, a look at DeFi Interest Rates](https://bankless.substack.com/p/rise-of-the-cryptodollar) *Blog Post by Ryan Sean Adams (February 2020)* #### MakerDAO 201 - [Measuring Dai Supply and Demand Price Effects](https://insights.santiment.net/read/measuring-dai-supply-and-demand-price-effects-623) *Post by Primoz Kordez on Santiment (August 2019)* - [A Ratings-Based Model for Credit Events in MakerDAO](https://static1.squarespace.com/static/5a479ee3b7411c6102f75729/t/5d25fc556a956b0001aa2c62/1562770517350/Maker-Ratings.pdf) *Paper by Alex Evans (July 2019)* - [Maker Network Overview: Placeholder VC](https://www.placeholder.vc/blog/2019/3/1/maker-network-report) *Report by Placeholder VC (March 2019)* - [MakerDAO Stability Fee Benchmarking](https://medium.com/@primoz.kordez/makerdao-stability-fee-benchmarking-1c440b69de6b) *Medium Post by Primoz Kordez (February 2019)* - [Evaluating MKR Buyback and Burn model](https://medium.com/@TrustlessState/evaluating-mkr-def6d36092bd) *Medium Post by David Hoffman (February 2019)* - [Dai in Numbers](https://blog.makerdao.com/dai-in-numbers/) *Blog Post by MakerDAO (February 2019)* - [Examining the Supply of Maker Dai: An Analysis into CDP Demand](https://medium.com/coinmonks/examining-the-supply-of-maker-dai-b04fbab7b4cd) *Medium Post by Jack Purdy (January 2019)* - [The Auction Grinding Attack: A Case for a Liquidation Penalty in MCD](https://github.com/livnev/auction-grinding/blob/master/grinding.pdf) *Paper by Lev Livnev (June 2018)* - [Single Collateral Dai — 9 Months in Review](https://medium.com/@mikeraymcdonald/single-collateral-dai-9-months-in-review-b9d9fbe45ab) *Medium Post by Mike McDonald (September 2018)* - [Maximum Leverage on Maker](https://ian.pw/posts/2018-01-25-maximum-leverage-on-maker.html) *Blog Post by Ian Macalinao (January 2018)* - [Measuring Maker-Dai Stability](https://medium.com/tokenanalyst/measuring-maker-dai-stability-f74c23108128) *Medium Post by Sid Shekhar (March 2018)* - [Collateralized Debt Obligations for Issuer-Backed Tokens](https://ethresear.ch/t/collateralized-debt-obligations-for-issuer-backed-tokens/525) *Research Post by Vitalik Buterin (January 2018)* - [How Stable are the top Stablecoins? A Quantitative Analysis](https://medium.com/coinmonks/how-well-do-the-top-stablecoins-perform-a-quantitative-analysis-c56d022719b) *Medium Post by Wes Levitt (January 2019)* - [MakerDAO 2018 Revenue Analysis](https://medium.com/@marcandrdumas/makerdao-2018-revenue-analysis-55462642e2b9) *Medium Post by Marc-André Dumas (February 2019)* - [MakerDAO Q1 2019 Revenue Analysis](https://medium.com/@marcandrdumas/makerdao-q1-2019-revenue-analysis-9afe82af3372) *Medium Post by Marc-André Dumas (April 2019)* - [MakerDAO Tokens Explained: DAI, WETH, PETH, SIN, MKR. Part 1](https://medium.com/coinmonks/makerdao-tokens-explained-dai-weth-peth-sin-mkr-part-1-a46a0f687d5e) *Medium Post by Aleksey Studnev (May 2019)* - [Maker DAO Transactions Illustrated](https://medium.com/coinmonks/maker-dao-transactions-illustrated-691ad2715cf7) *Medium Post by Aleksey Studnev (May 2019)* ### Maker Protocol #### Documentation Portal - [MCD Docs: Introduction to the Maker Protocol](https://docs.makerdao.com/) - [Maker Protocol 101](https://docs.makerdao.com/maker-protocol-101) ##### Smart Contract Modules - [Core Module](https://docs.makerdao.com/smart-contract-modules/core-module) - [Collateral Module](https://docs.makerdao.com/smart-contract-modules/collateral-module) - [Dai Module](https://docs.makerdao.com/smart-contract-modules/dai-module) - [System Stabilizer Module](https://docs.makerdao.com/smart-contract-modules/system-stabilizer-module) - [Oracle Module](https://docs.makerdao.com/smart-contract-modules/oracle-module) - [MKR Module](https://docs.makerdao.com/smart-contract-modules/mkr-module) - [Governance Module](https://docs.makerdao.com/smart-contract-modules/governance-module) - [Rates Module](https://docs.makerdao.com/smart-contract-modules/rates-module) - [Proxy Module](https://docs.makerdao.com/smart-contract-modules/proxy-module) - [Emergency Shutdown Module](https://docs.makerdao.com/smart-contract-modules/emergency-shutdown-module) - [Maker Protocol Shutdown](https://docs.makerdao.com/smart-contract-modules/shutdown) ##### Other MCD Documentation - [MCD Glossaries](https://docs.makerdao.com/other-documentation/system-glossary) - [Smart Contract Annotations](https://docs.makerdao.com/other-documentation/smart-contract-annotations) ##### Migration - [SCD<>MCD Migration](https://docs.makerdao.com/migration/scd-mcd-migration-detailed-documentation) ##### Auctions - [The Auctions of the Maker Protocol](https://docs.makerdao.com/auctions/the-auctions-of-the-maker-protocol) ## Governance and Risk The Maker Governance Framework is built on rigorously vetted, reproducible, scientific models created by experts with proven track records in the traditional finance space. Maker's risk analysts share research ideas, discuss quantitative models, and perform due diligence on collateral types. Maker values the opinions of informed members who participate in on-going Governance discussions. ### Governance Resources - [MakerDAO Governance Risk Framework Part 1](https://blog.makerdao.com/makerdao-governance-risk-framework/) | [Part 2](https://blog.makerdao.com/makerdao-governance-risk-framework-part-2/) | [Part 3](https://blog.makerdao.com/makerdao-governance-risk-framework-part-3/) *Blog Posts by MakerDAO (July 2018 | December 2018)* - [Lessons From MakerDAO](https://thecontrol.co/lessons-from-makerdao-a42081116e9a) *Medium Post by Nick Tomaino (February 2018)* - [Deep Dive Into MakerDAO Governance: A Look at the Code for Governance in SCD](https://medium.com/@banteg/deep-dive-into-makerdao-governance-437c89493203) *Medium Post by Banteg (December 2018)* - [Foundation Proposal V2](https://blog.makerdao.com/foundation-proposal-v2/) | [V1](https://blog.makerdao.com/foundation-proposal/) *Blog Post by MakerDAO (August 2018 | June 2018)* - [The Importance of Debt Ceilings within MakerDAO’s Collateralized Stable-Coin System](https://medium.com/@davidutrobin/the-importance-of-debt-ceilings-within-the-makerdao-collateralized-stable-coin-system-2a57f0688b50) *Medium Post by David Utrobin (April 2018)* - [Maker Governance: Exploring the Importance of Stability Fees](https://fitznerblockchain.consulting/maker-governance-exploring-the-importance-of-stability-fees/) *Article by Fitzner Blockchain Consulting (February 2019)* - [Introducing A New Governance On-Boarding Experience](https://blog.makerdao.com/makerdao-introducing-a-new-governance-on-boarding-experience/) *Medium Post by MakerDAO (May 2019)* - [FakerDAO: An Exploration Of MakerDAO’s Governance Incentives](https://www.scopelift.co/blog/fakerdao) *Blog Post by Ben DiFrancesco (March 2020)* ### Key Votes All Votes below have passed - [Multi-Collateral Dai activation](https://blog.makerdao.com/the-votes-are-in-mcd-is-approved/) | [Executive Vote](https://mkrgov.science/executive/0xf44113760c4f70afeeb412c63bc713b13e6e202e) - [Replace Debt Auction contract in MCD](https://forum.makerdao.com/t/proposal-upgrading-the-flopper/835) and [remove the MKR oracle delay in SCD?](https://forum.makerdao.com/t/proposal-remove-the-scd-mkr-oracle-security-module/837) | [Executive Vote](https://mkrgov.science/executive/0x902f009d4de4a7828284b04b364dd43f00e51a02) - [Set the Governance Security Module Delay to 24 hours?](https://forum.makerdao.com/t/signal-request-should-we-have-another-executive-vote-regarding-the-governance-security-module/1209) | [Executive Vote](https://mkrgov.science/executive/0xd24fbbb4497ad32308bda735683b55499ddc2cad) - [Poll: Should we suspend monetary policy votes when there are emergency technical changes to be made to the system? **Passed**](https://forum.makerdao.com/t/signal-request-how-do-we-handle-executive-bundling-in-relation-to-technical-changes/965) | [Governance Poll](https://mkrgov.science/poll/94) - [Poll: Should we replace the weekly DSR Rate governance poll with a weekly DSR Spread governance poll?](https://forum.makerdao.com/t/signal-request-should-we-replace-the-weekly-dsr-governance-poll-with-a-dsr-spread-governance-poll/969) | [Governance Poll](https://mkrgov.science/poll/77) - [Poll: Migration Risk Construct Proposal](https://forum.makerdao.com/t/proposal-migration-risk-construct/724) | [Governance Poll](https://mkrgov.science/poll/47) - [Poll: DeFi Public Feed Proposal](https://forum.makerdao.com/t/proposal-defi-public-feed-appointments/475) | [Governance Poll](https://mkrgov.science/poll/40) - [Poll: Responsible Oracle Migration Proposal](https://forum.makerdao.com/t/proposal-responsible-oracle-migration/509) | [Governance Poll](https://mkrgov.science/poll/35) - [Poll: Oracles Incentives Restructuring](https://forum.makerdao.com/t/proposal-oracles-incentives-restructuring/476) | [Governance Poll](https://mkrgov.science/poll/39) - [Poll: Ratify the Interim Oracle Team Mandate](https://forum.makerdao.com/t/mandate-oracle-teams/443) | [Governance Poll](https://mkrgov.science/poll/37) - [Poll: Exponential Rate Stepping for Stability Fee Polls](https://forum.makerdao.com/t/signal-request-should-we-move-to-exponential-rate-stepping-for-stability-fee-polls/40) | [Governance Poll](https://mkrgov.science/poll/34) - [Poll: Ratify the Interim Governance Facilitator Mandate](https://forum.makerdao.com/t/mandate-interim-governance-facilitators/264) | [Governance Poll](https://mkrgov.science/poll/29) - [Poll: Ratify the Interim Risk Team Mandate](https://forum.makerdao.com/t/mandate-risk-teams/282) | [Governance Poll](https://mkrgov.science/poll/30) ### Important Forum Threads - [An Explanation of Continuous Voting and the Peculiarities of the 7/26 Executive Stability Fee Vote](https://forum.makerdao.com/t/an-explanation-of-continuous-voting-and-the-peculiarities-of-the-7-26-executive-stability-fee-vote/193/1) - [Governance Initiatives](https://forum.makerdao.com/t/governance-initiatives/1347) - [Signaling Guidelines](https://forum.makerdao.com/t/practical-guide-to-the-signaling-process/2623) - [Participation in Maker governance](https://forum.makerdao.com/t/participation-in-maker-governance/968) - [Vote delegation](https://forum.makerdao.com/t/vote-delegation-is-not-something-we-should-be-striving-for/336) - [Stablecoins as collateral](https://forum.makerdao.com/t/whats-the-point-of-adding-stablecoins-as-collateral/453/25) - [DSR spread](https://forum.makerdao.com/t/a-governance-model-for-maker/1056) - [Validation Teams Proposal](https://forum.makerdao.com/t/validation-teams-a-proposal-for-a-new-variety-of-team/570) - [Interim Governance Facilitators Mandate](https://forum.makerdao.com/t/mandate-interim-governance-facilitators/264) - [Oracle Team mandate](https://forum.makerdao.com/t/mandate-oracle-teams/443) - [Oracle Migration](https://forum.makerdao.com/t/proposal-responsible-oracle-migration/509) - [Risk Team mandate](https://forum.makerdao.com/t/mandate-risk-teams/282) - [Migration Risk Construct](https://forum.makerdao.com/t/proposal-migration-risk-construct/724) - [Executive bundling in relation to technical changes](https://forum.makerdao.com/t/signal-request-how-do-we-handle-executive-bundling-in-relation-to-technical-changes/965/4) - [Systemic Risk Directory](https://forum.makerdao.com/t/systemic-risk-directory/157) - [SCD Shutdown Parameters Discussion](https://forum.makerdao.com/t/summary-discussion-of-parameters-for-scd-shutdown/1130/2) - [Dark Fix Mechanism: A Proposal for Handling Critical Vulnerabilities](https://forum.makerdao.com/t/dark-fix-mechanism-a-proposal-for-handling-critical-vulnerabilities-in-the-maker-protocol/1297) - [Ranked Choice Voting](https://forum.makerdao.com/t/signal-request-add-ranked-choice-voting-as-an-option-for-governance-polls/1274) - [How to Audit Executive contract code?](https://forum.makerdao.com/t/how-to-audit-executive-contract-code/1292/7) - [Compensating vault holders that liquidated at 0 bid](https://forum.makerdao.com/t/compensating-vault-holders-that-liquidated-at-0-bid/1541) - [Black Thursday Response Thread](https://forum.makerdao.com/t/black-thursday-response-thread/1433) ### Governance Call Presentations - [May 21, 2020: MIP 15 Dark Spell Mechanism with Wil Barnes](https://youtu.be/Rbd2hDIk7vc?t=2261) - [May 21, 2020: SourceCred and Maker with Dandelion Mane](https://youtu.be/Rbd2hDIk7vc?t=662) - [Mar 24, 2020: Debt Auction Blocking in the Dai Credit System with Kurt Barry](https://www.youtube.com/watch?v=erh25lnaIo0&feature=youtu.be&t=475) | [Written Summary](https://community-development.makerdao.com/governance/governance-and-risk-meetings/summaries/episode-82) - [Mar 05, 2020: Collateral Risk Model Presentation with Cyrus Younessi](https://www.youtube.com/watch?v=ZT8flAjPKLU&feature=youtu.be&t=2693) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-76.md#cyrus-younessi) - [Feb 27, 2020: Oracles and Governance with Nik Kunkel](https://www.youtube.com/watch?v=6APWQZ_7y2g&feature=youtu.be&t=2006) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-75.md#oracles) - [Feb 13, 2020: The Dark Fix (solution for handling bugs with the GSM delay) with Wil Barnes](https://youtu.be/e4VTkFV3lyc?t=1876) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-73.md#the-dark-fix) - [Feb 06, 2020: Governance Analystics Dashboard Demo with LFW](https://youtu.be/nzMwDpIWTCU?t=157) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-72.md#longforwisdom) - [Jan 09, 2020: Intro and Current Governance Development Backlog with Derek Flossman and Charles St. Louis](https://www.youtube.com/watch?v=QFFmPWYLh3Y&feature=youtu.be&t=368) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-68.md#intro-and-current-governance-development-backlog) - [Jan 02, 2020: Argument for a DSR Spread Poll Presentation with Sam M](https://www.youtube.com/watch?v=dRG1TThjv5c&feature=youtu.be&t=1288) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-67.md#samm) - [Nov 28, 2019: Monetary Policy in MCD with Primoz Kordez](https://www.youtube.com/watch?v=hAlPwTMd4Yk&feature=youtu.be&t=1619) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-63.md#monetary-policy-in-mcd) - [Nov 21, 2020: MKR Authority Transfer with Wouter Kampmann](https://www.youtube.com/watch?v=W6AeAC7mmDk&feature=youtu.be&t=730) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-62.md#mcd-next-steps) - [Nov 14, 2020: System and Oracle Risk Parameters with Cyrus Younessi](https://www.youtube.com/watch?v=DD7g2t29D1E&feature=youtu.be&t=1172) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-61.md#risk) - [Nov 07, 2020: Migration Risk Construct Review - part 3 with Cyrus Younessi](https://www.youtube.com/watch?v=G8ga8vjMWkw&feature=youtu.be&t=872) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-60.md#risk) - [Oct 31, 2020: Migration Risk Construct Review - part 2 with Cyrus Younessi](https://www.youtube.com/watch?v=KrutexQ0Cs4&feature=youtu.be&t=1483) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-59.md#cyrus) - [Oct 24, 2020: Migration Risk Construct Review - part 1 with Cyrus Younessi](https://www.youtube.com/watch?v=rKq4J4bKndc&feature=youtu.be&t=159) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-58.md#cyrus) - [Sep 19, 2020: Tokenized Asset Portfolios - TAP with Fluidity Team](https://www.youtube.com/watch?v=aLoqcivNvV0&feature=youtu.be&t=681) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-53.md#collateral-discussion) - [Sep 12, 2019: Oracles v2 - part 2 with Nik Kunkel](https://www.youtube.com/watch?v=gqVnwOL42hQ&feature=youtu.be&t=1270) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-52.md#oracles) - [Sep 05, 2019: Oracles v2 - part 1 with Nik Kunkel](https://www.youtube.com/watch?v=7jKNv8DMxmQ&feature=youtu.be&t=904) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-51.md#oracles) - [Jul 18, 2020: Ratings-Based Model for Credit Events in MakerDAO with Alex Evans](https://www.youtube.com/watch?v=0wScyBRdLwE&feature=youtu.be&t=464) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-44.md#alex-evans-discussing-a-ratings-based-model-for-credit-events-in-makerdao-0743) - [July 11, 2020: Collateral Risk Quantitative Analysis - part 3 with Cyrus Younessi](https://www.youtube.com/watch?v=DlH0bMvqO9w&feature=youtu.be&t=798) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-43.md#cyrus-quantitative-modeling-1320) - [Jun 27, 2020: Collateral Risk Quantitative Analysis - part 2 with Cyrus Younessi](https://www.youtube.com/watch?v=pOA-TIOQBs8&feature=youtu.be&t=1417) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-41.md#cyrus-single-cdp-credit-risk-model-2337) - [Jun 20, 2020: Collateral Risk: Quantitative Analysis - part 1 with Cyrus Younessi](https://www.youtube.com/watch?v=lSfXtvCplwc&feature=youtu.be&t=1502) | [Written Summary](https://github.com/makerdao/community/blob/master/governance/governance-and-risk-meetings/summaries/episode-40.md#cyrus-quantitative-analysis-2502) ### Analytics - [Governance Analytics Dashboard](https://mkrgov.science) - [Governance Poll History](https://mkrgov.science/polls) - [Executive Vote History](https://mkrgov.science/executive) - [MCD Parameter Changelog, based on passed Executive Votes](https://catflip.co/changelog) ### Meetings and Discussions - [Governance Forum](https://forum.makerdao.com/c/governance) - Scientific Governance and Risk Meetings [Join \*](https://zoom.us/j/697074715) | [Calendar](https://calendar.google.com/calendar/embed?src=makerdao.com_3efhm2ghipksegl009ktniomdk%40group.calendar.google.com&ctz=America%2FLos_Angeles) | [Video Playlist](https://www.youtube.com/playlist?list=PLLzkWCj8ywWNq5-90-Id6VPSsrk4OWVan) | [Audio Playlist](https://soundcloud.com/makerdao) | [Transcripts](https://community-development.makerdao.com/governance/governance-and-risk-meetings/transcripts) | [Minutes (Archive)](https://github.com/scottrepreneur/maker-minutes) **\* Note:** Public meetings are now password protected. Reach out to an admin on the [#general](https://chat.makerdao.com/channel/general) channel on Maker's Rocket.Chat to request access. ## Voting Basics MakerDAO relies on its governance community to manage the Maker Protocol. Successful governance grows the system, improves long-term reliability, and encourages the widespread adoption of Dai. Participate in MakerDAO Governance by staying informed and voting regularly. ### Voter Onboarding - [Voter Onboarding Guide](https://community-development.makerdao.com/onboarding/voter-onboarding) ### Voting Dashboard - [Governance Portal](https://vote.makerdao.com) - [Governance Poll History](https://vote.makerdao.com/polling) ### Voting Contract - [The MakerDAO Voting Proxy Contract](https://blog.makerdao.com/the-makerdao-voting-proxy-contract/) #### Setup Guides *Notice: The Voting Portal is undergoing an update.* - [Maker Governance Voting Setup for Ledger](https://web.archive.org/web/20190112110248/https://medium.com/makerdao/how-to-setup-the-voting-contract-using-a-ledger-hardware-wallet-1f00d49ce43a) - [Maker Governance Voting Setup for Trezor](https://web.archive.org/web/20190112110249/https://medium.com/makerdao/how-to-setup-the-voting-contract-using-a-trezor-hardware-wallet-af4969aa157f) - [Maker Governance Voting Setup for MetaMask](https://web.archive.org/web/20190112110247/https://medium.com/makerdao/how-to-setup-the-voting-contract-using-two-metamask-accounts-4e83e4fec602) - [Maker Governance Voting Setup for Paper Wallets Using SETH](https://web.archive.org/web/20180913234419/https://medium.com/makerdao/guide-vote-proxy-setup-with-seth-f62397a10c59) - [Video Voting Tutorial](https://youtu.be/wP7DedWcEmg?list=PLLzkWCj8ywWP6yCPPm1IRKysNsrzg3LQ6) ## Dai - [The Dai Universe](https://github.com/jordanlyall/dai-universe): Jordan Lyall aggregates all the different technical manifestations of Dai ### Generate Dai - Vault Onboarding Guide: _coming soon_ - [Oasis Vault Portal](https://oasis.app/borrow): Lock Collateral in Maker Vaults to Generate Dai #### Third Party Vault Portals - [DeBank](https://debank.com/): DeBank is a free data-driven all-in-1 DeFi wallet with (portfolio tracker + token swap + project list + stats ranking) - [DeFi Saver](https://defisaver.com/): Manage CDPs and Automate Liquidation Protection - [InstaDapp](https://instadapp.io/dapp/borrow/): Alternative CDP UI With Access to Lending and Borrowing - [Shadowlands](https://github.com/kayagoban/shadowlands): TextUI Dapp Platform built on Python3.5+, Web3 and Asciimatics - [Zerion](https://zerion.io): Interface to manage multiple Vaults and CDPs in a single place ### Earn Dai - [Coinbase (Earn Dai)](https://www.coinbase.com/earn/dai/): Earn Dai by watching introductory lessons - [Community Meetup Grants](https://community-development.makerdao.com/meetups): Get funding in Dai to host a Maker meetup - [Development Grants Program](https://community-development.makerdao.com/grants): The MakerDAO Community Grants Program - [Hackathons and Bounties](https://community-development.makerdao.com/hackathons): The MakerDAO Hackathons Initiative - [Oasis (DSR)](https://oasis.app/save): Earn Interest on Dai with the DSR ### Hold Dai #### Hardware Wallets - [KeepKey](https://shapeshift.io/keepkey/) | [Ledger](https://ledger.com/) | [Trezor](https://trezor.io/) #### Web | Paper Wallets - [MyCrypto](https://mycrypto.com) | [MyEtherWallet](https://www.myetherwallet.com/) #### Browser Extension Wallets - [MetaMask](https://metamask.io/) #### Mobile Wallets - [Argent](https://www.argent.xyz/) - [BRD](https://brd.com/) - [Celcius](https://celsius.network/) - [DexWallet](https://www.dexwallet.io/) - [Edge](https://edge.app/) - [Ethos Universal Wallet](https://www.ethos.io/universal-wallet/) - [Freewallet](https://freewallet.org/eth-wallet) - [MEW wallet](https://www.mewwallet.com/) - [WiniWallet](https://www.winiwallet.io) #### Mobile | Browser Wallets - [AlphaWallet](https://alphawallet.com/) - [Coinbase Wallet](https://wallet.coinbase.com/) - [imToken](https://token.im/) - [Trust Wallet](https://trustwallet.com/) - [Lumi](https://lumiwallet.com/) #### Mobile | Desktop Wallets - [Atomic Wallet](https://atomicwallet.io/) - [Exodus](https://www.exodus.io/) - [Status.im](https://status.im/) - [Zelcore](https://zel.network/project/zelcore/) ### Use Dai #### Apps | Integrations | Tools - [Atstake](https://atstake.net/): Marketplace and Platform for Contract Enforcement - [Bounty0x](https://bounty0x.io/): Bounty Hunting Platform - [Bounties Network](https://bounties.network/): Platform to Create Projects, Collaborate, and Freelance - [Chai](https://chai.money/): ERC-20 wrapper for Dai in DSR - [Gilded Finance](https://gilded.finance/): Dai Invoicing - [Gitcoin](https://gitcoin.co/): Crowdfunding and Freelance Developers Platform - [LNDR](https://blockmason.io/lndr/): Expense Sharing App - [Liquid Long](https://liquid-long.keydonix.com/): Leverage ETH - [PoolTogether](https://www.pooltogether.us/): Lossless Lottery - [Pool Dai](https://zeframlou.github.io/pooldai/): Lossless Donation Protocol - [Request](https://create.request.network/): Request a Payment in Dai - [Sablier](https://pay.sablier.finance): Stream Money with Dai - [Whisp.Money](https://whisp.money): Dai Payroll Solution #### Merchant Solutions | Payment Processors - [Coingate](https://coingate.com/): Accept payment in Dai and 50 other crypto currencies - [Dexpay](https://dexpay.me/): Sell more by accepting Dai, Eth and other cryptocurrencies - [Gilded](https://get.gilded.finance/): Crypto accounting - [Groundhog](https://groundhog.network/) - Accept recurring and pre-authorized subscription payments from customers - [Ink Protocol](https://paywithink.com/): Securely buy & sell anywhere with decentralized reputation & escrow using the XNK token - [Reqify](https://reqify.io/): Accept cryptocurrency payments with Request for Shopify - [WooREQ](https://wooreq.com/): Accept cryptocurrency payments with Request for WooCommerce ### Spend Dai - [Aave](https://aave.com/): Use crypto to send fiat payments to anyone - [AdEx Network](https://www.adex.network): Platform for decentralized advertising using Dai as payment method - [Bidali](https://giftcards.bidali.com/buy-giftcards-with-dai/): Buy gift cards with Dai - [CelerX](https://celerx.app/): Play eSports games, win crypto prizes - [Coinevents.io](https://coinevents.io): Event tickets, sell your event's tickets for crypto - [Grid Plus Energy](https://gridplus.io/energy): Pay for electricity with Dai, ETH, or BTC (Texas) - [Living Room of Satoshi](https://www.livingroomofsatoshi.com/): Pay any bill with cryptocurrency (Australia) - [Monolith](https://monolith.xyz/): Ethereum wallet with debit card options and various security features - [NeedsList](https://needslist.co): Purchase items that are critically needed and help with disaster preparedness - [OpenSea](https://opensea.io): Buy and sell digital goods and assets, make offers in Dai - [Swarm](https://www.swarm.fund/): Participate in security token offerings - [Unicef](https://lp.unicef.fr/donate-dai/): Donate Dai - [Wirex](https://wirexapp.com/card/): Visa debit card that can be top-up with Dai ### Lend Dai - [Aave](https://aave.com/): Open Source and Non-Custodial Lending and Borrowing - [Celcius](https://celsius.network/): Custodial Lending and Borrowing - [Compound.Finance](https://app.compound.finance/): Decentralized Lending and Borrowing - [Dharma](https://www.dharma.io/): Pretty Compound UI - [DyDx](https://dydx.exchange/): Decentralized Trading, Lending, and Borrowing - [Ethichub](https://ethichub.com/en): P2P Lending to Communities Around the Globe - [Fulcrum](https://fulcrum.trade/#/lend): Decentralized Dai Lending and Margin Trading - [Nexo](https://nexo.io/): Custodial Lending and Borrowing - [Nuo](https://www.nuo.network/): Non-Custodial Lending, Borrowing, and Trading - [RAY](https://staked.us/v/robo-advisor-yield/): Earn the Highest Yield in DeFi - [Zerion](https://zerion.io): Simple interface to the protocols of decentralized finance ### Trade Dai #### Dai and MKR Markets - [Messari](https://messari.io/): [DAI](https://messari.io/asset/Dai/exchanges) | [MKR](https://messari.io/asset/maker/exchanges) - [CoinGecko](https://www.coingecko.com/): [DAI](https://www.coingecko.com/en/coins/dai) | [MKR](https://www.coingecko.com/en/coins/maker) #### Token Swaps - [0xInstant](https://0x.org/instant) - [1inch.exchange](https://1inch.exchange/) - [Airswap](https://instant.airswap.io/) - [Bancor](https://www.bancor.network/) - [Collateral Swap](https://collateralswap.com/) - [DEX.AG](https://dex.ag/) - [KyberSwap](https://kyberswap.com/swap) - [Liquality](https://liquality.io/) - [SimpleSwap](https://simpleswap.io/) - [Swap.online](https://swaponline.io/) - [Uniswap](https://uniswap.exchange/swap) - [Tokenlon](https://tokenlon.im/instant) - [Zerion](https://zerion.io) #### Non-Custodial Exchanges - [Changelly](https://changelly.com/) - [DDex](https://ddex.io/spot/ETH-DAI) - [DeversiFi](https://trustless.ethfinex.com/DAIETH) - [Dex.Blue](https://dex.blue/) - [DyDx](https://trade.dydx.exchange) - [EtherDelta](https://etherdelta.com/) - [ForkDelta](https://forkdelta.app/#!/trade/DAI-ETH) - [Oasis](https://oasis.app/trade/market/WETH/DAI) - [Paradex](https://paradex.io/market/weth-dai) - [RadarRelay](https://app.radarrelay.com/WETH/DAI) - [ShapeShift](https://shapeshift.com/) - [Tokensets](https://www.tokensets.com/) - [Totle](https://app.totle.com) #### Custodial Exchanges - [Ace.io](https://ace.io): Taiwan - [Bitfinex](https://www.bitfinex.com): Hong Kong - [Bitkub](https://www.bitkub.com/market/DAI): Thailand - [Coinbase](https://pro.coinbase.com/trade/DAI-USDC): USA - [CoinJar](https://exchange.coinjar.com/trade): Australia - [Coinone](https://coinone.co.kr/exchange/trade/dai/krw): Korea - [COSS.IO](https://coss.io/): Singapore - [Exmo](https://exmo.com/en/trade#?pair=DAI_ETH): England - [Gate.io](https://www.gate.io/trade/DAI_USDT): USA - [Hanbitco](https://www.hanbitco.com/exchange/dai_btc): South Korea - [HitBTC](https://hitbtc.com/ETH-to-DAI): EU - [INDODAX](https://indodax.com/market/DAIIDR): Indonesia - [Korbit](https://www.korbit.co.kr/markets/?market=dai-krw): South Korea - [Kraken](https://trade.kraken.com/ko/markets/kraken/dai/usd): USA - [KuCoin](https://trade.kucoin.com/spot): Hong Kong - [OKEx](https://www.okex.com/en/spot/trade/btc-dai): Malta - [Panda](https://panda.exchange/en-IC/): Latin America - [Probit](https://www.probit.com/en-us): Republic of Seychelles - [Tokpie](https://tokpie.com/view_exchange/dai-usdc/): Hong Kong - [Upbit](https://upbit.com/exchange?code=CRIX.UPBIT.BTC-DAI): South Korea - [Yobit](https://yobit.net/en/trade/DAI/USD): Russia #### Crypto | Fiat - On/Off Ramps - [Buenbit](https://www.buenbit.com/): Argentina | Peru - [Easy Crypto](https://easycrypto.ai/): Australia | New Zealand | South Africa - [Elastum](https://elastum.io/): EU | Global - [Unsupported Countries and US States](https://elastum.zendesk.com/hc/en-us/articles/360021383471-Supported-countries) - [Orionx](https://www.orionx.com): Mexico | Chile - [PayTrie](https://paytrie.com): Canada - [Ramp](https://instant.ramp.network/): UK | EU - [Ripio](https://www.ripio.com/en/): Argentina | Brazil | Mexico - [Wyre](https://sendwyre.com): USA | EU | UK | Australia - [Geographic Restrictions List](https://support.sendwyre.com/en/articles/1863574-geographic-restrictions) - [Supported Currency Pairs](https://support.sendwyre.com/en/articles/3231576-supported-currencies-pairs) - [US License List](https://www.sendwyre.com/licenses/) ### Watch Dai #### Monitor Vaults - [CDP Simulator](https://cdp-simulator.surge.sh/): Metamask Required - [CDP Simulator](https://cdpsimulator.netlify.com/): Metamask Not Required - [DeFi Explore](https://defiexplore.com/): Find info on Maker Vaults - [EthView](https://ethview.app): View CDP and DeFi Statistics of an Ethereum Address - [Makerscan](https://makerscan.io/): MakerDAO System Explorer - [Stability Fee Notifications](https://makerstabilityfee.com/): Email List for Stability Fee Changes #### Analytics and Metrics - [Catflip](https://catflip.co/): Provides current and historical Maker's system parameters - [Daiembassy](https://www.daiembassy.online/): MakerDAO System Explorer - [Dai-in-Defi](https://dai-in-defi.com/): Supply and Demand Dashboard for Maker Dai - [DaiPeg](https://daipeg.com/): Dai USD Price Tracker - [Defi Score](https://app.defiscore.io/assets/dai): Compare DeFi lending by asset - [Dai.stablecoin.science](https://dai.stablecoin.science/): Dai USD Price Tracker - [DaiStats](https://daistats.com/): Dai Statistics - [DeFi.ai](https://defi.ai/dai): Provides Coinbase and Radar pricing data, showing where Dai trades in comparison to its $1 soft peg. - [DeFiTracker](https://defitracker.io/): Track Dai Across DeFi Protocols - [Dsr.fyi](https://dsr.fyi/): Check your DSR Dai balance - [Maker Auctions](https://maker-auctions.io/): Track Maker auctions - [MakerDaiBot](https://twitter.com/MakerDaiBot): Twitterbot - [MakerVaults.descipher.io](http://makervaults.descipher.io/): Analytics Dashboard - [MCD Collateral Auctions](https://daiauctions.com/): View the Collateral Auction process - [MCD State](http://mcdstate.info/): Data on individual Vaults <!-- Internal Server Error, asked tomasz if defunct. Site was crawled by google 4 days prior to testing --> - [Mkr.tools](https://mkr.tools): MakerDAO System Explorer and Informational Statistics - [Nomics: Dai](https://nomics.com/assets/dai-dai#statistics): Dai Statistics with an API Aggregator - [Santiment](https://graphs.santiment.net/makerdao): Maker Analytics - [Vishesh's Graphs](https://makerdao.descipher.io/): Data Representations - [VWAP Breakdown](http://dai.descipher.io/): Dai Price Tracker #### Stablecoin Comparisons - [DAppTotal](https://dapptotal.com/defi): DeFi Protocol Rankings - [DeFiPrime](https://defiprime.com/defi-rates): Compre DeFi Lending Rates to the Traditional Financial System - [DeFiPulse](https://defipulse.com/): DeFi Protocol Rankings and Analytics - [Loanscan](https://loanscan.io/): Analytics for Debt Issued on the Ethereum Blockchain - [TokenAnalyst: Stablecoins](https://www.tokenanalyst.io/stablecoins): Stablecoin Comparisons ## Milestones | Achievements A chronological collection of MakerDAO's major milestones and achievements over the years compiled by Maker's community. ### 2020 - [SCD Shutdown]() | [tx](https://etherscan.io/tx/0xe2f04da54fd0550abfd0da24f5e422c4fa820242ff7979aacb26bea596f0d1be) *(May 2020)* - [MKR Token Authority transfer](https://blog.makerdao.com/the-transfer-of-mkr-token-control-to-governance-the-final-step/) *MakerDAO Blog Post (March 2020)* - [First Debt Auction]() *needs link (March 2020)* - [First Surplus Auction](https://twitter.com/KentonPrescott/status/1223792492790706176?s=20) | [tx](https://etherscan.io/tx/%20%20%20%20%20%20%20%20%20%200x3e12197892310b9b50fc6ea89b66009e5d7e1a9c74afcd0c1821cb021a44d8f4) *Kenton Prescott Tweet (February 2020)* - [MKR Token Authority Transferred](https://blog.makerdao.com/transfer-of-mkr-token-control-a-giant-leap-toward-system-decentralization/) | [tx](https://etherscan.io/tx/0x6c3e56c4b99b280dddbff4f087c25d89c054421a202503fd49c36c6683e48fa1) *MakerDAO Blog Post (January 2020)* - [MKR in the burner address was BURNED for the first time](https://twitter.com/nanexcool/status/1216824200914243584?s=20) | [tx](https://etherscan.io/tx/0xda5f9a9dfc33c73dd1582c894736cb97248255fffa59b39bda0acb65e5374f95) *Mariano's Tweet (January 2020)* ### 2019 - [The Maker Foundation Transfers Trademarks and Software IP to Independent Dai Foundation](https://blog.makerdao.com/the-maker-foundation-transfers-trademarks-and-software-ip-to-independent-dai-foundation/) *MakerDAO Blog Post (December 2019)* - [Dai supply surpasses Sai](https://twitter.com/LenklaH/status/1203974242813042689?s=20) *Lenka's Tweet (December 2019)* - [**Multi-Collateral Dai Launched**](https://twitter.com/androolloyd/status/1196458513243017217?s=20) | [TX](https://etherscan.io/tx/0xa418049bc3d4f8d34678fdefb5c5cab66ce8f3650cdb0d11f3f56bb145bdbc55) *Andrew Redden Twitter Post (November 2019)* - [Launch Parameters Amendment](https://vote.makerdao.com/polling-proposal/qmzws83rd8gfwzhnjnfiduve6bcm826cyqemgp7nmzv6p4) *Ratified Governance Poll (November 2019)* - [Migration Risk Construct Proposal](https://vote.makerdao.com/polling-proposal/qmba2hpv3kcbjgzvlnv7xsogs3jenqdiqo3ffnktgqtepn) *Ratified Governance Poll (November 2019)* - [DeFi Public Feed Proposal](https://vote.makerdao.com/polling-proposal/qmpem83sxjjwe1jvn2csdtetn4r3j95ejuzpbmtxef4lu5) *Ratified Governance Poll (October 2019)* - [Responsible Oracle Migration Proposal](https://vote.makerdao.com/polling-proposal/qmtg1vnui79st2cvnth3rhh1bjkgi1qttftnk1yt9nwqdx) *Ratified Governance Poll (October 2019)* - [Oracles Incentives Restructuring](https://vote.makerdao.com/polling-proposal/qmwzwvfdi8qtjh8dkggjpqxysu3qjg2gegpuar2nh7ucer) *Ratified Governance Poll (October 2019)* - [Interim Oracle Team Mandate](https://vote.makerdao.com/polling-proposal/qmas1bqrquo2h41qv4fa8hpek9ukb7dlwtpkpn62r5hhmq) *Ratified Governance Poll (October 2019)* - [Interim Risk Team Mandate](https://vote.makerdao.com/polling-proposal/qmpvhtcjxpm6wxs1cnq4bjc31d5egbyyd2k4ejotbtmhmt) *Ratified Governance Poll (September 2019)* - [Interim Governance Facilitator Mandate](https://vote.makerdao.com/polling-proposal/qmvh4z3l5ymqgtfs6tifq3jpjx5mxgdfnjy6alewnwwvba) *Ratified Governance Poll (September 2019)* - [Collateral Asset Priority Polls](https://blog.makerdao.com/multi-collateral-dai-collateral-types/) | [Results](https://forum.makerdao.com/t/results-collateral-asset-priority-poll-august-19-2019/278) *Ratified Governance Polls (August 2019)* - [MCD Public Bug Bounty is Announced](https://blog.makerdao.com/mcd-bug-bounty-announcement-and-security-roadmap-update/) *MakerDAO Blog Post (July 2019)* - [Critical Update to Governance Voting Contract](https://www.reddit.com/r/MakerDAO/comments/bmlgdm/notice_update_to_governance_voting_contract/) *Reddit Post by Richard Brown (May 2019)* - [Oasis Contract Upgrade](https://www.reddit.com/r/MakerDAO/comments/aoimcy/announcement_the_oasis_team_is_performing_an/) | [Postmortem Update](https://blog.makerdao.com/postmortem-oasis-contract-upgrade/) *Reddit (February 2019) | MakerDAO Blog (March 2019)* - [Updated SCD WhitePaper](https://www.reddit.com/r/MakerDAO/comments/ascw7p/check_out_the_updated_whitepaper/) *Reddit Post by Rune Christensen (February 2019)* - [2,000,000 ETH Locked in the CDP Engine](https://twitter.com/nanexcool/status/1090833187918528517) *Tweet by Mariano Conti (January 2019)* ### 2018 - [Happy BirthDAI: One Year Since Dai's Launch](https://blog.makerdao.com/happy-birthdai/) *Blog Post by MakerDAO (December 2018)* - [1,000,000 ETH Locked in the CDP Engine](https://twitter.com/mikeraymcdonald/status/1062384077280632833) *Tweet Post by Mike McDonald (November 2018)* - [Introducing the New CDP Portal for Single Collateral Dai](https://blog.makerdao.com/introducing-the-new-cdp-portal-for-single-collateral-dai/) *Blog Post by MakerDAO (October 2018)* - [Announcing the MakerDAO Core Community Development Initiative](https://web.archive.org/web/20190518020147/https://medium.com/makerdao/announcing-the-makerdao-core-community-development-initiative-d388bfba88e3) *Medium Post by MakerDAO (October 2018)* <!-- This article exists in the wayback machine, but the link only works a few times --> - [The Maker Foundation Proposal](https://vote.makerdao.com/polling-proposal/pollfoundationproposal) *Ratified Governance Poll (September 2018)* - [Introducing the Governance Voting UI for the Maker Foundational Vote](https://blog.makerdao.com/introducing-the-governance-voting-ui-for-the-maker-foundational-vote/) *Blog Post by MakerDAO (September 2018)* - [Multi-Collateral Dai Code Open for Review](https://blog.makerdao.com/part-1-why-stablecoins-matter/) *Blog Post by MakerDAO (September 2018)* - [Dai Savings Rate Announced](https://blog.makerdao.com/dai-savings-rate/) *Blog Post by MakerDAO (August 2018)* - [Debt Ceiling Raised to $100MM USD](https://blog.makerdao.com/we-raised-the-roof/) *Blog Post by MakerDAO (July 2018)* ### 2017 - [Sai V1 Globally Settled](https://www.reddit.com/r/MakerDAO/comments/7lhbmx/psa_sai_now_globally_settled/) *Reddit Post by MakerDAO (December 2017)* - [Dai V1 Launched](https://blog.makerdao.com/dai-is-now-live/) *Blog Post by MakerDAO (December 2017)* - [Dai V1 Audited](https://blog.makerdao.com/single-collateral-dai-source-code-and-security-reviews/) *Blog Post by MakerDAO (December 2017)* - [Introducing Sai](https://web.archive.org/web/20170606025602/https://blog.makerdao.com/2017/06/05/introducing-sai/) *MakerDAO Blog Post by Andy Milenius (June 2017)* - [Establishment of the Dai Foundation](https://web.archive.org/web/20170603093744/https://blog.makerdao.com/2017/02/19/establishment-of-the-dai-foundation/) *MakerDAO Blog Post by Rune Christensen (February 2017)* ### 2016 - [2017 Product Roadmap](https://web.archive.org/web/20170608025915/https://blog.makerdao.com/2016/12/02/2017-product-roadmap/) *MakerDAO Blog Post by Andy Milenius (December 2016)* ## Media Coverage ### Interviews #### 2019 | Video Interviews - [CoinDesk at DevCon 5: MakerDAO’s Multi-Collateral Dai Token with Rune Christensen](https://www.youtube.com/watch?v=kAshxmsC4F4) *Video Interview by CoinDesk (October 2019)* - [Introducing Dai Stablecoin: Interview with Rune Christensen](https://www.youtube.com/watch?v=BhQg7fnAplQ) *Video Interview by BROD (July 2019)* - [Rune Christiansen, Co-Founder & CEO of MakerDAO, Talks Future of Blockchain](https://www.youtube.com/watch?v=huSerGBTdYA) *Video Interview by Underscore VC (April 2019)* - [Whiteboard Series with NEAR | Ep: 10 David Utrobin from MakerDAO](https://www.youtube.com/watch?time_continue=58&v=lhPdUDy1z1s) *Video Interview by NEAR Protocol (March 2019)* #### 2019 | Transcribed Interviews - [The Next 10 Years for MakerDao: A Conversation with Rune Christensen](https://medium.com/the-spartan-group/the-next-10-years-for-makerdao-a-conversation-with-rune-christensen-fe93e35e4960) *Interview by Jason Choi (November 2019)* - [Towards a Second-Generation Tokenization: Interview with Rune Chistensen](https://thetokenizer.io/2019/02/18/towards-a-second-generation-tokenization/) *Interview by The Tokenizer (February 2019)* - [A Conversation with MakerDAO’s “Head of Oracles” - Mariano Conti](https://medium.com/witnet/a-conversation-with-makerdaos-head-of-oracles-mariano-conti-9e5ea454a9b9) *Interview by James Ryan Moreau (January 2019)* #### 2018 | Video Interviews - [MakerDAO President Steven Becker on the Boom in 'Stablecoins'](https://cheddar.com/videos/makerdao-president-on-the-boom-in-stablecoins) *Video Interview by Cheddar (November 2018)* - [Niklas Of MakerDAO: Synthetic Tokens, Earning Interest On Dai, What's Next](https://www.youtube.com/watch?feature=youtu.be&v=l4BrsUZ_VwE&app=desktop) *Video Interview by Crypt0's News (November 2018)* - [MakerDAO Chat with Greg Diprisco](https://youtu.be/QAbrgEtdtKY) *Video Interview by Ethex CEO Dan Walton (August 2018)* - [A Better Stable Coin Than Tether? Interview with Rune Christensen](https://www.youtube.com/watch?v=BW8DkIKXpdQ) *Video Interview by Colin Andrews (June 2018)* - [Andy Milenius of MakerDAO Talks To ChronoLogic about Scheduling Transactions](https://www.youtube.com/watch?v=RhWD8GbePV0) *Video Interview by ChronoLogic (May 2018)* - [MakerDAO Interview with Matt Richards](https://youtu.be/gIp10mX6cbs) *Video Interview by BQLQ (April 2018)* #### 2018 | Transcribed Interviews - [MakerDAO: The Backbone of the Future Economy? Interview with Rune Christensen](https://www.coinisseur.com/makerdao-the-backbone-of-the-future-economy/) *Interview by Coinisseur (November 2018)* - [CCN Interview: MakerDAO CEO Rune Christensen Talks Stablecoins](https://www.ccn.com/interview-makerdao-ceo-rune-christensen-talks-stablecoins/) *Interview by Jake Sylvestre (August 2018)* - [We're Rune Christensen (MakerDAO) and Michael Dunworth (Wyre). We just announced a great partnership. (AMA|AUA)](https://www.reddit.com/r/ethtrader/comments/97ue60/were_rune_christensen_ceo_makerdao_and_michael/) *Reddit AMA with Rune Christensen and Michael Dunworth (August 2018)* #### 2017 | Video Interviews - [MakerDAO Interview with Rune Christensen](https://youtu.be/MTiINrPpXDw) *Video Interview by Nugget's News (November 2017)* #### 2016 | Transcribed Interviews - [Bitcoinist Interview with Rune Christensen](https://bitcoinist.com/makerdao-founder-claims-absolutely-zero-obligation-dao-investors-interview/) *Interview by Tyson O'Ham (July 2016)* ### Podcasts #### 2020 | Broadcasts - [The Block Experience: Alex Van de Sande – The MakerDAO Situation & The Ethereum Foundation](https://thedailychain.com/the-block-experience-alex-van-de-sande-the-makerdao-situation-the-ethereum-foundation/) *The Block Experience Podcast (April 2020)* - [The Defiant: MakerDAO Founder Rune Christensen on DeFi’s Biggest Test Yet](https://anchor.fm/camila-russo/episodes/MakerDAO-Founder-Rune-Christensen-On-DeFis-Biggest-Test-Yet-ecgj0b) *The Defiant Podcast (April 2020)* - [OKCoin Let’s Chat: Dai’s Secret Sauce Is Decentralization with Greg Diprisco](https://blog.okcoin.com/2020/04/01/ok-lets-chat%e2%80%8a-%e2%80%8adais-secret-sauceis-decentralization/) *OKCoin Let’s Chat Podcast (April 2020)* - [Ethereal Podcast: Episode 1 - Why MakerDAO's Head of Smart Contracts Dogfoods DAI](https://www.etherealsummit.com/news/ethereal-podcast-episode-1-mariano-conti) *Ethereal Podcast (March 2020)* #### 2019 | Broadcasts - [The Blockchain VC podcast with Tomer Federman: Ep. 9: Rune Christensen, Co-Founder and CEO, MakerDAO](https://youtu.be/tC3GH9chmXY) *The Blockchain VC podcast (December 2019)* - [Base Layer Episode 081: Mariano Conti on Dai and Living in Argentina](https://acrabaselayer.podbean.com/e/base-layer-episode-081-mariano-conti-maker-foundation/) *Base Layer (November 2019)* - [Maker DAO: The Central Bank of Web 3.0 w/ Rune Christensen (Episode 298)](https://epicenter.tv/episode/298/) *Epicenter (July 2019)* - [POV Crypto #058: The Frontier of Dai with Mariano Conti](https://medium.com/@TrustlessState/58-the-frontier-of-dai-with-mariano-conti-8e532cdc48a4) *David Hoffman (June 2019)* - [Hashing It Out #47: MakerDAO – Nik Kunkel](https://thebitcoinpodcast.com/hashing-it-out-47/) *The Bitcoin Podcast (May 2019)* - [Software Engineering Daily: Stablecoins with Rune Christensen](https://softwareengineeringdaily.com/2019/04/03/stablecoins-with-rune-christensen/) *SE Daily (April 2019)* - [Digging into Dai with Rune Christensen from Maker (Episode 70)](https://www.zeroknowledge.fm/70) *Zero Knowledge FM (March 2019)* - [Maker: Establishing Stability in Crypto with Rune Christensen (Episode 579)](https://ethhub.substack.com/p/maker-establishing-stability-in-crypto-579) *Into The Ether (March 2019)* - [POV Crypto #040: Bitcoin vs. MakerDAO II](https://medium.com/@TrustlessState/pov-crypto-episode-40-bitcoin-vs-makerdao-ii-d71cce4f19b8) *David Hoffman (March 2019)* - [Blockchain Meditations #01: Stablecoins and what’s next for MakerDAO with Ashleigh Schap](https://limechain.tech/stable-coins-and-whats-next-for-makerdao/?) *Lime Chain Blog (March 2019)* - [How Maker Became Ethereum's Biggest Project with Rune Christensen (Episode 47)](https://blockcrunch.libsyn.com/how-maker-became-ethereums-biggest-project-rune-christensen-founder-makerdao) *BlockCrunch (February 2019)* - [Unchained: Rune Christensen of MakerDAO Part 2: How Dai Stayed at $1 While ETH Crashed From $1,400 to \$85 - Ep. 105](https://overcast.fm/+LNqexSQnI) *Unchained Podcast (February 2019)* - [Unchained: Rune Christensen of MakerDAO Part 1: How to Keep a Crypto-Collateralized Stablecoin Afloat - Ep. 104](https://overcast.fm/+LNqfe3mfk) *Unchained Podcast (January 2019)* - [Wyre Talks Ep. 19: MakerDAO, Novel Paradigms for Risk Management with Steven Becker](https://simplecast.com/s/e32e5290) *Wyre (January 2019)* #### 2018 | Broadcasts - [a16z Podcast Ep. 420: All About Stablecoins with Andy Milenius, Jesse Walden, and Sonal Chokshi](https://a16z.com/2018/12/20/stablecoins-why-matter-what-how-daos-maker/) *a16z Podcast (December 2018)* - [POV Crypto Special Edition: The Role of Ether in Multi-Collateral Dai with David Utrobin](https://medium.com/@TrustlessState/pov-crypto-special-edition-the-role-of-ether-in-multi-collateral-dai-dd90fd15adfc) *David Hoffman (December 2018)* - [POV Crypto  #014: Bitcoin vs. MakerDAO](https://medium.com/pov-crypto/pov-crypto-episode-14-bitcoin-vs-makerdao-2d5689f3fbb1) *David Hoffman (December 2018)* - [BoostVC S3 EP31: Solving for Volatility in Crypto with a Decentralized Stablecoin with Steven Becker](https://www.breaker.audio/the-boost-vc-podcast/e/39268463) *The Boost VC Podcast (October 2018)* - [MakerDAO Founder and CEO Rune Christensen: Why Dai Will Displace Stablecoin Tethers (Episode 5)](https://fiftyonepercent.podbean.com/e/episode-5-makerdao-founder-and-ceo-rune-christensen/) *51 Percent (October 2018)* - [Rune Christensen of MakerDAO on \$15 Million from Andreessen Horowitz - Ep. 039](https://unconfirmed.libsyn.com/rune-christensen-of-makerdao-on-its-15-million-from-andreessen-horowitz-ep039) *Unconfirmed Podcast (September 2018)* - [101 Series: Stablecoins](https://www.cryptobasicpodcast.com/home/stablecoins) *Crypto Basic Podcast (September 2018)* - [BlockZero #006 - MakerDAO & The Dai Stable Coin: Founder Rune Christensen](https://blockzero.simplecast.com/episodes/006-makerdao-the-dai-stable-coin-founder-08860ac9) *Block Zero (February 2018)* - [Vitalik Buterin on Cryptoeconomics and Markets in Everything](https://soundcloud.com/conversationswithtyler/vitalik-buterin-tyler-cowen-cryptoeconomics) *Conversations with Tyler Cowen (July 2018)* - [Unchained: Why It's so Hard to Keep Stablecoins Stable with Rune Christensen](https://soundcloud.com/unchainedpodcast/why-its-so-hard-to-keep) *Unchained Podcast (February 2018)* #### 2017 | Broadcasts - [This Week in Crypto #3: MakerDAO Project CEO Rune Christensen](https://soundcloud.com/ccnpodcast/3-this-week-in-crypto-coinbase) *CCN Podcast (July 2017)* - [BlockChannel Episode 7: Meet Your Maker, Ethereum: Andy Milenius & Kenny Rowe](https://soundcloud.com/blockchannelshow/episode-7-meet-your-maker-ethereum) *Block Channel (February 2017)* #### 2016 | Broadcasts - [Rune Christensen: MakerDAO Ethereum's Decentralized Central Bank (Episode 124)](https://soundcloud.com/epicenterbitcoin/eb-124) *Epicenter (March 2016)* ### Videos #### 2019 | Videos - [What's Next for DeFi?](https://slideslive.com/38920014/whats-next-for-defi) *Presentation by Rune Christensen (October 2019)* - [OasisDEX: Past, Present, Future and it's Role in the DeFi Ecosystem](https://youtu.be/mwkL7beq0m8) *Presentation by Bartek Kiepuszewski (September 2019)* - [Demand Generation for Dai and Synthetic Assets](https://www.youtube.com/watch?v=LcakWfUBa20) *Meetup Presentation by Niklas Kunkel at Meterup DeFi (August 2019)* - ["Beyond Banks" by Gregory Di Prisco, MakerDAO](https://www.youtube.com/watch?v=9lKg6nlyc14) *Presentation by Gregory Di Prisco at Fluidity (May 2019)* - [Michael Elliot Blockchain Engineer at MakerDAO: CDP Portal State Management](https://youtu.be/p0y-NafGshM) *Presentation by Michael Elliot at EDCON (May 2019)* - [Ashleigh Schap: Biz Dev & Crypto: Breaking Out of the Bubble MakerDAO](https://www.youtube.com/watch?v=gdfIVD7pgdI&feature=youtu.be) *Presentation by Ashleigh Schap at ETH Denver (February 2019)* - [Mariano Conti: CDPs and MCD: A Look Back with Maker Panel](https://www.youtube.com/watch?v=rY_jcyqjubs) *Presentation by Mariano Conti at ETH Denver (February 2019)* - [Mariano Conti: CDPs and MCD: A Look Back with Maker](https://www.youtube.com/watch?v=R5vA7u9WFfU) *Presentation by Mariano Conti at ETH Denver (February 2019)* #### 2018 | Videos - [Fall 2018 Summit: The Great Stablecoin Debate with Reserve, USDC, and MakerDAO](https://www.youtube.com/watch?v=WAiuZuQg3kg) *Debate Hosted by Multicoin Capital (December 2018)* - [Stable Coins: a Volatility Cure-All?](https://www.youtube.com/watch?v=RnmWcgKbiQ8) *Crypto Summit Discussion by Bloomberg Live (December 2018)* - [MakerDAO: A New Hope for Financial Reform](https://slideslive.com/38911619/makerdao-a-new-hope-for-financial-reform) *Presentation by Andy Milenius at Devcon 4 (November 2018)* - [MakerDAO: Challenges of Asset Backed Stablecoins](https://www.youtube.com/watch?v=JLRDIKG59Mg&t=49s) *Presentation by Niklas and Rune at DeFi Summit Prague (November 2018)* - [Mariano Conti: Price Oracles + Signed Messages On & Off-Chain](https://view.ly/v/Rt275OYzLCI1) *Presentation by Mariano Conti at ETH Berlin (September 2018)* - [What I Learned by Getting a Loan From a Robot (Ethereum, MakerDAO, Stablecoins)](https://youtube.com/watch?v=wwHqPjg8P9s&) *Video by Blockhead Media (September 2018)* - [Maker: What’s to Come](https://www.youtube.com/watch?v=cNMaz3Q4S5U) *Presentation by Matt Richard at DappCon Berlin (July 2018)* - [MakerDAO and Dai Stablecoin](https://youtu.be/rFVVApu_hYY) *Meetup Presentation by Chao Pan at Ethereum Shanghai (March 2018)* - [What is MakerDAO? with Rune Christensen](https://www.youtube.com/watch?v=yvfvVlxL-Lw) *Meetup Presentation by Rune Christensen at NYC Ethereum (February 2018)* - [Mena Summit 2018 Panel: Navigating Investments from Cryptocurrencies to Blockchain (Charles Noyes Mentions MakerDAO)](https://www.youtube.com/watch?time_continue=718&v=lp5Yx34SO58) *Discussion by Milken Institue (February 2018)* - [The Psychology Of "Doing Nothing" in Crypto - Weiss Ratings, Korean Exchange, StableCoins - Ep 130](https://youtu.be/ZxoWlzmh0VE?t=11m4s) *Video by Coin Mastery (January 2018)* - [Tether 2.0 – A Look at Dai and Maker Coins](https://youtu.be/DAz6RtkoTM4?t=14m36s) *Video by CryptosRUs (January 2018)* - [Introduction to Dai](https://www.youtube.com/watch?v=vJurxzk1Z6Q&feature=youtu.be) *Presentation by Andy Milenius at The World Crypto Economic Forum (January 2018)* #### 2017 | Videos - [Stability Mechanics of the Dai Stablecoin System](https://vimeo.com/247715549) *Animated Short by MakerDAO (December 2017)* - [Dai Stablecoin Presentation with Andy Milenius](https://www.youtube.com/watch?v=L1erp9Gkesk&feature=youtu.be) *Presentation by Andy Milenius at Devcon 3 (November 2017)* - [Stablecoins with MakerDAO: Formal Verification Research with Denis Erfurt and Others](https://youtu.be/49S2_FJtJko) *Meetup Presentation by Ethereum Madrid at Private Key Berlin (October 2017)* ### Speculation #### 2019 | Speculation - [Maker (MKR) Valuation Fundamentals :  The Case for Trillion Dollar Maker](https://medium.com/@Rewkang/maker-mkr-valuation-fundamentals-the-case-for-trillion-dollar-maker-9b6e3f0150f1) *Medium Post by Andrew Kang (March 2019)* - [Cryptoasset Research: Maker (MKR)](https://cryptocurrencyhub.io/cryptoasset-research-maker-mkr-a0e89fccb985) *Medium Post by Jack Purdy (February 2019)* - [A MakerDAO Case Study](https://medium.com/@visionhill_/a-makerdao-case-study-47a31d858be5) *Medium Post by Vision Hill Advisors (February 2019)* #### 2018 | Speculation - [Investment Analysis: MakerDAO](https://medium.com/@blockspace.info/investment-analysis-makerdao-e58245d07c2f) *Medium Post by Aviv Milner and Victor Hogrefe (May 2018)* - [Thoughts on how the amount of Dai issued affects the valuation of MKR](https://www.reddit.com/r/MakerDAO/comments/86p081/maker_token_valuation/) *Reddit Post by u/davidutro (March 2018)* ### Criticism #### 2019 | Criticism - [(In)Stability for the Blockchain: Deleveraging Spirals and Stablecoin Attacks](https://arxiv.org/abs/1906.02152) *Academic Paper by Ariah Klages-Mundt and Andreea Minca (June 2019)* - [“Mad King” Rune Christensen Tries to Burn Down MakerDAO](https://coinjazeera.news/mad-king-rune-christensen-tries-to-burn-down-makerdao/) *Satire by Coin Jazeera (May 2019)* - [Revisiting Stablecoins](https://jpkoning.blogspot.com/2019/05/revisiting-stablecoins.html) *Blog Post by JP Koning (May 2019)* - [The $1.00 Stablecoin Worth $0.98](https://medium.com/@GrapefruitTrading/the-1-00-stablecoin-worth-0-98-2699046c5266) *Medium Post by Grapefruit Trading (April 2019)* - [Maker Dai: Stable, But Not Scalable: A Lesson in Stablecoin Arbitrage](https://medium.com/@hasufly/maker-dai-stable-but-not-scalable-3107ba730484?sk=bc7d016d8f47ff68a951beee75ccf0c6) | [Reddit Thread](https://www.reddit.com/r/MakerDAO/comments/adp7ur/maker_dai_stable_but_not_scalable_medium_article/) *Medium Post by Hasu (January 2019)* #### 2018 | Criticism - [Cryptoasset Collateral Concerns](https://blog.havven.io/cryptoasset-collateral-concerns-25e2c2d74f30?_branch_match_id=565372563598051656) *Medium Post by Kain Warwick (October 2018)* - [Reserve’s Analysis of the MakerDAO Protocol](https://hackernoon.com/reserves-analysis-of-the-makerdao-protocol-697141a8bbae) *Hakernoon Post by Nevin Freeman (August 2018)* - [Can the Powers That Be Shut Down MakerDAO and Dai?](https://www.reddit.com/r/MakerDAO/comments/8e5cnv/can_the_powers_at_be_shut_down_makerdao_and_dai/dxsswx6/) *Reddit Post by u/18idlwk1920dc (April 2018)* - [Why Should We Trust the MakerDAO Oracle System?](https://www.reddit.com/r/MakerDAO/comments/7zitlv/why_should_we_trust_the_makerdao_oracle_system/dup6j2t/) *Reddit Post by u/griggah (February 2018)* - [4 Questions to Dai and the Future of Stable Cryptocurrency](https://bootstrapping.dk/4-questions-to-dai-and-the-future-of-stable-cryptocurrency/) *Article by Esben Vest (January 2018)* - [MakerDAO and the Dai](https://blog.havven.io/makerdao-and-the-dai-f21a4d5571a1) *Medium Post by Michael Spain (January 2018)* ### Dai and MakerDAO Mentions #### 2019 | Mentions - [It’s 2019. Where the f\*ck is Our Global Peer-to-Peer Electronic Cash System?](https://hackernoon.com/where-the-f-ck-is-our-peer-to-peer-electronic-cash-system-c8f43f5ad8b0) *Hackernoon Post by Tom Howard (April 2019)* - [Introducing DIPOR: LIBOR for Open Finance](https://www.theblockcrypto.com/genesis/19324/introducing-dipor-libor-for-open-finance) *Article by Matteo Leibowitz (April 2019)* - [The 100+ Projects Pioneering Decentralized Finance](https://media.consensys.net/the-100-projects-pioneering-decentralized-finance-717478ddcdf2) *Medium Post by Consensys (March 2019)* - [Formal Verification, Virtual Hardware, and Engineering for Blockchains](https://medium.com/balance-io/formal-verification-virtual-hardware-and-engineering-for-blockchains-51d07abdc934) *Medium Post by Richard Burton (March 2019)* - [The Year of the DAO Comeback: Ustanding What’s Leading the Charge](https://medium.com/amentum/the-year-of-the-dao-comeback-9c888b44980) *Medium Post by Steven McKie (March 2019)* - [Open Finance: Loan Origination Snapshot for January and February 2019](https://medium.com/bloqboard/open-finance-loan-origination-snapshot-for-january-and-february-2019-5562ab811286) *Medium Post by Bloqboard (March 2019)* - [How to Loan Yourself Money with MakerDAO](https://decryptmedia.com/5344/be-your-own-bank-with-makerdao) *Decrypt Post by Ben Munster (February 2019)* - [An Elegant Relationship (DAI, ETH, MKR)](https://medium.com/@cyrus.younessi/an-elegant-relationship-dai-eth-mkr-4e4d5e69590) *Medium Post by Cyrus Younessi (January 2019)* - [Stablecoins: Strengths & Weaknesses](https://blog.makerdao.com/stablecoins-strengths-weaknesses/) *MakerDAO Blog Post by Brian D. Colwell (January 2019)* - [Maker Investment Thesis](https://www.placeholder.vc/blog/2019/1/23/maker-investment-thesis) *Placeholder VC Post by Chris Burniske and Joel Monegro (January 2019)* - [Lender of First Resort](https://blog.makerdao.com/lender-of-first-resort/) *MakerDAO Blog Post by ProgrammableTX (January 2019)* - [Daimonds in the Soles of Her Shoes](https://medium.com/@cryptowanderer/daimonds-in-the-soles-of-her-shoes-9c6a7c51c62d) *Medium Post by Andy Tudhope (January 2019)* #### 2018 | Mentions - [Exploring the Emerging Crypto Debt Markets](https://maxbronstein.com/exploring-emerging-crypto-debt-markets/) *Blog Post by Max Bronstein (December 2018)* - [MakerDAO: The Decentralized Global Reserve Bank](https://medium.com/pov-crypto/makerdao-the-decentralized-global-reserve-bank-98e174a53369) *Medium Post by David Hoffman (December 2018)* - [The Rise of Decentralized Finance](https://www.trustnodes.com/2018/12/10/the-rise-of-decentralized-finance) *Article by Trustnodes (December 2018)* - [Stablecoins: Collateralization Types](https://blog.makerdao.com/stablecoins-collateralization-types/) *MakerDAO Blog Post by Brian D. Colwell (December 2018)* - [Stablecoins: Use Cases](https://blog.makerdao.com/stablecoins-use-cases/) *MakerDAO Blog Post by Brian D. Colwell (December 2018)* - [DAI Moved Nearly \$200 Million Worth of Decentralized Tokenized Dollars](https://www.trustnodes.com/2018/11/21/dai-moved-nearly-200-million-worth-of-decentralized-tokenized-dollars) *Article by Trustnodes (November 2018)* - [Twelve Reasons I’m Bullish About Ethereum Today](https://medium.com/crypto-nyc/twelve-reasons-im-bullish-about-ethereum-today-809a234312b2) *Medium Post by Lane Rettig (September 2018)* - [Ethereum Projects Start Using DAI as a Bank](https://www.trustnodes.com/2018/09/17/ethereum-projects-start-using-dai-as-a-bank) *Article by Trustnodes (September 2018)* - [MakerDAO - Shitcoin Review](http://doiownashitcoin.com/blog/post/MakerDAO-Shitcoin-Review/) *Do I Own A Shitcoin? Blog Post by Mike and Aaron (September 2018)* - [DAI (MakerDAO) is Ethereum’s Crown Jewel](https://funnyking.io/archives/1630?lang=en) *Funnyking Post by Paolo Rebuffo (August 2018)* - [Amid Chaos, Dai Stays Stable](https://www.trustnodes.com/2018/08/15/amid-chaos-dai-stays-stable) *Article by Trustnodes (August 2018)* - [How Does MakerDAO’s Proposed 20% Charitable Giving Principle Make Sense?](https://medium.com/@davidutrobin/how-does-makerdaos-20-charitable-giving-principle-make-sense-79ded5455e41) *Medium Post by David Utrobin (July 2018)* - [Is It Time For Crypto Exchanges to Replace the Dollar?](https://www.trustnodes.com/2018/04/11/time-crypto-exchanges-replace-dollar) *Article by Trustnodes (April 2018)* - [Dai CDP User Stories](https://web.archive.org/web/20191019044531/https://medium.com/makerdao/dai-cdp-user-stories-36735f095fda) *Medium Post by MakerDAO (February 2018)* - [MakerDAO and More: The Quest for a Stable Stablecoin Continues](https://www.coindesk.com/makerdao-quest-stable-stablecoin-continues/) *Coindesk Article by Rachel Rose O'Leary (January 2018)* #### 2017 | Mentions - [Keepers — Workers that Maintain Blockchain Networks](https://medium.com/@rzurrer/keepers-workers-that-maintain-blockchain-networks-a40182615b66) *Medium Post by Ryan Zurrer of Polychain Capital (August 2017)* ## Audits | Security ### Multi-Collateral Dai - [PeckShield: MCD Smart Contract Audit Report](https://github.com/makerdao/mcd-security/blob/master/Audit%20Reports/PeckShield_Final_Audit_Report.pdf) *Audit by PeckShield (October 2019)* - [Trail of Bits: MCD Core Smart Contracts Security Assessment](https://github.com/makerdao/mcd-security/blob/master/Audit%20Reports/TOB_MakerDAO_Final_Report.pdf) *Analysis by Trail of Bits (August 2019)* - [Trail of Bits: DAI Security Assessment](https://github.com/makerdao/audits/blob/master/mcd/trail-of-bits.pdf) *Analysis by Trail of Bits (March 2018)* ### Single-Collateral Dai - [SAI Contract Audit](https://github.com/bokkypoobah/MakerDAOSaiContractAudit/tree/8dbefb06826c01082ff2fb9c368d30c0336733a1) *Analysis by Bok Consulting (July 2018)* - [SAI Code Review](https://github.com/makerdao/audits/blob/master/scd/white-hat-group.pdf) *Analysis by Whitehat Group (December 2017)* - [Trail of Bits: SAI Security Assessment](https://github.com/makerdao/audits/blob/master/scd/trail-of-bits.pdf) *Analysis by Trail of Bits (October 2017)* ### Dappsys - [Trail of Bits: DappHub Security Assessment](https://github.com/makerdao/audits/blob/master/dappsys/trail-of-bits.pdf) *Analysis by Trail of Bits (November 2017)* ## Developer Resources _Notice: Some Single-Collateral and Multi-Collateral Dai resources may overlap._ ### Github Orgs - [MakerDAO](https://github.com/makerdao) - [DappHub](https://github.com/dapphub) - [OasisDEX](https://github.com/OasisDEX) ### Documentation - [Maker Documentation Portal](https://docs.makerdao.com/) - [Dai.js JavaScript Library Documentation](https://github.com/makerdao/dai.js) - [Dapp.tools](https://dapp.tools/) - [Seth](https://github.com/makerdao/developerguides/blob/master/devtools/seth/seth-guide-01/seth-guide-01.md) - [Klab: Generating and Debugging K-Framework Reachability Proofs](https://github.com/dapphub/klab) - [Multicall](https://github.com/makerdao/multicall) - [Dappsys Library](https://dapp.tools/dappsys/) - [ds-token](https://dapp.tools/dappsys/ds-token.html) - [ds-auth](https://dapp.tools/dappsys/ds-auth.html) - [ds-value](https://dapp.tools/dappsys/ds-value.html) - [ds-math](https://dapp.tools/dappsys/ds-math.html) - [ds-note](https://dapp.tools/dappsys/ds-note.html) - [ds-proxy](https://dapp.tools/dappsys/ds-proxy.html) ### Guides and Tutorials - [Developer Guides](https://github.com/makerdao/developerguides) - [Introduction to Seth](https://github.com/makerdao/developerguides/blob/master/devtools/seth/seth-guide-01/seth-guide-01.md) - [Working with DSProxy](https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md) ### Single-Collateral Dai #### Contracts ##### Mainnet - [Dai Token Tracker](https://etherscan.io/token/0x89d24a6b4ccb1b6faa2625fe562bdd9a23260359) - [MKR Token Tracker](https://etherscan.io/token/0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2) - [Global Settlement Mechanism](https://etherscan.io/address/0x9b0ccf7c8994e19f39b2b4cf708e0a7df65fa8a3) - [CDP Engine](https://etherscan.io/address/0x448a5065aebb8e423f0896e6c5d525c040f59af3) - [CDP Liquidator](https://etherscan.io/address/0xbda109309f9fafa6dd6a9cb9f1df4085b27ee8ef) - [Chief Governance](https://etherscan.io/address/0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5) - [MKR Burner](https://etherscan.io/address/0x69076e44a9c70a67d5b79d95795aba299083c275) - [DSProxy Registry](https://etherscan.io/address/0x4678f0a6958e4d2bc4f1baf7bc52e8f3564f3fe4) ##### Kovan Testnet - [Dai Token Tracker](https://kovan.etherscan.io/token/0xc4375b7de8af5a38a93548eb8453a498222c4ff2) - [MKR Token Tracker](https://kovan.etherscan.io/token/0xaaf64bfcc32d0f15873a02163e7e500671a4ffcd) - [Global Settlement Mechanism](https://kovan.etherscan.io/address/0x5f00393547561da3030ebf30e52f5dc0d5d3362c) - [CDP Engine](https://kovan.etherscan.io/address/0xa71937147b55deb8a530c7229c442fd3f31b7db2) - [CDP Liquidator](https://kovan.etherscan.io/address/0xc936749d2d0139174ee0271bd28325074fdbc654) - [Chief Governance](https://kovan.etherscan.io/address/0x74d41fd874234d9bea31ff6b090ba1d0b9dc8785) - [MKR Burner](https://kovan.etherscan.io/address/0xbd747742b0f1f9791d3e6b85f8797a0cf4fbf10b) - [DSProxy Registry](https://kovan.etherscan.io/address/0x64a436ae831c1672ae81f674cab8b6775df3475c) #### Tools - [Testchain: Run SCD Contracts Locally](https://github.com/makerdao/testchain) - [Pymaker: Python API for Maker Contracts](https://github.com/makerdao/pymaker) - [Governance Dashboard](https://github.com/makerdao/governance-dashboard) - [SCD CDP Portal](https://github.com/makerdao/scd-cdp-portal) #### Documentation - [Dai Documentation](https://developer.makerdao.com/dai/1/) - [Dai Developer Documentation](https://github.com/makerdao/sai/blob/master/DEVELOPING.md) - [Dai Main Repo: All Contracts](https://github.com/makerdao/sai) - [Purple Paper: Reference Implementation (_Outdated_)](https://makerdao.com/purple/) #### Guides and Tutorials - [Developer Guides](https://github.com/makerdao/developerguides) - [Dai Token Guide](https://github.com/makerdao/developerguides/blob/master/dai/dai-token/dai-token.md) - [Using Dai in smart contracts](https://github.com/makerdao/developerguides/blob/master/dai/dai-in-smart-contracts/README.md) - [Keepers Guide](https://github.com/makerdao/developerguides/tree/master/keepers) - [Testchain Guide to deploy contracts locally](https://github.com/makerdao/developerguides/blob/master/devtools/test-chain-guide/test-chain-guide.md) - [How to setup DAI for local development](https://medium.com/@matthewblack/how-to-setup-dai-for-local-development-37bfba5212fc) - [Deep dive into MakerDAO Governance: A look at the code for governance in SCD](https://medium.com/@banteg/deep-dive-into-makerdao-governance-437c89493203) - [VoteProxy Setup Guide](https://github.com/makerdao/developerguides/blob/master/governance/vote-proxy-setup-airgapped-machine/vote-proxy-setup-airgapped-machine.md) - [Intro to Oasis Maker OTC Guide](https://github.com/makerdao/developerguides/blob/master/Oasis/intro-to-oasis/intro-to-oasis-maker-otc.md) - [Dai.js](https://github.com/makerdao/dai.js) - [Get Started with MakerDAO CDPs and Dai.js](https://medium.com/@rossbulat/get-started-with-makerdao-cdps-and-dai-js-447c8f5eb1fa) #### Data and APIs - [GraphQL API](https://developer.makerdao.com/dai/1/graphql/) - [Price Feed Documentation](https://developer.makerdao.com/feeds/) #### Examples - [Node-Dai](https://github.com/Kaisle/node-dai) - [CDP Liquidator Devpost](https://devpost.com/software/cdp-liquidator) - [CDP Saver](https://github.com/DecenterApps/cdpsaver-contracts) - [Dai Integration Examples](https://github.com/makerdao/integration-examples) - [Liquid Long CDP Management](https://help.keydonix.com/articles/37031-where-can-i-find-the-source-code) - [Shadowlands CDP Manager: 100% Python, TextUI Dapp platform for ethereum, built on Python3.5+, web3.py and asciimatics](https://github.com/kayagoban/shadowlands_cdp_manager) ### Multi-Collateral Dai #### Contracts - [Changelog](https://changelog.makerdao.com): Multi-Collateral DAI Public Releases #### Tools - [Testchain](https://github.com/makerdao/testchain): Run MCD Contracts Locally #### Documentation - [MCD Core CDP Engine Architecture](https://github.com/makerdao/dss/wiki) - [MCD System Variables](https://www.notion.so/MCD-System-c4df43ded9aa47f7b3770cb7ea6a79e7) - [K-DSS Formal Specification and Verification of Multi-Collateral Dai](https://github.com/dapphub/k-dss) #### Guides and Tutorials - [MCD 101](https://github.com/makerdao/developerguides/blob/master/mcd/mcd-101/mcd-101.md) - [Auction Keeper Bot Setup Guide](https://github.com/makerdao/developerguides/blob/master/keepers/auction-keeper-bot-setup-guide.md) - [Auctions and Keepers in Multi-Collateral Dai Explained](https://github.com/makerdao/developerguides/blob/master/keepers/auctions/auctions-101.md) - [Introduction on How to Use Maker's Custom Test Chain](https://github.com/makerdao/developerguides/blob/master/devtools/test-chain-guide/test-chain-guide.md) - [Intro to the Rate mechanism](https://github.com/makerdao/developerguides/blob/master/mcd/intro-rate-mechanism/intro-rate-mechanism.md) - [WIP: Multi Collateral Dai Developer Guide](https://github.com/makerdao/dss/blob/master/DEVELOPING.md) - [Upgrading to Multi-Collateral Dai](https://github.com/makerdao/developerguides/tree/master/mcd) ## Translated Resources #### Translated Beginner Guides - [中文 | Tutorial in Chinese: How to Use the Dai Platform](https://www.youtube.com/watch?v=HCMBf4Yq1ZA) *Video by Maker 说 (August 2018)* - [Elementarz MakerDAO: Primer on MakerDAO in Polish](https://medium.com/@reuptake/elementarz-makerdao-ee20a6b8a9f8) *Medium Post by Marcin Jagodziński (March 2019)* #### Translated FAQs - [SCD FAQs: Spanish](https://community-development.makerdao.com/makerdao-scd-faqs/es) - [SCD FAQs: French](https://community-development.makerdao.com/makerdao-scd-faqs/fr) - [SCD FAQs: Italian](https://community-development.makerdao.com/makerdao-scd-faqs/it) - [SCD FAQs: Japanese](https://community-development.makerdao.com/makerdao-scd-faqs/ja) - [SCD FAQs: Korean](https://community-development.makerdao.com/makerdao-scd-faqs/ko) - [SCD FAQs: Polish](https://community-development.makerdao.com/makerdao-scd-faqs/pl) - [SCD FAQs: Zhōngwén](https://community-development.makerdao.com/makerdao-scd-faqs/zh) #### Translated Videos - [MakerDAO 是什么?以太坊上的央行?| What is MakerDAO?](https://www.youtube.com/watch?v=-PJrpDO4JpY) *Video by Maker说 (August 2018)* - [MakerDAO ve DAI Nedir? | Kripto Para Yatırımı Yaptım (Oasis)](https://youtu.be/3b2-UrvNlPc) *Video by Bitcoin Kraliçesi(January 2020)* ## Archived Resources *Coming Soon...*
nataliebrooks_near-collect
README.md babel.config.js market-contract Cargo.toml README.md build.sh src events.rs external.rs internal.rs lib.rs nft_callbacks.rs order.rs order_flow.rs order_views.rs sale.rs sale_views.rs nft-contract Cargo.toml README.md build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs update.rs package.json src App.js components camera ReactCameraDivs.js shared utils.js config.js global.css index.html index.js neardev dev-account.env tests integration App-integration.test.js ui App-ui.test.js utils colors.js near.js piles.js roles.js subgraphs README.md generated schema.ts package.json src handlers item.ts order.ts tailwind.config.js
Collect ========== for the common good. [![Build Status](https://travis-ci.com/near-examples/guest-book.svg?branch=master)](https://travis-ci.com/near-examples/guest-book) [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/guest-book) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> Sign in with [NEAR] and add a message to the guest book! A starter app built with an [AssemblyScript] backend and a [React] frontend. Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install [yarn]: `npm install --global yarn` (or just `npm i -g yarn`) 2. Run the local development server: `yarn && yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Running `yarn dev` will tell you the URL you can visit in your browser to see the app. Exploring The Code ================== 1. The backend code lives in the `/assembly` folder. This code gets deployed to the NEAR blockchain when you run `yarn deploy:contract`. This sort of code-that-runs-on-a-blockchain is called a "smart contract" – [learn more about NEAR smart contracts][smart contract docs]. 2. The frontend code lives in the `/src` folder. [/src/index.html](/src/index.html) is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and backend. The backend code gets tested with the [asp] command for running the backend AssemblyScript tests, and [jest] for running frontend tests. You can run both of these at once with `yarn test`. Both contract and client-side code will auto-reload as you change source files. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contracts get deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli -------------------------- You need near-cli installed globally. Here's how: npm install --global near-cli This will give you the `near` [CLI] tool. Ensure that it's installed with: near --version Step 1: Create an account for the contract ------------------------------------------ Visit [NEAR Wallet] and make a new account. You'll be deploying these smart contracts to this new account. Now authorize NEAR CLI for this new account, and follow the instructions it gives you: near login Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'your-account-here!' Step 3: change remote URL if you cloned this repo ------------------------- Unless you forked this repository you will need to change the remote URL to a repo that you have commit access to. This will allow auto deployment to GitHub Pages from the command line. 1) go to GitHub and create a new repository for this project 2) open your terminal and in the root of this project enter the following: $ `git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPOSITORY.git` Step 4: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contracts to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. [NEAR]: https://near.org/ [yarn]: https://yarnpkg.com/ [AssemblyScript]: https://www.assemblyscript.org/introduction.html [React]: https://reactjs.org [smart contract docs]: https://docs.near.org/docs/develop/contracts/overview [asp]: https://www.npmjs.com/package/@as-pect/cli [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.near.org [near-cli]: https://github.com/near/near-cli [CLI]: https://www.w3schools.com/whatis/whatis_cli.asp [create-near-app]: https://github.com/near/create-near-app [gh-pages]: https://github.com/tschaub/gh-pages # NEAR Template Subgraph A NEAR Template Subgraph project to help you get started with The Graph for NEAR. For more information see the docs for [Building Subgraphs on NEAR](https://thegraph.com/docs/supported-networks/near). Customize the following files: - subgraph.yaml - schema.graphql - src/mappings.ts We've commented the three files to indicate what likely needs changing. # NFT Contract This contract contains the logic to create and manage items ## Deploying the Contract Build the contract: ./build.sh This will compile the contract into a wasm you can find in ./res Test contract (TODO) cargo test -- --no-capture Quick deploy: cd .. near dev-deploy --wasmFile ./out/market.wasm This will print out a dev account contract was deployed to. Set it to CONTRACT_NAME source neardev/dev-account.env Initialize the contract: near call $CONTRACT_NAME new_default_meta '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME Now fun stuff: Login to your near testnet account near login export ACCOUNT_ID={{WALLET_ID}} near call $CONTRACT_NAME create_order '{"requester_id": "'$ACCOUNT_ID'", "token_id": "9999"}' --accountId $ACCOUNT_ID --depositYocto 1 near view $CONTRACT_NAME get_supply_orders near view $CONTRACT_NAME get_supply_by_requester_id '{"requester_id": "'$ACCOUNT_ID'"}' near view $CONTRACT_NAME get_orders_by_requester '{"requester_id": "'$ACCOUNT_ID'", "limit": 5}' # Market Contract This contract contains the logic to create and manage orders ## Deploying the Contract Build the contract: ./build.sh This will compile the contract into a wasm you can find in ./res Test contract (TODO) cargo test -- --no-capture Quick deploy: cd .. near dev-deploy --wasmFile ./out/market.wasm This will print out a dev account contract was deployed to. Set it to CONTRACT_NAME source neardev/dev-account.env Initialize the contract: near call $CONTRACT_NAME new '{"owner_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME Now fun stuff: Login to your near testnet account near login export ACCOUNT_ID={{WALLET_ID}} near call $CONTRACT_NAME create_order '{"requester_id": "'$ACCOUNT_ID'", "token_id": "9999"}' --accountId $ACCOUNT_ID --depositYocto 1 near view $CONTRACT_NAME get_supply_orders near view $CONTRACT_NAME get_supply_by_requester_id '{"requester_id": "'$ACCOUNT_ID'"}' near view $CONTRACT_NAME get_orders_by_requester '{"requester_id": "'$ACCOUNT_ID'", "limit": 5}'
Morowot_morowot.github.io
README.md contract Cargo.toml README.md build.sh compile.js src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs target .rustc_info.json debug .fingerprint Inflector-4abb4462752984fb lib-inflector.json autocfg-491f31ad758e1582 lib-autocfg.json borsh-derive-982fdfb48f69be92 lib-borsh-derive.json borsh-derive-internal-d50c46e06158b7c9 lib-borsh-derive-internal.json borsh-schema-derive-internal-884c287726cd4214 lib-borsh-schema-derive-internal.json byteorder-4678558b19904739 build-script-build-script-build.json convert_case-6422071f72e7eeb3 lib-convert_case.json derive_more-4527320901fb28de lib-derive_more.json generic-array-c6f78d1a2dcbb951 build-script-build-script-build.json hashbrown-0ebaa7762b17f35a build-script-build-script-build.json hashbrown-625fe97f72ab7efd run-build-script-build-script-build.json hashbrown-97def125353ac13b lib-hashbrown.json indexmap-4381a46e87fd75a0 build-script-build-script-build.json indexmap-87b1d90a3f722fe4 run-build-script-build-script-build.json indexmap-d7eec4f9d0810f6e lib-indexmap.json itoa-18955514e94ee3df lib-itoa.json memchr-d172e178d0380546 build-script-build-script-build.json near-rpc-error-core-ddca5d56afa3e3a3 lib-near-rpc-error-core.json near-rpc-error-macro-cb50414efa6bf5ea lib-near-rpc-error-macro.json near-sdk-core-7ff3e94a18e2d77b lib-near-sdk-core.json near-sdk-macros-9c5676e0a1778150 lib-near-sdk-macros.json num-bigint-087b98528bb17d3a build-script-build-script-build.json num-integer-66202b6950780756 build-script-build-script-build.json num-rational-60a16f5bd5f3f024 build-script-build-script-build.json num-traits-70c95ea006e32a74 build-script-build-script-build.json proc-macro-crate-98b41315df30d3b7 lib-proc-macro-crate.json proc-macro2-2c6a23d60ccd7f4e run-build-script-build-script-build.json proc-macro2-8b5af9d397ead18a build-script-build-script-build.json proc-macro2-8bf22a28dd603d8c lib-proc-macro2.json quote-5bdc800257202187 lib-quote.json ryu-6e495802e0dca2f8 lib-ryu.json ryu-925eb7fa97cd33ae run-build-script-build-script-build.json ryu-dbc3a66ea4f76593 build-script-build-script-build.json serde-99b53df3332da024 run-build-script-build-script-build.json serde-b503d75818c50ef0 lib-serde.json serde-cc59da143fa15358 build-script-build-script-build.json serde_derive-1bb857dc8f29ae99 run-build-script-build-script-build.json serde_derive-6e9c85125d7a2ed1 lib-serde_derive.json serde_derive-f3ded73a7e2b9793 build-script-build-script-build.json serde_json-b70eff300b5a4957 build-script-build-script-build.json serde_json-d551c9d593571616 lib-serde_json.json serde_json-eea198169688ab24 run-build-script-build-script-build.json syn-4d72f68efd5c7071 run-build-script-build-script-build.json syn-d2f993746dc4eea5 lib-syn.json syn-ebf209806d57e738 build-script-build-script-build.json toml-6ccdf7e83a48abed lib-toml.json typenum-82b9447c219d6833 build-script-build-script-main.json unicode-xid-fb6d37763bf8ceac lib-unicode-xid.json version_check-2836013898ac669a lib-version_check.json wee_alloc-56d24b26c3f4ff71 build-script-build-script-build.json wasm32-unknown-unknown debug .fingerprint ahash-8a394d8d9685b366 lib-ahash.json aho-corasick-2c979cf76cafdb66 lib-aho_corasick.json base64-16948a8d617392fc lib-base64.json block-buffer-5f6e06afa074b171 lib-block-buffer.json block-buffer-d1541a82d6a5a1e1 lib-block-buffer.json block-padding-0dbbd77a1c7db503 lib-block-padding.json borsh-0f27ab8d5ef6aaf4 lib-borsh.json bs58-a6029119cf8e19b6 lib-bs58.json byte-tools-c561556a14cd01a2 lib-byte-tools.json byteorder-95eb5b5b00f3f9ce lib-byteorder.json byteorder-9e830d1983e96d91 run-build-script-build-script-build.json cfg-if-10b30cdd8ee72c3a lib-cfg-if.json cfg-if-3273d8d291d4694c lib-cfg-if.json digest-45d6a0aaffeb1b5e lib-digest.json digest-f2348cdc1e354c37 lib-digest.json generic-array-73b59990da7689d7 lib-generic_array.json generic-array-c408dacbc967f500 lib-generic_array.json generic-array-ed444c6f70013b50 run-build-script-build-script-build.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-45893a3de91ef8c3 run-build-script-build-script-build.json hashbrown-6f5e7718c2ecb998 lib-hashbrown.json hashbrown-bffcb3fdbed68aa0 lib-hashbrown.json hex-2141af1744c0e16c lib-hex.json indexmap-933933baa5304885 run-build-script-build-script-build.json indexmap-eef5baf882b129c0 lib-indexmap.json itoa-40550c993f54d444 lib-itoa.json keccak-00d467683040643f lib-keccak.json lazy_static-a4c2e1c5c77171c4 lib-lazy_static.json memchr-91b522f39629515c run-build-script-build-script-build.json memchr-b6bccb00cce1faf7 lib-memchr.json memory_units-eca18f7170267cc6 lib-memory_units.json near-primitives-core-15b5c3ca2f991866 lib-near-primitives-core.json near-runtime-utils-e6e7a4aec43c0dd1 lib-near-runtime-utils.json near-sdk-945157d7caccdafa lib-near-sdk.json near-vm-errors-067f7f682ec0af31 lib-near-vm-errors.json near-vm-logic-9a86d6a06431d7e5 lib-near-vm-logic.json num-bigint-109c0ba3932b259b lib-num-bigint.json num-bigint-75e4cf1ea1a77d07 run-build-script-build-script-build.json num-integer-9efe661c0e66a9ae lib-num-integer.json num-integer-d35e1e83d940e1d3 run-build-script-build-script-build.json num-rational-54aef6de280a8e8a run-build-script-build-script-build.json num-rational-8c7d13544dfc363c lib-num-rational.json num-traits-60a7fce699e5dd4e run-build-script-build-script-build.json num-traits-b48a6ae4330a8a0f lib-num-traits.json opaque-debug-40e71e3d1cd3d500 lib-opaque-debug.json opaque-debug-5f776447d7d37c32 lib-opaque-debug.json regex-41b75f0e91269155 lib-regex.json regex-syntax-ca89d0552bd21e03 lib-regex-syntax.json ryu-041695aba4fdaa0d run-build-script-build-script-build.json ryu-1e98f7b84b8c8254 lib-ryu.json serde-6a3c2e872d3b8eb2 run-build-script-build-script-build.json serde-dd6df87d196a5a08 lib-serde.json serde_json-1dbc49333af7298e lib-serde_json.json serde_json-e9a34276aad67d26 run-build-script-build-script-build.json sha2-bb7724a88e8ebccd lib-sha2.json sha3-8ad035aa5ed4c51e lib-sha3.json typenum-332c243a6b371734 lib-typenum.json typenum-e850512b0eed675b run-build-script-build-script-main.json wee_alloc-0e4c95ab84521c02 lib-wee_alloc.json wee_alloc-da109d75bf09910e run-build-script-build-script-build.json build num-bigint-75e4cf1ea1a77d07 out radix_bases.rs typenum-e850512b0eed675b out consts.rs op.rs tests.rs wee_alloc-da109d75bf09910e out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint ahash-bfd007b3211d12f8 lib-ahash.json base64-2ee67bdf7e9e28bf lib-base64.json borsh-cce0d7d6e391151f lib-borsh.json bs58-e9d2b088a1b3aa68 lib-bs58.json cfg-if-d186281152208ab6 lib-cfg-if.json contract-b9b080fd8c9c503c lib-contract.json hashbrown-d532716c4d97ebd3 lib-hashbrown.json itoa-9064f01d43981d55 lib-itoa.json memory_units-640ff7701f83577f lib-memory_units.json near-sdk-6671d8a1266f9fc4 lib-near-sdk.json near-sys-2eb9cd53cdb20e2b lib-near-sys.json ryu-3af457c0a69565df lib-ryu.json serde-552920a20459ba04 lib-serde.json serde-c313852a29052fa4 run-build-script-build-script-build.json serde_json-ad658a676b920724 run-build-script-build-script-build.json serde_json-deeb30fce098ebcd lib-serde_json.json wee_alloc-20a6d95a53a658be lib-wee_alloc.json wee_alloc-22497db7cf616fe1 run-build-script-build-script-build.json build wee_alloc-22497db7cf616fe1 out wee_alloc_static_array_backend_size_bytes.txt package.json src App.js Components InfoBubble.js MintingTool.js __mocks__ fileMock.js assets logo-black.svg logo-white.svg near_icon.svg near_logo_wht.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
nft-mint-frontend ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `nft-mint-frontend.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `nft-mint-frontend.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account nft-mint-frontend.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'nft-mint-frontend.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # chalenge3-4 nft-mint-frontend Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html
andreykobal_amber-frontend
.gitpod.yml README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs target .rustc_info.json debug .fingerprint Inflector-43feca6693eacde7 lib-inflector.json autocfg-ce7784e1ec7b4471 lib-autocfg.json borsh-derive-c66a001f715b61bd lib-borsh-derive.json borsh-derive-internal-47300e99565762f7 lib-borsh-derive-internal.json borsh-schema-derive-internal-e125f8abee8d6d3c lib-borsh-schema-derive-internal.json byteorder-a5b2ef220fa4aa58 build-script-build-script-build.json convert_case-3e34b674a3055f51 lib-convert_case.json derive_more-90da512afdf29cec lib-derive_more.json generic-array-8f9750ce6db71cdf build-script-build-script-build.json hashbrown-4715147519423b9f lib-hashbrown.json hashbrown-e6dbeeaf60ba0149 run-build-script-build-script-build.json hashbrown-fe3d052080e72922 build-script-build-script-build.json indexmap-12cdf0c04991d5b2 run-build-script-build-script-build.json indexmap-771e05f56e911434 build-script-build-script-build.json indexmap-9188af7f2fbde06c lib-indexmap.json itoa-d6019665920166ca lib-itoa.json memchr-0c2655dece3a5c2a build-script-build-script-build.json near-rpc-error-core-ddae6533e865161d lib-near-rpc-error-core.json near-rpc-error-macro-4cf3bd44b1c8af0d lib-near-rpc-error-macro.json near-sdk-core-a0c8311b5dfc4cfd lib-near-sdk-core.json near-sdk-macros-798e2fb2a8a5154c lib-near-sdk-macros.json num-bigint-a8b27e1851a47dae build-script-build-script-build.json num-integer-3ff85b8c0139205c build-script-build-script-build.json num-rational-6afe7dccf089b23c build-script-build-script-build.json num-traits-6b7105063d8405e8 build-script-build-script-build.json proc-macro-crate-cbe39f16c93ce811 lib-proc-macro-crate.json proc-macro2-6a03fdc1a66cb69b lib-proc-macro2.json proc-macro2-8777eb9a9ba47919 build-script-build-script-build.json proc-macro2-a0a7a6f5ec265d63 run-build-script-build-script-build.json quote-f9022bfb03d8dff3 lib-quote.json ryu-b114b7bf20bd588d build-script-build-script-build.json ryu-b4079b41f3134326 run-build-script-build-script-build.json ryu-f9bb3c7becb97891 lib-ryu.json serde-717545a8fde9d017 run-build-script-build-script-build.json serde-a72186585efe8ed1 build-script-build-script-build.json serde-ebe4278c3a11133a lib-serde.json serde_derive-09f2f95028200222 run-build-script-build-script-build.json serde_derive-86ed526aec1da329 lib-serde_derive.json serde_derive-cf88a84d678ee2e4 build-script-build-script-build.json serde_json-ba2eea35140cff06 lib-serde_json.json serde_json-d85ef4522161f5a6 run-build-script-build-script-build.json serde_json-ed3733fd9def1067 build-script-build-script-build.json syn-287957610e19250e run-build-script-build-script-build.json syn-331a484e788aa9c3 build-script-build-script-build.json syn-d65eb9871f6bf639 lib-syn.json toml-9cf6199398334e8d lib-toml.json typenum-a15a19a45c376e99 build-script-build-script-main.json unicode-xid-2d77b7eadf50c62e lib-unicode-xid.json version_check-413790463c361025 lib-version_check.json wee_alloc-e24e3f3e55a205fe build-script-build-script-build.json release .fingerprint Inflector-971d12571cd74ccc lib-inflector.json autocfg-6c90b200fc23a9fc lib-autocfg.json borsh-derive-dd622f9b282b0769 lib-borsh-derive.json borsh-derive-internal-de23273ba7fb2032 lib-borsh-derive-internal.json borsh-schema-derive-internal-5b061598c67a252e lib-borsh-schema-derive-internal.json byteorder-7df47cfeb4932ccb build-script-build-script-build.json convert_case-0b0e2598baee41bb lib-convert_case.json derive_more-f14f429f7df56c3d lib-derive_more.json generic-array-ff847ced35daa5ac build-script-build-script-build.json hashbrown-1331270c5cb619a7 run-build-script-build-script-build.json hashbrown-56c096e6265afdec build-script-build-script-build.json hashbrown-786da5887c47dddf lib-hashbrown.json indexmap-37915a07ad376331 run-build-script-build-script-build.json indexmap-38fc82d153d2ce3b lib-indexmap.json indexmap-eb9a185c88da4a36 build-script-build-script-build.json itoa-b4085ecfc311edf9 lib-itoa.json memchr-ed355b9280ab2042 build-script-build-script-build.json near-rpc-error-core-ca165ed9b31a5a3e lib-near-rpc-error-core.json near-rpc-error-macro-c3cf6d58e7b4594e lib-near-rpc-error-macro.json near-sdk-core-41bef0775b141b0e lib-near-sdk-core.json near-sdk-macros-8d6b45d6d89e14b7 lib-near-sdk-macros.json num-bigint-e6debb391fc94216 build-script-build-script-build.json num-integer-619179dc329c0b50 build-script-build-script-build.json num-rational-e77899a5dc776f71 build-script-build-script-build.json num-traits-8eac38bb77017341 build-script-build-script-build.json proc-macro-crate-99af7a02f87e7c37 lib-proc-macro-crate.json proc-macro2-3e000e516e10a5db lib-proc-macro2.json proc-macro2-c05ad936e37638dd build-script-build-script-build.json proc-macro2-d324b639bd36dd22 run-build-script-build-script-build.json quote-e8b3d3ee2b2a468c lib-quote.json ryu-0b9c3d175bc20f19 build-script-build-script-build.json ryu-40efe35c938286b6 run-build-script-build-script-build.json ryu-5e71ea23f4463188 lib-ryu.json serde-878518af6ec69d23 run-build-script-build-script-build.json serde-aebce9d0b211a288 lib-serde.json serde-cdcb260ace74b1a9 build-script-build-script-build.json serde_derive-166f7eceabe345fa lib-serde_derive.json serde_derive-209d7b975b72075c run-build-script-build-script-build.json serde_derive-7fd709e497b8dca0 build-script-build-script-build.json serde_json-087891b2d492085f lib-serde_json.json serde_json-b564d827ba6eefed build-script-build-script-build.json serde_json-de693e9034ab1a9e run-build-script-build-script-build.json syn-2e7b6d98ae7148f3 build-script-build-script-build.json syn-36c575ee6bdee5d8 run-build-script-build-script-build.json syn-6bd3d4cc0039bc9d lib-syn.json toml-3058adb7e121ae03 lib-toml.json typenum-32c4bab48277300b build-script-build-script-main.json unicode-xid-9973c4f77c270d9c lib-unicode-xid.json version_check-2f8f6d186475fac7 lib-version_check.json wee_alloc-b0ada70db02a195c build-script-build-script-build.json wasm32-unknown-unknown debug .fingerprint ahash-612946e4a705c957 lib-ahash.json aho-corasick-8d2aa056d0c5ed4e lib-aho_corasick.json base64-cf025b5209cb2d0b lib-base64.json block-buffer-4bded05429b809b7 lib-block-buffer.json block-buffer-b1d0627a5d94608c lib-block-buffer.json block-padding-7b2bce12c0a16fc2 lib-block-padding.json borsh-d9f6961a11ba8949 lib-borsh.json bs58-e88674807796dbe2 lib-bs58.json byte-tools-7f51d59596b144f0 lib-byte-tools.json byteorder-25b42b86990d6e9e lib-byteorder.json byteorder-2ea8c8d15201dbe9 run-build-script-build-script-build.json cfg-if-b1cf6720ef6e429e lib-cfg-if.json cfg-if-fbbf0c3f7446caa3 lib-cfg-if.json digest-b3d22e244b26ae4b lib-digest.json digest-c2b970ee82c2766b lib-digest.json generic-array-0013ddbf3705f5e8 lib-generic_array.json generic-array-14725602e612fc92 lib-generic_array.json generic-array-c52ee7585bf80077 run-build-script-build-script-build.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-3d9774000b24314a lib-hashbrown.json hashbrown-ead79d8c4e3cfdb6 run-build-script-build-script-build.json hashbrown-f1b2fc1acdd979a8 lib-hashbrown.json hex-aa6f119bb7cef037 lib-hex.json indexmap-2b9fdfb0590db8ce lib-indexmap.json indexmap-92c77bbe3c53869b run-build-script-build-script-build.json itoa-f2dcdd15c069cfbf lib-itoa.json keccak-7f6c060605a15b71 lib-keccak.json lazy_static-ba9430838c81ba7b lib-lazy_static.json memchr-2a91fec19f7c81d7 run-build-script-build-script-build.json memchr-bcb0550f2dea2f4d lib-memchr.json memory_units-e5187fe04e81451b lib-memory_units.json near-primitives-core-c8f928056eafa8e2 lib-near-primitives-core.json near-runtime-utils-f702ee4ffda2a82a lib-near-runtime-utils.json near-sdk-ec0bd81dd0fccfc4 lib-near-sdk.json near-vm-errors-9f041a1b91cb2aa5 lib-near-vm-errors.json near-vm-logic-a358c1aa14d02ee9 lib-near-vm-logic.json num-bigint-11831ee67f264ebc run-build-script-build-script-build.json num-bigint-d1d7787064642cc5 lib-num-bigint.json num-integer-a63ab742df9986f5 lib-num-integer.json num-integer-bd7de2d2e9d87cc2 run-build-script-build-script-build.json num-rational-e830f3c5920260cc run-build-script-build-script-build.json num-rational-fb2bfa7a7416b383 lib-num-rational.json num-traits-0ad3b298da797243 lib-num-traits.json num-traits-d6beb2ca4d55107c run-build-script-build-script-build.json opaque-debug-af2f926b7222bc39 lib-opaque-debug.json opaque-debug-d34cbce1623f1a5f lib-opaque-debug.json regex-a2da315afc9140be lib-regex.json regex-syntax-0031869bd5c4f7a5 lib-regex-syntax.json ryu-5bb7f55c9b9fa198 lib-ryu.json ryu-d8152e1e1adf5a90 run-build-script-build-script-build.json serde-8c43f8d5072e3763 run-build-script-build-script-build.json serde-970d35b57ce242d2 lib-serde.json serde_json-1f4b0ef86fe74ed0 run-build-script-build-script-build.json serde_json-380a991f2ec0f5b7 lib-serde_json.json sha2-8a0bbd10f702e140 lib-sha2.json sha3-8ec6108662b48525 lib-sha3.json typenum-30fd908905b7508c run-build-script-build-script-main.json typenum-47add8917f46666a lib-typenum.json wee_alloc-01c61f61c5ad8231 lib-wee_alloc.json wee_alloc-6533575ddc004432 run-build-script-build-script-build.json build num-bigint-11831ee67f264ebc out radix_bases.rs typenum-30fd908905b7508c out consts.rs op.rs tests.rs wee_alloc-6533575ddc004432 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint ahash-1ff91d44a43d7f75 lib-ahash.json aho-corasick-f11a03410faecbf6 lib-aho_corasick.json base64-21664f36015e21f0 lib-base64.json block-buffer-50faabb797e48e8a lib-block-buffer.json block-buffer-97d423858901d24c lib-block-buffer.json block-padding-2d789381e00611f4 lib-block-padding.json borsh-d020ecd12b459daa lib-borsh.json bs58-749dd7ed550ad75f lib-bs58.json byte-tools-05804b47334692cd lib-byte-tools.json byteorder-85e8667836c28a8d run-build-script-build-script-build.json byteorder-edd123b6856808d1 lib-byteorder.json cfg-if-3f548c3b3a8613a1 lib-cfg-if.json cfg-if-e13b599e1580433b lib-cfg-if.json digest-21127efb99aa1d39 lib-digest.json digest-384cad7eeed48bba lib-digest.json generic-array-4763a2c796feb8d9 lib-generic_array.json generic-array-820b295fae9fbb44 run-build-script-build-script-build.json generic-array-ed00dd64539dc42b lib-generic_array.json greeter-98ace302c5fafa12 lib-greeter.json hashbrown-385bf8b0f7c4c038 lib-hashbrown.json hashbrown-4e157b87ad0046b8 lib-hashbrown.json hashbrown-959490edc8c96893 run-build-script-build-script-build.json hex-54f8cfcb821fddf5 lib-hex.json indexmap-1b3c2534c9d944d4 run-build-script-build-script-build.json indexmap-d8a7f0a9f688624d lib-indexmap.json itoa-a93a621f1a399e74 lib-itoa.json keccak-34c96866ecf1ac67 lib-keccak.json lazy_static-27a6f23ae3f80174 lib-lazy_static.json memchr-3074bb45b4cda370 run-build-script-build-script-build.json memchr-c307ab9b5924dec1 lib-memchr.json memory_units-9fc5376dafbdf7bb lib-memory_units.json near-primitives-core-8135a9e9ca2c6776 lib-near-primitives-core.json near-runtime-utils-bbf2b8a16bbc80b2 lib-near-runtime-utils.json near-sdk-24c30a2a1e1c1648 lib-near-sdk.json near-vm-errors-10bf7cbd817a83d6 lib-near-vm-errors.json near-vm-logic-8354b17fb39a7b1a lib-near-vm-logic.json num-bigint-2f9fca567c356851 lib-num-bigint.json num-bigint-44d75eb8e8ac0c09 run-build-script-build-script-build.json num-integer-cb3f0d9a8c39cd6b lib-num-integer.json num-integer-fd2b0de5f3c4233f run-build-script-build-script-build.json num-rational-08a2c0bf3208b1d2 run-build-script-build-script-build.json num-rational-fab72aae72d688c2 lib-num-rational.json num-traits-5ca7fd70d19e2a27 lib-num-traits.json num-traits-a74b0448982ca6dd run-build-script-build-script-build.json opaque-debug-afd69d12090964c4 lib-opaque-debug.json opaque-debug-bbd4a25179605534 lib-opaque-debug.json regex-a36e3bd3eb0957e3 lib-regex.json regex-syntax-ccc2f080bb9c2e6f lib-regex-syntax.json ryu-777ad4717f0f7df0 lib-ryu.json ryu-bf1be415105ea5cf run-build-script-build-script-build.json serde-2a76f0dc07cd97f7 lib-serde.json serde-fceeb30e8b3ca4bd run-build-script-build-script-build.json serde_json-16d522284be3ff0e lib-serde_json.json serde_json-d926fba75d425a8f run-build-script-build-script-build.json sha2-009b80ca03fcaaf9 lib-sha2.json sha3-3c89001fed259ad9 lib-sha3.json typenum-034e826346a0e35c run-build-script-build-script-main.json typenum-8c8860325d5ce5a8 lib-typenum.json wee_alloc-0a3b231e1e35b654 lib-wee_alloc.json wee_alloc-b6a34cf62f4bcb70 run-build-script-build-script-build.json build num-bigint-44d75eb8e8ac0c09 out radix_bases.rs typenum-034e826346a0e35c out consts.rs op.rs tests.rs wee_alloc-b6a34cf62f4bcb70 out wee_alloc_static_array_backend_size_bytes.txt package.json src App.js __mocks__ fileMock.js app.css assets logo-black.svg logo-white.svg config.js global.css index.html index.js jest.init.js main.test.js utils.js wallet login index.html
holy-cube-amber ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `holy-cube-amber.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `holy-cube-amber.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account holy-cube-amber.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'holy-cube-amber.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages holy-cube-amber ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `holy-cube-amber.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `holy-cube-amber.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account holy-cube-amber.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'holy-cube-amber.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages holy-cube-amber Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html holy-cube-amber ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `holy-cube-amber.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `holy-cube-amber.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account holy-cube-amber.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'holy-cube-amber.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages holy-cube-amber Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html holy-cube-amber ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `holy-cube-amber.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `holy-cube-amber.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account holy-cube-amber.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'holy-cube-amber.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages holy-cube-amber Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html holy-cube-amber Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html holy-cube-amber Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html holy-cube-amber ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `holy-cube-amber.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `holy-cube-amber.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account holy-cube-amber.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'holy-cube-amber.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
nearlog_nearlog-protocol
Cargo.toml README.md build.sh contract Cargo.toml src account.rs account_asset.rs actions.rs asset.rs asset_config.rs big_decimal.rs black_scholes.rs config.rs events.rs fungible_token.rs lib.rs option_order.rs option_orders_manager.rs pool.rs price_receiver.rs prices.rs storage.rs storage_tracker.rs utils.rs scripts 0_deploy.sh 1_deposit.sh tests basic.rs
# Nearlog Protocol Contract Nearlog protolcol is a native Near open-source option market that allows traders to buy and sell options on cryptocurrencies against a pool of liquidity. ## Getting started ``` cd existing_repo git remote add origin https://github.com/nearlog/nearlog-protocol.git git branch -M main git push -uf origin main ``` ## Build ``` ./build.sh ``` ## Deploy ``` ./scripts/0_deploy.sh ``` ## Actions ### Register account by paying for storage This has to be done one per account. ```bash near call $CONTRACT_ID --accountId=$ACCOUNT_ID --gas=$GAS --amount=0.1 storage_deposit '{}' ``` ### Deposit liquidity For example, let's deposit `5` WETH. ```bash near call $WETH_TOKEN_ID --accountId=$ACCOUNT_ID --gas=$GAS --amount=$ONE_YOCTO ft_transfer_call '{ "receiver_id": "'$CONTRACT_ID'", "amount": "5000000000000000000", "msg": "" }' ``` ### View account information ```bash near view $CONTRACT_ID get_account '{"account_id": "'$ACCOUNT_ID'"}' ``` ### View a given asset ```bash near view $CONTRACT_ID get_asset '{"token_id": "'$WETH_TOKEN_ID'"}' ``` ### Create a call option ``` near call $ORACLE_ID --accountId=$MAIN_ACCOUNT oracle_call '{ "receiver_id": "'$CONTRACT_ID'", "asset_ids": [ "'$WETH_TOKEN_ID'", "'$USDT_TOKEN_ID'", ], "msg": "{\"Execute\": {\"actions\": [{\"Create\":{\"option_type\": \"call\", \"strike\": \"20000\", \"expiration\": \"1663078814\", \"amount\": \"1\", \"token_id\":\"'$WETH_TOKEN_ID'\"}}]}}" }' --amount=$ONE_YOCTO --gas=$GAS ``` ### Create a put option ``` near call $ORACLE_ID --accountId=$MAIN_ACCOUNT oracle_call '{ "receiver_id": "'$CONTRACT_ID'", "asset_ids": [ "'$WETH_TOKEN_ID'", "'$USDT_TOKEN_ID'", ], "msg": "{\"Execute\": {\"actions\": [{\"Create\":{\"option_type\": \"put\", \"strike\": \"20000\", \"expiration\": \"1663078814\", \"amount\": \"1\", \"token_id\":\"'$WETH_TOKEN_ID'\"}}]}}" }' --amount=$ONE_YOCTO --gas=$GAS ``` ### Exercise an option ``` near call $ORACLE_ID --accountId=$MAIN_ACCOUNT oracle_call '{ "receiver_id": "'$CONTRACT_ID'", "asset_ids": [ "'$WETH_TOKEN_ID'", "'$USDT_TOKEN_ID'", ], "msg": "{\"Execute\": {\"actions\": [{\"Exercise\":{\"option_id\": \"1111\", \"token_id\":\"'$WETH_TOKEN_ID'\"}}]}}" }' --amount=$ONE_YOCTO --gas=$GAS ```
nabeel-ahmed-troon_StoreFront-Admin
README.md package.json public index.html manifest.json robots.txt src App.css App.js App.test.js NearProvider config.js utils.js components Collections.js CreateCollection.js Header.js InsertMetadata.js IpfsUpload.js index.css index.js logo.svg reportWebVitals.js setupTests.js
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can't go back!** If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Grekoff18_hackathon-status-message
.github dependabot.yml workflows tests.yml .gitpod.yml .travis.yml Cargo.toml README-Gitpod.md README-Windows.md README.md borsh.js frontend App.js config.js index.html index.js package-lock.json package.json src lib.rs test.bat test.js test.sh tests-ava README.md __tests__ main.ava.ts package.json tsconfig.json
These tests use [near-workspaces-ava](https://github.com/near/workspaces-js/tree/main/packages/ava): delightful, deterministic local testing for NEAR smart contracts. You will need to install [NodeJS](https://nodejs.dev/). Then you can use the `scripts` defined in [package.json](./package.json): npm run test If you want to run `near-workspaces-ava` or `ava` directly, you can use [npx](https://nodejs.dev/learn/the-npx-nodejs-package-runner): npx near-workspaces-ava --help npx ava --help To run only one test file: npm run test "**/main*" # matches test files starting with "main" npm run test "**/whatever/**/*" # matches test files in the "whatever" directory To run only one test: npm run test -- -m "root sets*" # matches tests with titles starting with "root sets" yarn test -m "root sets*" # same thing using yarn instead of npm, see https://yarnpkg.com/ Status Message ============== [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/rust-status-message) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> This smart contract saves and records the status messages of NEAR accounts that call it. Windows users: please visit the [Windows-specific README file](README-Windows.md). ## Prerequisites Ensure `near-cli` is installed by running: ``` near --version ``` If needed, install `near-cli`: ``` npm install near-cli -g ``` Ensure `Rust` is installed by running: ``` rustc --version ``` If needed, install `Rust`: ``` curl https://sh.rustup.rs -sSf | sh ``` Install dependencies ``` npm install ``` ## Quick Start To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install yarn: `npm install --global yarn` (or just `npm i -g yarn`) 2. Run the local development server: `yarn && yarn dev` (see package.json for a full list of scripts you can run with yarn) Now you'll have a local development environment backed by the NEAR TestNet! Running yarn dev will tell you the URL you can visit in your browser to see the app. ## Building this contract To make the build process compatible with multiple operating systems, the build process exists as a script in `package.json`. There are a number of special flags used to compile the smart contract into the wasm file. Run this command to build and place the wasm file in the `res` directory: ```bash npm run build ``` **Note**: Instead of `npm`, users of [yarn](https://yarnpkg.com) may run: ```bash yarn build ``` ### Important If you encounter an error similar to: >note: the `wasm32-unknown-unknown` target may not be installed Then run: ```bash rustup target add wasm32-unknown-unknown ``` ## Using this contract ### Web app Deploy the smart contract to a specific account created with the NEAR Wallet. Then interact with the smart contract using near-api-js on the frontend. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract to your NEAR account: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Build the frontend: ```bash npm start ``` If all is successful the app should be live at `localhost:1234`! ### Quickest deploy Build and deploy this smart contract to an development account. This development account will be created automatically and is not intended to be permanent. Please see the "Standard deploy" section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/status_message.wasm --helperUrl https://near-contract-helper.onrender.com ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing the key to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will call the contract's `set_status` method: ```bash near call $CONTRACT_NAME set_status '{"message": "aloha!"}' --accountId $CONTRACT_NAME ``` To retrieve the message from the contract, call `get_status` with the following: ```bash near view $CONTRACT_NAME get_status '{"account_id": "'$CONTRACT_NAME'"}' ``` ### Standard deploy In this option, the smart contract will get deployed to a specific account created with the NEAR Wallet. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Set a status for your account: ```bash near call YOUR_ACCOUNT_NAME set_status '{"message": "aloha friend"}' --accountId YOUR_ACCOUNT_NAME ``` Get the status: ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "YOUR_ACCOUNT_NAME"}' ``` Note that these status messages are stored per account in a `HashMap`. See `src/lib.rs` for the code. We can try the same steps with another account to verify. **Note**: we're adding `NEW_ACCOUNT_NAME` for the next couple steps. There are two ways to create a new account: - the NEAR Wallet (as we did before) - `near create_account NEW_ACCOUNT_NAME --masterAccount YOUR_ACCOUNT_NAME` Now call the contract on the first account (where it's deployed): ```bash near call YOUR_ACCOUNT_NAME set_status '{"message": "bonjour"}' --accountId NEW_ACCOUNT_NAME ``` ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "NEW_ACCOUNT_NAME"}' ``` Returns `bonjour`. Make sure the original status remains: ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "YOUR_ACCOUNT_NAME"}' ``` ## Testing To test run: ```bash cargo test --package status-message -- --nocapture ```
mgmoreira_Equipo5
.idea misc.xml modules.xml vcs.xml README.md as-pect.config.js asconfig.json build debug neardev dev-account.env neardev dev-account.env node_modules @as-covers assembly CONTRIBUTING.md README.md index.ts package.json tsconfig.json core CONTRIBUTING.md README.md package.json glue README.md lib index.d.ts index.js package.json transform README.md lib index.d.ts index.js util.d.ts util.js node_modules visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js toString.d.ts toString.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformRange.d.ts transformRange.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json package.json @as-pect assembly README.md assembly index.ts internal Actual.ts Expectation.ts Expected.ts Reflect.ts ReflectedValueType.ts Test.ts assert.ts call.ts comparison toIncludeComparison.ts toIncludeEqualComparison.ts log.ts noOp.ts package.json types as-pect.d.ts as-pect.portable.d.ts env.d.ts cli README.md init as-pect.config.js env.d.ts example.spec.ts init-types.d.ts portable-types.d.ts lib as-pect.cli.amd.d.ts as-pect.cli.amd.js help.d.ts help.js index.d.ts index.js init.d.ts init.js portable.d.ts portable.js run.d.ts run.js test.d.ts test.js types.d.ts types.js util CommandLineArg.d.ts CommandLineArg.js IConfiguration.d.ts IConfiguration.js asciiArt.d.ts asciiArt.js collectReporter.d.ts collectReporter.js getTestEntryFiles.d.ts getTestEntryFiles.js removeFile.d.ts removeFile.js strings.d.ts strings.js writeFile.d.ts writeFile.js worklets ICommand.d.ts ICommand.js compiler.d.ts compiler.js package.json core README.md lib as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js reporter CombinationReporter.d.ts CombinationReporter.js EmptyReporter.d.ts EmptyReporter.js IReporter.d.ts IReporter.js SummaryReporter.d.ts SummaryReporter.js VerboseReporter.d.ts VerboseReporter.js test IWarning.d.ts IWarning.js TestContext.d.ts TestContext.js TestNode.d.ts TestNode.js transform assemblyscript.d.ts assemblyscript.js createAddReflectedValueKeyValuePairsMember.d.ts createAddReflectedValueKeyValuePairsMember.js createGenericTypeParameter.d.ts createGenericTypeParameter.js createStrictEqualsMember.d.ts createStrictEqualsMember.js emptyTransformer.d.ts emptyTransformer.js hash.d.ts hash.js index.d.ts index.js util IAspectExports.d.ts IAspectExports.js IWriteable.d.ts IWriteable.js ReflectedValue.d.ts ReflectedValue.js TestNodeType.d.ts TestNodeType.js rTrace.d.ts rTrace.js stringifyReflectedValue.d.ts stringifyReflectedValue.js timeDifference.d.ts timeDifference.js wasmTools.d.ts wasmTools.js package.json csv-reporter index.ts lib as-pect.csv-reporter.amd.d.ts as-pect.csv-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json json-reporter index.ts lib as-pect.json-reporter.amd.d.ts as-pect.json-reporter.amd.js index.d.ts index.js package.json readme.md tsconfig.json snapshots __tests__ snapshot.spec.ts jest.config.js lib Snapshot.d.ts Snapshot.js SnapshotDiff.d.ts SnapshotDiff.js SnapshotDiffResult.d.ts SnapshotDiffResult.js as-pect.core.amd.d.ts as-pect.core.amd.js index.d.ts index.js parser grammar.d.ts grammar.js package.json src Snapshot.ts SnapshotDiff.ts SnapshotDiffResult.ts index.ts parser grammar.ts tsconfig.json @assemblyscript loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @eslint eslintrc CHANGELOG.md README.md conf config-schema.js environments.js eslint-all.js eslint-recommended.js lib cascading-config-array-factory.js config-array-factory.js config-array config-array.js config-dependency.js extracted-config.js ignore-pattern.js index.js override-tester.js flat-compat.js index.js shared ajv.js config-ops.js config-validator.js deprecation-warnings.js naming.js relative-module-resolver.js types.js package.json @humanwhocodes config-array README.md api.js package.json object-schema .eslintrc.js .github workflows nodejs-test.yml release-please.yml CHANGELOG.md README.md package.json src index.js merge-strategy.js object-schema.js validation-strategy.js tests merge-strategy.js object-schema.js validation-strategy.js acorn-jsx README.md index.d.ts index.js package.json xhtml.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js definition_schema.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json as-bignum README.md assembly __tests__ as-pect.d.ts i128.spec.as.ts safe_u128.spec.as.ts u128.spec.as.ts u256.spec.as.ts utils.ts fixed fp128.ts fp256.ts index.ts safe fp128.ts fp256.ts types.ts globals.ts index.ts integer i128.ts i256.ts index.ts safe i128.ts i256.ts i64.ts index.ts u128.ts u256.ts u64.ts u128.ts u256.ts tsconfig.json utils.ts package.json asbuild README.md dist cli.d.ts cli.js commands build.d.ts build.js fmt.d.ts fmt.js index.d.ts index.js init cmd.d.ts cmd.js files asconfigJson.d.ts asconfigJson.js aspecConfig.d.ts aspecConfig.js assembly_files.d.ts assembly_files.js eslintConfig.d.ts eslintConfig.js gitignores.d.ts gitignores.js index.d.ts index.js indexJs.d.ts indexJs.js packageJson.d.ts packageJson.js test_files.d.ts test_files.js index.d.ts index.js interfaces.d.ts interfaces.js run.d.ts run.js test.d.ts test.js index.d.ts index.js main.d.ts main.js utils.d.ts utils.js index.js node_modules cliui CHANGELOG.md LICENSE.txt README.md index.js package.json wrap-ansi index.js package.json readme.md y18n CHANGELOG.md README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md build lib apply-extends.d.ts apply-extends.js argsert.d.ts argsert.js command.d.ts command.js common-types.d.ts common-types.js completion-templates.d.ts completion-templates.js completion.d.ts completion.js is-promise.d.ts is-promise.js levenshtein.d.ts levenshtein.js middleware.d.ts middleware.js obj-filter.d.ts obj-filter.js parse-command.d.ts parse-command.js process-argv.d.ts process-argv.js usage.d.ts usage.js validation.d.ts validation.js yargs.d.ts yargs.js yerror.d.ts yerror.js index.js locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json assemblyscript-json .eslintrc.js .travis.yml README.md assembly JSON.ts decoder.ts encoder.ts index.ts tsconfig.json util index.ts index.js package.json temp-docs README.md classes decoderstate.md json.arr.md json.bool.md json.float.md json.integer.md json.null.md json.num.md json.obj.md json.str.md json.value.md jsondecoder.md jsonencoder.md jsonhandler.md throwingjsonhandler.md modules json.md assemblyscript-regex .eslintrc.js .github workflows benchmark.yml release.yml test.yml README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __spec_tests__ generated.spec.ts __tests__ alterations.spec.ts as-pect.d.ts boundary-assertions.spec.ts capture-group.spec.ts character-classes.spec.ts character-sets.spec.ts characters.ts empty.ts quantifiers.spec.ts range-quantifiers.spec.ts regex.spec.ts utils.ts char.ts env.ts index.ts nfa matcher.ts nfa.ts types.ts walker.ts parser node.ts parser.ts string-iterator.ts walker.ts regexp.ts tsconfig.json util.ts benchmark benchmark.js package.json spec test-generator.js ts index.ts tsconfig.json assemblyscript-temporal .github workflows node.js.yml release.yml .vscode launch.json README.md as-pect.config.js asconfig.empty.json asconfig.json assembly __tests__ README.md as-pect.d.ts date.spec.ts duration.spec.ts empty.ts plaindate.spec.ts plaindatetime.spec.ts plainmonthday.spec.ts plaintime.spec.ts plainyearmonth.spec.ts timezone.spec.ts zoneddatetime.spec.ts constants.ts date.ts duration.ts enums.ts env.ts index.ts instant.ts now.ts plaindate.ts plaindatetime.ts plainmonthday.ts plaintime.ts plainyearmonth.ts timezone.ts tsconfig.json tz __tests__ index.spec.ts rule.spec.ts zone.spec.ts iana.ts index.ts rule.ts zone.ts utils.ts zoneddatetime.ts development.md package.json tzdb README.md iana theory.html zoneinfo2tdf.pl assemblyscript README.md cli README.md asc.d.ts asc.js asc.json shim README.md fs.js path.js process.js transform.d.ts transform.js util colors.d.ts colors.js find.d.ts find.js mkdirp.d.ts mkdirp.js options.d.ts options.js utf8.d.ts utf8.js dist asc.js assemblyscript.d.ts assemblyscript.js sdk.js index.d.ts index.js lib loader README.md index.d.ts index.js package.json umd index.d.ts index.js package.json rtrace README.md bin rtplot.js index.d.ts index.js package.json umd index.d.ts index.js package.json package-lock.json package.json std README.md assembly.json assembly array.ts arraybuffer.ts atomics.ts bindings Date.ts Math.ts Reflect.ts asyncify.ts console.ts wasi.ts wasi_snapshot_preview1.ts wasi_unstable.ts builtins.ts compat.ts console.ts crypto.ts dataview.ts date.ts diagnostics.ts error.ts function.ts index.d.ts iterator.ts map.ts math.ts memory.ts number.ts object.ts polyfills.ts process.ts reference.ts regexp.ts rt.ts rt README.md common.ts index-incremental.ts index-minimal.ts index-stub.ts index.d.ts itcms.ts rtrace.ts stub.ts tcms.ts tlsf.ts set.ts shared feature.ts target.ts tsconfig.json typeinfo.ts staticarray.ts string.ts symbol.ts table.ts tsconfig.json typedarray.ts uri.ts util casemap.ts error.ts hash.ts math.ts memory.ts number.ts sort.ts string.ts uri.ts vector.ts wasi index.ts portable.json portable index.d.ts index.js types assembly index.d.ts package.json portable index.d.ts package.json tsconfig-base.json astral-regex index.d.ts index.js package.json readme.md axios CHANGELOG.md README.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel Cancel.js CancelToken.js isCancel.js core Axios.js InterceptorManager.js README.md buildFullPath.js createError.js dispatchRequest.js enhanceError.js mergeConfig.js settle.js transformData.js defaults.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isURLSameOrigin.js normalizeHeaderName.js parseHeaders.js spread.js utils.js package.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js binary-install README.md example binary.js package.json run.js index.js package.json src binary.js binaryen README.md index.d.ts package-lock.json package.json wasm.d.ts bn.js README.md lib bn.js package.json brace-expansion README.md index.js package.json bs58 CHANGELOG.md README.md index.js package.json callsites index.d.ts index.js package.json readme.md camelcase index.d.ts index.js package.json readme.md chalk index.d.ts package.json readme.md source index.js templates.js util.js chownr README.md chownr.js package.json cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts concat-map .travis.yml example map.js index.js package.json test map.js cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json csv-stringify README.md lib browser index.js sync.js es5 index.d.ts index.js sync.d.ts sync.js index.d.ts index.js sync.d.ts sync.js package.json debug README.md package.json src browser.js common.js index.js node.js decamelize index.js package.json readme.md deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js diff CONTRIBUTING.md README.md dist diff.js diff.min.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js discontinuous-range .travis.yml README.md index.js package.json test main-test.js doctrine CHANGELOG.md README.md lib doctrine.js typed.js utility.js package.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js enquirer CHANGELOG.md README.md index.d.ts index.js lib ansi.js combos.js completer.js interpolate.js keypress.js placeholder.js prompt.js prompts autocomplete.js basicauth.js confirm.js editable.js form.js index.js input.js invisible.js list.js multiselect.js numeral.js password.js quiz.js scale.js select.js snippet.js sort.js survey.js text.js toggle.js render.js roles.js state.js styles.js symbols.js theme.js timer.js types array.js auth.js boolean.js index.js number.js string.js utils.js package.json env-paths index.d.ts index.js package.json readme.md escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js node_modules estraverse README.md estraverse.js gulpfile.js package.json package.json eslint-utils README.md index.js package.json eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json eslint CHANGELOG.md README.md bin eslint.js conf category-list.json config-schema.js default-cli-options.js eslint-all.js eslint-recommended.js replacements.json lib api.js cli-engine cli-engine.js file-enumerator.js formatters checkstyle.js codeframe.js compact.js html.js jslint-xml.js json-with-metadata.js json.js junit.js stylish.js table.js tap.js unix.js visualstudio.js hash.js index.js lint-result-cache.js load-rules.js xml-escape.js cli.js config default-config.js flat-config-array.js flat-config-schema.js rule-validator.js eslint eslint.js index.js init autoconfig.js config-file.js config-initializer.js config-rule.js npm-utils.js source-code-utils.js linter apply-disable-directives.js code-path-analysis code-path-analyzer.js code-path-segment.js code-path-state.js code-path.js debug-helpers.js fork-context.js id-generator.js config-comment-parser.js index.js interpolate.js linter.js node-event-generator.js report-translator.js rule-fixer.js rules.js safe-emitter.js source-code-fixer.js timing.js options.js rule-tester index.js rule-tester.js rules accessor-pairs.js array-bracket-newline.js array-bracket-spacing.js array-callback-return.js array-element-newline.js arrow-body-style.js arrow-parens.js arrow-spacing.js block-scoped-var.js block-spacing.js brace-style.js callback-return.js camelcase.js capitalized-comments.js class-methods-use-this.js comma-dangle.js comma-spacing.js comma-style.js complexity.js computed-property-spacing.js consistent-return.js consistent-this.js constructor-super.js curly.js default-case-last.js default-case.js default-param-last.js dot-location.js dot-notation.js eol-last.js eqeqeq.js for-direction.js func-call-spacing.js func-name-matching.js func-names.js func-style.js function-call-argument-newline.js function-paren-newline.js generator-star-spacing.js getter-return.js global-require.js grouped-accessor-pairs.js guard-for-in.js handle-callback-err.js id-blacklist.js id-denylist.js id-length.js id-match.js implicit-arrow-linebreak.js indent-legacy.js indent.js index.js init-declarations.js jsx-quotes.js key-spacing.js keyword-spacing.js line-comment-position.js linebreak-style.js lines-around-comment.js lines-around-directive.js lines-between-class-members.js max-classes-per-file.js max-depth.js max-len.js max-lines-per-function.js max-lines.js max-nested-callbacks.js max-params.js max-statements-per-line.js max-statements.js multiline-comment-style.js multiline-ternary.js new-cap.js new-parens.js newline-after-var.js newline-before-return.js newline-per-chained-call.js no-alert.js no-array-constructor.js no-async-promise-executor.js no-await-in-loop.js no-bitwise.js no-buffer-constructor.js no-caller.js no-case-declarations.js no-catch-shadow.js no-class-assign.js no-compare-neg-zero.js no-cond-assign.js no-confusing-arrow.js no-console.js no-const-assign.js no-constant-condition.js no-constructor-return.js no-continue.js no-control-regex.js no-debugger.js no-delete-var.js no-div-regex.js no-dupe-args.js no-dupe-class-members.js no-dupe-else-if.js no-dupe-keys.js no-duplicate-case.js no-duplicate-imports.js no-else-return.js no-empty-character-class.js no-empty-function.js no-empty-pattern.js no-empty.js no-eq-null.js no-eval.js no-ex-assign.js no-extend-native.js no-extra-bind.js no-extra-boolean-cast.js no-extra-label.js no-extra-parens.js no-extra-semi.js no-fallthrough.js no-floating-decimal.js no-func-assign.js no-global-assign.js no-implicit-coercion.js no-implicit-globals.js no-implied-eval.js no-import-assign.js no-inline-comments.js no-inner-declarations.js no-invalid-regexp.js no-invalid-this.js no-irregular-whitespace.js no-iterator.js no-label-var.js no-labels.js no-lone-blocks.js no-lonely-if.js no-loop-func.js no-loss-of-precision.js no-magic-numbers.js no-misleading-character-class.js no-mixed-operators.js no-mixed-requires.js no-mixed-spaces-and-tabs.js no-multi-assign.js no-multi-spaces.js no-multi-str.js no-multiple-empty-lines.js no-native-reassign.js no-negated-condition.js no-negated-in-lhs.js no-nested-ternary.js no-new-func.js no-new-object.js no-new-require.js no-new-symbol.js no-new-wrappers.js no-new.js no-nonoctal-decimal-escape.js no-obj-calls.js no-octal-escape.js no-octal.js no-param-reassign.js no-path-concat.js no-plusplus.js no-process-env.js no-process-exit.js no-promise-executor-return.js no-proto.js no-prototype-builtins.js no-redeclare.js no-regex-spaces.js no-restricted-exports.js no-restricted-globals.js no-restricted-imports.js no-restricted-modules.js no-restricted-properties.js no-restricted-syntax.js no-return-assign.js no-return-await.js no-script-url.js no-self-assign.js no-self-compare.js no-sequences.js no-setter-return.js no-shadow-restricted-names.js no-shadow.js no-spaced-func.js no-sparse-arrays.js no-sync.js no-tabs.js no-template-curly-in-string.js no-ternary.js no-this-before-super.js no-throw-literal.js no-trailing-spaces.js no-undef-init.js no-undef.js no-undefined.js no-underscore-dangle.js no-unexpected-multiline.js no-unmodified-loop-condition.js no-unneeded-ternary.js no-unreachable-loop.js no-unreachable.js no-unsafe-finally.js no-unsafe-negation.js no-unsafe-optional-chaining.js no-unused-expressions.js no-unused-labels.js no-unused-vars.js no-use-before-define.js no-useless-backreference.js no-useless-call.js no-useless-catch.js no-useless-computed-key.js no-useless-concat.js no-useless-constructor.js no-useless-escape.js no-useless-rename.js no-useless-return.js no-var.js no-void.js no-warning-comments.js no-whitespace-before-property.js no-with.js nonblock-statement-body-position.js object-curly-newline.js object-curly-spacing.js object-property-newline.js object-shorthand.js one-var-declaration-per-line.js one-var.js operator-assignment.js operator-linebreak.js padded-blocks.js padding-line-between-statements.js prefer-arrow-callback.js prefer-const.js prefer-destructuring.js prefer-exponentiation-operator.js prefer-named-capture-group.js prefer-numeric-literals.js prefer-object-spread.js prefer-promise-reject-errors.js prefer-reflect.js prefer-regex-literals.js prefer-rest-params.js prefer-spread.js prefer-template.js quote-props.js quotes.js radix.js require-atomic-updates.js require-await.js require-jsdoc.js require-unicode-regexp.js require-yield.js rest-spread-spacing.js semi-spacing.js semi-style.js semi.js sort-imports.js sort-keys.js sort-vars.js space-before-blocks.js space-before-function-paren.js space-in-parens.js space-infix-ops.js space-unary-ops.js spaced-comment.js strict.js switch-colon-spacing.js symbol-description.js template-curly-spacing.js template-tag-spacing.js unicode-bom.js use-isnan.js utils ast-utils.js fix-tracker.js keywords.js lazy-loading-rule-map.js patterns letters.js unicode index.js is-combining-character.js is-emoji-modifier.js is-regional-indicator-symbol.js is-surrogate-pair.js valid-jsdoc.js valid-typeof.js vars-on-top.js wrap-iife.js wrap-regex.js yield-star-spacing.js yoda.js shared ajv.js ast-utils.js config-validator.js deprecation-warnings.js logging.js relative-module-resolver.js runtime-info.js string-utils.js traverser.js types.js source-code index.js source-code.js token-store backward-token-comment-cursor.js backward-token-cursor.js cursor.js cursors.js decorative-cursor.js filter-cursor.js forward-token-comment-cursor.js forward-token-cursor.js index.js limit-cursor.js padded-token-cursor.js skip-cursor.js utils.js messages all-files-ignored.js extend-config-missing.js failed-to-read-json.js file-not-found.js no-config-found.js plugin-conflict.js plugin-invalid.js plugin-missing.js print-config-with-directory-path.js whitespace-found.js node_modules eslint-visitor-keys CHANGELOG.md README.md lib index.js visitor-keys.json package.json package.json espree CHANGELOG.md README.md espree.js lib ast-node-types.js espree.js features.js options.js token-translator.js visitor-keys.js package.json esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esquery README.md dist esquery.esm.js esquery.esm.min.js esquery.js esquery.lite.js esquery.lite.min.js esquery.min.js license.txt package.json parser.js esrecurse README.md esrecurse.js gulpfile.babel.js package.json estraverse README.md estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-deep-equal README.md es6 index.d.ts index.js react.d.ts react.js index.d.ts index.js package.json react.d.ts react.js fast-json-stable-stringify .eslintrc.yml .github FUNDING.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.d.ts index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json file-entry-cache README.md cache.js changelog.md package.json find-up index.d.ts index.js package.json readme.md flat-cache README.md changelog.md package.json src cache.js del.js utils.js flatted .github FUNDING.yml workflows node.js.yml README.md SPECS.md cjs index.js package.json es.js esm index.js index.js min.js package.json php flatted.php types.d.ts follow-redirects README.md http.js https.js index.js node_modules debug .coveralls.yml .travis.yml CHANGELOG.md README.md karma.conf.js node.js package.json src browser.js debug.js index.js node.js ms index.js license.md package.json readme.md package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json functional-red-black-tree README.md bench test.js package.json rbtree.js test test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globals globals.json index.d.ts index.js package.json readme.md has-flag index.d.ts index.js package.json readme.md hasurl README.md index.js package.json ignore CHANGELOG.md README.md index.d.ts index.js legacy.js package.json import-fresh index.d.ts index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.js package.json js-base64 LICENSE.md README.md base64.d.ts base64.js package.json js-tokens CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-stable-stringify-without-jsonify .travis.yml example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js replacer.js space.js str.js to-json.js levn README.md lib cast.js index.js parse-string.js package.json line-column README.md lib line-column.js package.json locate-path index.d.ts index.js package.json readme.md lodash.clonedeep README.md index.js package.json lodash.merge README.md index.js package.json lodash.sortby README.md index.js package.json lodash.truncate README.md index.js package.json long README.md dist long.js index.js package.json src long.js lru-cache README.md index.js package.json minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp bin cmd.js usage.txt index.js package.json moo README.md moo.js package.json ms index.js license.md package.json readme.md natural-compare README.md index.js package.json near-mock-vm assembly __tests__ main.ts context.ts index.ts outcome.ts vm.ts bin bin.js package.json pkg near_mock_vm.d.ts near_mock_vm.js package.json vm dist cli.d.ts cli.js context.d.ts context.js index.d.ts index.js memory.d.ts memory.js runner.d.ts runner.js utils.d.ts utils.js index.js near-sdk-as README.md as-pect.config.js as_types.d.ts asconfig.json asp.asconfig.json assembly __tests__ as-pect.d.ts assert.spec.ts avl-tree.spec.ts bignum.spec.ts contract.spec.ts contract.ts data.txt datetime.spec.ts empty.ts generic.ts includeBytes.spec.ts main.ts max-heap.spec.ts model.ts near.spec.ts persistent-set.spec.ts promise.spec.ts rollback.spec.ts roundtrip.spec.ts runtime.spec.ts unordered-map.spec.ts util.ts utils.spec.ts as_types.d.ts bindgen.ts index.ts json.lib.ts tsconfig.json vm __tests__ vm.include.ts index.ts compiler.js imports.js out assembly __tests__ ason.ts model.ts ~lib as-bignum integer safe u128.ts package.json near-sdk-bindgen README.md assembly index.ts compiler.js dist JSONBuilder.d.ts JSONBuilder.js classExporter.d.ts classExporter.js index.d.ts index.js transformer.d.ts transformer.js typeChecker.d.ts typeChecker.js utils.d.ts utils.js index.js package.json near-sdk-core README.md asconfig.json assembly as_types.d.ts base58.ts base64.ts bignum.ts collections avlTree.ts index.ts maxHeap.ts persistentDeque.ts persistentMap.ts persistentSet.ts persistentUnorderedMap.ts persistentVector.ts util.ts contract.ts datetime.ts env env.ts index.ts runtime_api.ts index.ts logging.ts math.ts promise.ts storage.ts tsconfig.json util.ts docs assets css main.css js main.js search.json classes _sdk_core_assembly_collections_avltree_.avltree.html _sdk_core_assembly_collections_avltree_.avltreenode.html _sdk_core_assembly_collections_avltree_.childparentpair.html _sdk_core_assembly_collections_avltree_.nullable.html _sdk_core_assembly_collections_persistentdeque_.persistentdeque.html _sdk_core_assembly_collections_persistentmap_.persistentmap.html _sdk_core_assembly_collections_persistentset_.persistentset.html _sdk_core_assembly_collections_persistentunorderedmap_.persistentunorderedmap.html _sdk_core_assembly_collections_persistentvector_.persistentvector.html _sdk_core_assembly_contract_.context-1.html _sdk_core_assembly_contract_.contractpromise.html _sdk_core_assembly_contract_.contractpromiseresult.html _sdk_core_assembly_math_.rng.html _sdk_core_assembly_promise_.contractpromisebatch.html _sdk_core_assembly_storage_.storage-1.html globals.html index.html modules _sdk_core_assembly_base58_.base58.html _sdk_core_assembly_base58_.html _sdk_core_assembly_base64_.base64.html _sdk_core_assembly_base64_.html _sdk_core_assembly_collections_avltree_.html _sdk_core_assembly_collections_index_.collections.html _sdk_core_assembly_collections_index_.html _sdk_core_assembly_collections_persistentdeque_.html _sdk_core_assembly_collections_persistentmap_.html _sdk_core_assembly_collections_persistentset_.html _sdk_core_assembly_collections_persistentunorderedmap_.html _sdk_core_assembly_collections_persistentvector_.html _sdk_core_assembly_collections_util_.html _sdk_core_assembly_contract_.html _sdk_core_assembly_env_env_.env.html _sdk_core_assembly_env_env_.html _sdk_core_assembly_env_index_.html _sdk_core_assembly_env_runtime_api_.html _sdk_core_assembly_index_.html _sdk_core_assembly_logging_.html _sdk_core_assembly_logging_.logging.html _sdk_core_assembly_math_.html _sdk_core_assembly_math_.math.html _sdk_core_assembly_promise_.html _sdk_core_assembly_storage_.html _sdk_core_assembly_util_.html _sdk_core_assembly_util_.util.html package.json near-sdk-simulator __tests__ avl-tree-contract.spec.ts cross.spec.ts empty.spec.ts exportAs.spec.ts singleton-no-constructor.spec.ts singleton.spec.ts asconfig.js asconfig.json assembly __tests__ avlTreeContract.ts empty.ts exportAs.ts model.ts sentences.ts singleton-fail.ts singleton-no-constructor.ts singleton.ts words.ts as_types.d.ts tsconfig.json dist bin.d.ts bin.js context.d.ts context.js index.d.ts index.js runtime.d.ts runtime.js types.d.ts types.js utils.d.ts utils.js jest.config.js out assembly __tests__ empty.ts exportAs.ts model.ts sentences.ts singleton copy.ts singleton-no-constructor.ts singleton.ts package.json src context.ts index.ts runtime.ts types.ts utils.ts tsconfig.json near-vm getBinary.js install.js package.json run.js uninstall.js nearley LICENSE.txt README.md bin nearley-railroad.js nearley-test.js nearley-unparse.js nearleyc.js lib compile.js generate.js lint.js nearley-language-bootstrapped.js nearley.js stream.js unparse.js package.json once README.md once.js package.json optionator CHANGELOG.md README.md lib help.js index.js util.js package.json p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md parent-module index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-key index.d.ts index.js package.json readme.md prelude-ls CHANGELOG.md README.md lib Func.js List.js Num.js Obj.js Str.js index.js package.json progress CHANGELOG.md Readme.md index.js lib node-progress.js package.json punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js railroad-diagrams README.md example.html generator.html package.json railroad-diagrams.css railroad-diagrams.js railroad_diagrams.py randexp README.md lib randexp.js package.json regexpp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json require-from-string index.js package.json readme.md require-main-filename CHANGELOG.md LICENSE.txt README.md index.js package.json resolve-from index.js package.json readme.md ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf CHANGELOG.md README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json semver README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json shebang-command index.js package.json readme.md shebang-regex index.d.ts index.js package.json readme.md slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.d.ts index.js package.json readme.md supports-color browser.js index.js package.json readme.md table README.md dist src alignSpanningCell.d.ts alignSpanningCell.js alignString.d.ts alignString.js alignTableData.d.ts alignTableData.js calculateCellHeight.d.ts calculateCellHeight.js calculateMaximumColumnWidths.d.ts calculateMaximumColumnWidths.js calculateOutputColumnWidths.d.ts calculateOutputColumnWidths.js calculateRowHeights.d.ts calculateRowHeights.js calculateSpanningCellWidth.d.ts calculateSpanningCellWidth.js createStream.d.ts createStream.js drawBorder.d.ts drawBorder.js drawContent.d.ts drawContent.js drawRow.d.ts drawRow.js drawTable.d.ts drawTable.js generated validators.d.ts validators.js getBorderCharacters.d.ts getBorderCharacters.js index.d.ts index.js injectHeaderConfig.d.ts injectHeaderConfig.js makeRangeConfig.d.ts makeRangeConfig.js makeStreamConfig.d.ts makeStreamConfig.js makeTableConfig.d.ts makeTableConfig.js mapDataUsingRowHeights.d.ts mapDataUsingRowHeights.js padTableData.d.ts padTableData.js schemas config.json shared.json streamConfig.json spanningCellManager.d.ts spanningCellManager.js stringifyTableData.d.ts stringifyTableData.js table.d.ts table.js truncateTableData.d.ts truncateTableData.js types api.d.ts api.js internal.d.ts internal.js utils.d.ts utils.js validateConfig.d.ts validateConfig.js validateSpanningCellConfig.d.ts validateSpanningCellConfig.js validateTableData.d.ts validateTableData.js wrapCell.d.ts wrapCell.js wrapString.d.ts wrapString.js wrapWord.d.ts wrapWord.js node_modules ajv .runkit_example.js README.md dist 2019.d.ts 2019.js 2020.d.ts 2020.js ajv.d.ts ajv.js compile codegen code.d.ts code.js index.d.ts index.js scope.d.ts scope.js errors.d.ts errors.js index.d.ts index.js jtd parse.d.ts parse.js serialize.d.ts serialize.js types.d.ts types.js names.d.ts names.js ref_error.d.ts ref_error.js resolve.d.ts resolve.js rules.d.ts rules.js util.d.ts util.js validate applicability.d.ts applicability.js boolSchema.d.ts boolSchema.js dataType.d.ts dataType.js defaults.d.ts defaults.js index.d.ts index.js keyword.d.ts keyword.js subschema.d.ts subschema.js core.d.ts core.js jtd.d.ts jtd.js refs data.json json-schema-2019-09 index.d.ts index.js meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.d.ts index.js meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.d.ts jtd-schema.js runtime equal.d.ts equal.js parseJson.d.ts parseJson.js quote.d.ts quote.js re2.d.ts re2.js timestamp.d.ts timestamp.js ucs2length.d.ts ucs2length.js uri.d.ts uri.js validation_error.d.ts validation_error.js standalone index.d.ts index.js instance.d.ts instance.js types index.d.ts index.js json-schema.d.ts json-schema.js jtd-schema.d.ts jtd-schema.js vocabularies applicator additionalItems.d.ts additionalItems.js additionalProperties.d.ts additionalProperties.js allOf.d.ts allOf.js anyOf.d.ts anyOf.js contains.d.ts contains.js dependencies.d.ts dependencies.js dependentSchemas.d.ts dependentSchemas.js if.d.ts if.js index.d.ts index.js items.d.ts items.js items2020.d.ts items2020.js not.d.ts not.js oneOf.d.ts oneOf.js patternProperties.d.ts patternProperties.js prefixItems.d.ts prefixItems.js properties.d.ts properties.js propertyNames.d.ts propertyNames.js thenElse.d.ts thenElse.js code.d.ts code.js core id.d.ts id.js index.d.ts index.js ref.d.ts ref.js discriminator index.d.ts index.js types.d.ts types.js draft2020.d.ts draft2020.js draft7.d.ts draft7.js dynamic dynamicAnchor.d.ts dynamicAnchor.js dynamicRef.d.ts dynamicRef.js index.d.ts index.js recursiveAnchor.d.ts recursiveAnchor.js recursiveRef.d.ts recursiveRef.js errors.d.ts errors.js format format.d.ts format.js index.d.ts index.js jtd discriminator.d.ts discriminator.js elements.d.ts elements.js enum.d.ts enum.js error.d.ts error.js index.d.ts index.js metadata.d.ts metadata.js nullable.d.ts nullable.js optionalProperties.d.ts optionalProperties.js properties.d.ts properties.js ref.d.ts ref.js type.d.ts type.js union.d.ts union.js values.d.ts values.js metadata.d.ts metadata.js next.d.ts next.js unevaluated index.d.ts index.js unevaluatedItems.d.ts unevaluatedItems.js unevaluatedProperties.d.ts unevaluatedProperties.js validation const.d.ts const.js dependentRequired.d.ts dependentRequired.js enum.d.ts enum.js index.d.ts index.js limitContains.d.ts limitContains.js limitItems.d.ts limitItems.js limitLength.d.ts limitLength.js limitNumber.d.ts limitNumber.js limitProperties.d.ts limitProperties.js multipleOf.d.ts multipleOf.js pattern.d.ts pattern.js required.d.ts required.js uniqueItems.d.ts uniqueItems.js lib 2019.ts 2020.ts ajv.ts compile codegen code.ts index.ts scope.ts errors.ts index.ts jtd parse.ts serialize.ts types.ts names.ts ref_error.ts resolve.ts rules.ts util.ts validate applicability.ts boolSchema.ts dataType.ts defaults.ts index.ts keyword.ts subschema.ts core.ts jtd.ts refs data.json json-schema-2019-09 index.ts meta applicator.json content.json core.json format.json meta-data.json validation.json schema.json json-schema-2020-12 index.ts meta applicator.json content.json core.json format-annotation.json meta-data.json unevaluated.json validation.json schema.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json jtd-schema.ts runtime equal.ts parseJson.ts quote.ts re2.ts timestamp.ts ucs2length.ts uri.ts validation_error.ts standalone index.ts instance.ts types index.ts json-schema.ts jtd-schema.ts vocabularies applicator additionalItems.ts additionalProperties.ts allOf.ts anyOf.ts contains.ts dependencies.ts dependentSchemas.ts if.ts index.ts items.ts items2020.ts not.ts oneOf.ts patternProperties.ts prefixItems.ts properties.ts propertyNames.ts thenElse.ts code.ts core id.ts index.ts ref.ts discriminator index.ts types.ts draft2020.ts draft7.ts dynamic dynamicAnchor.ts dynamicRef.ts index.ts recursiveAnchor.ts recursiveRef.ts errors.ts format format.ts index.ts jtd discriminator.ts elements.ts enum.ts error.ts index.ts metadata.ts nullable.ts optionalProperties.ts properties.ts ref.ts type.ts union.ts values.ts metadata.ts next.ts unevaluated index.ts unevaluatedItems.ts unevaluatedProperties.ts validation const.ts dependentRequired.ts enum.ts index.ts limitContains.ts limitItems.ts limitLength.ts limitNumber.ts limitProperties.ts multipleOf.ts pattern.ts required.ts uniqueItems.ts package.json json-schema-traverse .eslintrc.yml .github FUNDING.yml workflows build.yml publish.yml README.md index.d.ts index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js package.json tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json text-table .travis.yml example align.js center.js dotalign.js doubledot.js table.js index.js package.json test align.js ansi-colors.js center.js dotalign.js doubledot.js table.js tr46 LICENSE.md README.md index.js lib mappingTable.json regexes.js package.json ts-mixer CHANGELOG.md README.md dist cjs decorator.js index.js mixin-tracking.js mixins.js proxy.js settings.js types.js util.js esm index.js index.min.js types decorator.d.ts index.d.ts mixin-tracking.d.ts mixins.d.ts proxy.d.ts settings.d.ts types.d.ts util.d.ts package.json type-check README.md lib check.js index.js parse-type.js package.json type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts universal-url README.md browser.js index.js package.json uri-js README.md dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js ws.d.ts ws.js wss.d.ts wss.js uri.d.ts uri.js util.d.ts util.js package.json v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js visitor-as .github workflows test.yml README.md as index.d.ts index.js asconfig.json dist astBuilder.d.ts astBuilder.js base.d.ts base.js baseTransform.d.ts baseTransform.js decorator.d.ts decorator.js examples capitalize.d.ts capitalize.js exportAs.d.ts exportAs.js functionCallTransform.d.ts functionCallTransform.js includeBytesTransform.d.ts includeBytesTransform.js list.d.ts list.js index.d.ts index.js path.d.ts path.js simpleParser.d.ts simpleParser.js transformer.d.ts transformer.js utils.d.ts utils.js visitor.d.ts visitor.js package.json tsconfig.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js URLSearchParams-impl.js URLSearchParams.js infra.js public-api.js url-state-machine.js urlencoded.js utils.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js word-wrap README.md index.d.ts index.js package.json wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json | features not yet implemented issues with the tests differences between PCRE and JS regex | | | package-lock.json package.json src as_types.d.ts contrato __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts model.ts tsconfig.json utils.ts
Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). long.js ======= A Long class for representing a 64 bit two's-complement integer value derived from the [Closure Library](https://github.com/google/closure-library) for stand-alone use and extended with unsigned support. [![Build Status](https://travis-ci.org/dcodeIO/long.js.svg)](https://travis-ci.org/dcodeIO/long.js) Background ---------- As of [ECMA-262 5th Edition](http://ecma262-5.com/ELS5_HTML.htm#Section_8.5), "all the positive and negative integers whose magnitude is no greater than 2<sup>53</sup> are representable in the Number type", which is "representing the doubleprecision 64-bit format IEEE 754 values as specified in the IEEE Standard for Binary Floating-Point Arithmetic". The [maximum safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) in JavaScript is 2<sup>53</sup>-1. Example: 2<sup>64</sup>-1 is 1844674407370955**1615** but in JavaScript it evaluates to 1844674407370955**2000**. Furthermore, bitwise operators in JavaScript "deal only with integers in the range −2<sup>31</sup> through 2<sup>31</sup>−1, inclusive, or in the range 0 through 2<sup>32</sup>−1, inclusive. These operators accept any value of the Number type but first convert each such value to one of 2<sup>32</sup> integer values." In some use cases, however, it is required to be able to reliably work with and perform bitwise operations on the full 64 bits. This is where long.js comes into play. Usage ----- The class is compatible with CommonJS and AMD loaders and is exposed globally as `Long` if neither is available. ```javascript var Long = require("long"); var longVal = new Long(0xFFFFFFFF, 0x7FFFFFFF); console.log(longVal.toString()); ... ``` API --- ### Constructor * new **Long**(low: `number`, high: `number`, unsigned?: `boolean`)<br /> Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. See the from* functions below for more convenient ways of constructing Longs. ### Fields * Long#**low**: `number`<br /> The low 32 bits as a signed value. * Long#**high**: `number`<br /> The high 32 bits as a signed value. * Long#**unsigned**: `boolean`<br /> Whether unsigned or not. ### Constants * Long.**ZERO**: `Long`<br /> Signed zero. * Long.**ONE**: `Long`<br /> Signed one. * Long.**NEG_ONE**: `Long`<br /> Signed negative one. * Long.**UZERO**: `Long`<br /> Unsigned zero. * Long.**UONE**: `Long`<br /> Unsigned one. * Long.**MAX_VALUE**: `Long`<br /> Maximum signed value. * Long.**MIN_VALUE**: `Long`<br /> Minimum signed value. * Long.**MAX_UNSIGNED_VALUE**: `Long`<br /> Maximum unsigned value. ### Utility * Long.**isLong**(obj: `*`): `boolean`<br /> Tests if the specified object is a Long. * Long.**fromBits**(lowBits: `number`, highBits: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. * Long.**fromBytes**(bytes: `number[]`, unsigned?: `boolean`, le?: `boolean`): `Long`<br /> Creates a Long from its byte representation. * Long.**fromBytesLE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its little endian byte representation. * Long.**fromBytesBE**(bytes: `number[]`, unsigned?: `boolean`): `Long`<br /> Creates a Long from its big endian byte representation. * Long.**fromInt**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given 32 bit integer value. * Long.**fromNumber**(value: `number`, unsigned?: `boolean`): `Long`<br /> Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. * Long.**fromString**(str: `string`, unsigned?: `boolean`, radix?: `number`)<br /> Long.**fromString**(str: `string`, radix: `number`)<br /> Returns a Long representation of the given string, written using the specified radix. * Long.**fromValue**(val: `*`, unsigned?: `boolean`): `Long`<br /> Converts the specified value to a Long using the appropriate from* function for its type. ### Methods * Long#**add**(addend: `Long | number | string`): `Long`<br /> Returns the sum of this and the specified Long. * Long#**and**(other: `Long | number | string`): `Long`<br /> Returns the bitwise AND of this Long and the specified. * Long#**compare**/**comp**(other: `Long | number | string`): `number`<br /> Compares this Long's value with the specified's. Returns `0` if they are the same, `1` if the this is greater and `-1` if the given one is greater. * Long#**divide**/**div**(divisor: `Long | number | string`): `Long`<br /> Returns this Long divided by the specified. * Long#**equals**/**eq**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value equals the specified's. * Long#**getHighBits**(): `number`<br /> Gets the high 32 bits as a signed integer. * Long#**getHighBitsUnsigned**(): `number`<br /> Gets the high 32 bits as an unsigned integer. * Long#**getLowBits**(): `number`<br /> Gets the low 32 bits as a signed integer. * Long#**getLowBitsUnsigned**(): `number`<br /> Gets the low 32 bits as an unsigned integer. * Long#**getNumBitsAbs**(): `number`<br /> Gets the number of bits needed to represent the absolute value of this Long. * Long#**greaterThan**/**gt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than the specified's. * Long#**greaterThanOrEqual**/**gte**/**ge**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is greater than or equal the specified's. * Long#**isEven**(): `boolean`<br /> Tests if this Long's value is even. * Long#**isNegative**(): `boolean`<br /> Tests if this Long's value is negative. * Long#**isOdd**(): `boolean`<br /> Tests if this Long's value is odd. * Long#**isPositive**(): `boolean`<br /> Tests if this Long's value is positive. * Long#**isZero**/**eqz**(): `boolean`<br /> Tests if this Long's value equals zero. * Long#**lessThan**/**lt**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than the specified's. * Long#**lessThanOrEqual**/**lte**/**le**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value is less than or equal the specified's. * Long#**modulo**/**mod**/**rem**(divisor: `Long | number | string`): `Long`<br /> Returns this Long modulo the specified. * Long#**multiply**/**mul**(multiplier: `Long | number | string`): `Long`<br /> Returns the product of this and the specified Long. * Long#**negate**/**neg**(): `Long`<br /> Negates this Long's value. * Long#**not**(): `Long`<br /> Returns the bitwise NOT of this Long. * Long#**notEquals**/**neq**/**ne**(other: `Long | number | string`): `boolean`<br /> Tests if this Long's value differs from the specified's. * Long#**or**(other: `Long | number | string`): `Long`<br /> Returns the bitwise OR of this Long and the specified. * Long#**shiftLeft**/**shl**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits shifted to the left by the given amount. * Long#**shiftRight**/**shr**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits arithmetically shifted to the right by the given amount. * Long#**shiftRightUnsigned**/**shru**/**shr_u**(numBits: `Long | number | string`): `Long`<br /> Returns this Long with bits logically shifted to the right by the given amount. * Long#**subtract**/**sub**(subtrahend: `Long | number | string`): `Long`<br /> Returns the difference of this and the specified Long. * Long#**toBytes**(le?: `boolean`): `number[]`<br /> Converts this Long to its byte representation. * Long#**toBytesLE**(): `number[]`<br /> Converts this Long to its little endian byte representation. * Long#**toBytesBE**(): `number[]`<br /> Converts this Long to its big endian byte representation. * Long#**toInt**(): `number`<br /> Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. * Long#**toNumber**(): `number`<br /> Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). * Long#**toSigned**(): `Long`<br /> Converts this Long to signed. * Long#**toString**(radix?: `number`): `string`<br /> Converts the Long to a string written in the specified radix. * Long#**toUnsigned**(): `Long`<br /> Converts this Long to unsigned. * Long#**xor**(other: `Long | number | string`): `Long`<br /> Returns the bitwise XOR of this Long and the given one. Building -------- To build an UMD bundle to `dist/long.js`, run: ``` $> npm install $> npm run build ``` Running the [tests](./tests): ``` $> npm test ``` # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT # levn [![Build Status](https://travis-ci.org/gkz/levn.png)](https://travis-ci.org/gkz/levn) <a name="levn" /> __Light ECMAScript (JavaScript) Value Notation__ Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments). Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1. __How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose. npm install levn For updates on levn, [follow me on twitter](https://twitter.com/gkzahariev). ## Quick Examples ```js var parse = require('levn').parse; parse('Number', '2'); // 2 parse('String', '2'); // '2' parse('String', 'levn'); // 'levn' parse('String', 'a b'); // 'a b' parse('Boolean', 'true'); // true parse('Date', '#2011-11-11#'); // (Date object) parse('Date', '2011-11-11'); // (Date object) parse('RegExp', '/[a-z]/gi'); // /[a-z]/gi parse('RegExp', 're'); // /re/ parse('Int', '2'); // 2 parse('Number | String', 'str'); // 'str' parse('Number | String', '2'); // 2 parse('[Number]', '[1,2,3]'); // [1,2,3] parse('(String, Boolean)', '(hi, false)'); // ['hi', false] parse('{a: String, b: Number}', '{a: str, b: 2}'); // {a: 'str', b: 2} // at the top level, you can ommit surrounding delimiters parse('[Number]', '1,2,3'); // [1,2,3] parse('(String, Boolean)', 'hi, false'); // ['hi', false] parse('{a: String, b: Number}', 'a: str, b: 2'); // {a: 'str', b: 2} // wildcard - auto choose type parse('*', '[hi,(null,[42]),{k: true}]'); // ['hi', [null, [42]], {k: true}] ``` ## Usage `require('levn');` returns an object that exposes three properties. `VERSION` is the current version of the library as a string. `parse` and `parsedTypeParse` are functions. ```js // parse(type, input, options); parse('[Number]', '1,2,3'); // [1, 2, 3] // parsedTypeParse(parsedType, input, options); var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ### parse(type, input, options) `parse` casts the string `input` into a JavaScript value according to the specified `type` in the [type format](https://github.com/gkz/type-check#type-format) (and taking account the optional `options`) and returns the resulting JavaScript value. ##### arguments * type - `String` - the type written in the [type format](https://github.com/gkz/type-check#type-format) which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js parse('[Number]', '1,2,3'); // [1, 2, 3] ``` ### parsedTypeParse(parsedType, input, options) `parsedTypeParse` casts the string `input` into a JavaScript value according to the specified `type` which has already been parsed (and taking account the optional `options`) and returns the resulting JavaScript value. You can parse a type using the [type-check](https://github.com/gkz/type-check) library's `parseType` function. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `String` - the value written in the [levn format](#levn-format) * options - `Maybe Object` - an optional parameter specifying additional [options](#options) ##### returns `*` - the resulting JavaScript value ##### example ```js var parsedType = require('type-check').parseType('[Number]'); parsedTypeParse(parsedType, '1,2,3'); // [1, 2, 3] ``` ## Levn Format Levn can use the type information you provide to choose the appropriate value to produce from the input. For the same input, it will choose a different output value depending on the type provided. For example, `parse('Number', '2')` will produce the number `2`, but `parse('String', '2')` will produce the string `"2"`. If you do not provide type information, and simply use `*`, levn will parse the input according the unambiguous "explicit" mode, which we will now detail - you can also set the `explicit` option to true manually in the [options](#options). * `"string"`, `'string'` are parsed as a String, eg. `"a msg"` is `"a msg"` * `#date#` is parsed as a Date, eg. `#2011-11-11#` is `new Date('2011-11-11')` * `/regexp/flags` is parsed as a RegExp, eg. `/re/gi` is `/re/gi` * `undefined`, `null`, `NaN`, `true`, and `false` are all their JavaScript equivalents * `[element1, element2, etc]` is an Array, and the casting procedure is recursively applied to each element. Eg. `[1,2,3]` is `[1,2,3]`. * `(element1, element2, etc)` is an tuple, and the casting procedure is recursively applied to each element. Eg. `(1, a)` is `(1, a)` (is `[1, 'a']`). * `{key1: val1, key2: val2, ...}` is an Object, and the casting procedure is recursively applied to each property. Eg. `{a: 1, b: 2}` is `{a: 1, b: 2}`. * Any test which does not fall under the above, and which does not contain special characters (`[``]``(``)``{``}``:``,`) is a string, eg. `$12- blah` is `"$12- blah"`. If you do provide type information, you can make your input more concise as the program already has some information about what it expects. Please see the [type format](https://github.com/gkz/type-check#type-format) section of [type-check](https://github.com/gkz/type-check) for more information about how to specify types. There are some rules about what levn can do with the information: * If a String is expected, and only a String, all characters of the input (including any special ones) will become part of the output. Eg. `[({})]` is `"[({})]"`, and `"hi"` is `'"hi"'`. * If a Date is expected, the surrounding `#` can be omitted from date literals. Eg. `2011-11-11` is `new Date('2011-11-11')`. * If a RegExp is expected, no flags need to be specified, and the regex is not using any of the special characters,the opening and closing `/` can be omitted - this will have the affect of setting the source of the regex to the input. Eg. `regex` is `/regex/`. * If an Array is expected, and it is the root node (at the top level), the opening `[` and closing `]` can be omitted. Eg. `1,2,3` is `[1,2,3]`. * If a tuple is expected, and it is the root node (at the top level), the opening `(` and closing `)` can be omitted. Eg. `1, a` is `(1, a)` (is `[1, 'a']`). * If an Object is expected, and it is the root node (at the top level), the opening `{` and closing `}` can be omitted. Eg `a: 1, b: 2` is `{a: 1, b: 2}`. If you list multiple types (eg. `Number | String`), it will first attempt to cast to the first type and then validate - if the validation fails it will move on to the next type and so forth, left to right. You must be careful as some types will succeed with any input, such as String. Thus put String at the end of your list. In non-explicit mode, Date and RegExp will succeed with a large variety of input - also be careful with these and list them near the end if not last in your list. Whitespace between special characters and elements is inconsequential. ## Options Options is an object. It is an optional parameter to the `parse` and `parsedTypeParse` functions. ### Explicit A `Boolean`. By default it is `false`. __Example:__ ```js parse('RegExp', 're', {explicit: false}); // /re/ parse('RegExp', 're', {explicit: true}); // Error: ... does not type check... parse('RegExp | String', 're', {explicit: true}); // 're' ``` `explicit` sets whether to be in explicit mode or not. Using `*` automatically activates explicit mode. For more information, read the [levn format](#levn-format) section. ### customTypes An `Object`. Empty `{}` by default. __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function (x) { return x % 2 === 0; }, cast: function (x) { return {type: 'Just', value: parseInt(x)}; } } } } parse('Even', '2', options); // 2 parse('Even', '3', options); // Error: Value: "3" does not type check... ``` __Another Example:__ ```js function Person(name, age){ this.name = name; this.age = age; } var options = { customTypes: { Person: { typeOf: 'Object', validate: function (x) { x instanceof Person; }, cast: function (value, options, typesCast) { var name, age; if ({}.toString.call(value).slice(8, -1) !== 'Object') { return {type: 'Nothing'}; } name = typesCast(value.name, [{type: 'String'}], options); age = typesCast(value.age, [{type: 'Numger'}], options); return {type: 'Just', value: new Person(name, age)}; } } } parse('Person', '{name: Laura, age: 25}', options); // Person {name: 'Laura', age: 25} ``` `customTypes` is an object whose keys are the name of the types, and whose values are an object with three properties, `typeOf`, `validate`, and `cast`. For more information about `typeOf` and `validate`, please see the [custom types](https://github.com/gkz/type-check#custom-types) section of type-check. `cast` is a function which receives three arguments, the value under question, options, and the typesCast function. In `cast`, attempt to cast the value into the specified type. If you are successful, return an object in the format `{type: 'Just', value: CAST-VALUE}`, if you know it won't work, return `{type: 'Nothing'}`. You can use the `typesCast` function to cast any child values. Remember to pass `options` to it. In your function you can also check for `options.explicit` and act accordingly. ## Technical About `levn` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [type-check](https://github.com/gkz/type-check) to both parse types and validate values. It also uses the [prelude.ls](http://preludels.com/) library. # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. Like `chown -R`. Takes the same arguments as `fs.chown()` # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![build status](https://img.shields.io/travis/axios/axios/master.svg?style=flat-square)](https://travis-ci.org/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) Promise based HTTP client for the browser and node.js ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using cdn: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios'); // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .finally(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete })); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience aliases have been provided for all supported request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency Helper functions for dealing with concurrent requests. ##### axios.all(iterable) ##### axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed maxContentLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' defines the hostname and port of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with // All header names are lower cased headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation You can cancel a request using a *cancel token*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token. ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. ###### NOTE The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665). ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions. ```typescript import axios from 'axios'; axios.get('/user?ID=12345'); ``` ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. ## License [MIT](LICENSE) # lodash.merge v4.6.2 The [Lodash](https://lodash.com/) method `_.merge` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.merge ``` In Node.js: ```js var merge = require('lodash.merge'); ``` See the [documentation](https://lodash.com/docs#merge) or [package source](https://github.com/lodash/lodash/blob/4.6.2-npm-packages/lodash.merge) for more details. These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # randexp.js randexp will generate a random string that matches a given RegExp Javascript object. [![Build Status](https://secure.travis-ci.org/fent/randexp.js.svg)](http://travis-ci.org/fent/randexp.js) [![Dependency Status](https://david-dm.org/fent/randexp.js.svg)](https://david-dm.org/fent/randexp.js) [![codecov](https://codecov.io/gh/fent/randexp.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/randexp.js) # Usage ```js var RandExp = require('randexp'); // supports grouping and piping new RandExp(/hello+ (world|to you)/).gen(); // => hellooooooooooooooooooo world // sets and ranges and references new RandExp(/<([a-z]\w{0,20})>foo<\1>/).gen(); // => <m5xhdg>foo<m5xhdg> // wildcard new RandExp(/random stuff: .+/).gen(); // => random stuff: l3m;Hf9XYbI [YPaxV>U*4-_F!WXQh9>;rH3i l!8.zoh?[utt1OWFQrE ^~8zEQm]~tK // ignore case new RandExp(/xxx xtreme dragon warrior xxx/i).gen(); // => xxx xtReME dRAGON warRiOR xXX // dynamic regexp shortcut new RandExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i'); // is the same as new RandExp(new RegExp('(sun|mon|tue|wednes|thurs|fri|satur)day', 'i')); ``` If you're only going to use `gen()` once with a regexp and want slightly shorter syntax for it ```js var randexp = require('randexp').randexp; randexp(/[1-6]/); // 4 randexp('great|good( job)?|excellent'); // great ``` If you miss the old syntax ```js require('randexp').sugar(); /yes|no|maybe|i don't know/.gen(); // maybe ``` # Motivation Regular expressions are used in every language, every programmer is familiar with them. Regex can be used to easily express complex strings. What better way to generate a random string than with a language you can use to express the string you want? Thanks to [String-Random](http://search.cpan.org/~steve/String-Random-0.22/lib/String/Random.pm) for giving me the idea to make this in the first place and [randexp](https://github.com/benburkert/randexp) for the sweet `.gen()` syntax. # Default Range The default generated character range includes printable ASCII. In order to add or remove characters, a `defaultRange` attribute is exposed. you can `subtract(from, to)` and `add(from, to)` ```js var randexp = new RandExp(/random stuff: .+/); randexp.defaultRange.subtract(32, 126); randexp.defaultRange.add(0, 65535); randexp.gen(); // => random stuff: 湐箻ໜ䫴␩⶛㳸長���邓蕲뤀쑡篷皇硬剈궦佔칗븛뀃匫鴔事좍ﯣ⭼ꝏ䭍詳蒂䥂뽭 ``` # Custom PRNG The default randomness is provided by `Math.random()`. If you need to use a seedable or cryptographic PRNG, you can override `RandExp.prototype.randInt` or `randexp.randInt` (where `randexp` is an instance of `RandExp`). `randInt(from, to)` accepts an inclusive range and returns a randomly selected number within that range. # Infinite Repetitionals Repetitional tokens such as `*`, `+`, and `{3,}` have an infinite max range. In this case, randexp looks at its min and adds 100 to it to get a useable max value. If you want to use another int other than 100 you can change the `max` property in `RandExp.prototype` or the RandExp instance. ```js var randexp = new RandExp(/no{1,}/); randexp.max = 1000000; ``` With `RandExp.sugar()` ```js var regexp = /(hi)*/; regexp.max = 1000000; ``` # Bad Regular Expressions There are some regular expressions which can never match any string. * Ones with badly placed positionals such as `/a^/` and `/$c/m`. Randexp will ignore positional tokens. * Back references to non-existing groups like `/(a)\1\2/`. Randexp will ignore those references, returning an empty string for them. If the group exists only after the reference is used such as in `/\1 (hey)/`, it will too be ignored. * Custom negated character sets with two sets inside that cancel each other out. Example: `/[^\w\W]/`. If you give this to randexp, it will return an empty string for this set since it can't match anything. # Projects based on randexp.js ## JSON-Schema Faker Use generators to populate JSON Schema samples. See: [jsf on github](https://github.com/json-schema-faker/json-schema-faker/) and [jsf demo page](http://json-schema-faker.js.org/). # Install ### Node.js npm install randexp ### Browser Download the [minified version](https://github.com/fent/randexp.js/releases) from the latest release. # Tests Tests are written with [mocha](https://mochajs.org) ```bash npm test ``` # License MIT # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # lodash.sortby v4.7.0 The [lodash](https://lodash.com/) method `_.sortBy` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.sortby ``` In Node.js: ```js var sortBy = require('lodash.sortby'); ``` See the [documentation](https://lodash.com/docs#sortBy) or [package source](https://github.com/lodash/lodash/blob/4.7.0-npm-packages/lodash.sortby) for more details. Railroad-diagram Generator ========================== This is a small js library for generating railroad diagrams (like what [JSON.org](http://json.org) uses) using SVG. Railroad diagrams are a way of visually representing a grammar in a form that is more readable than using regular expressions or BNF. I think (though I haven't given it a lot of thought yet) that if it's easy to write a context-free grammar for the language, the corresponding railroad diagram will be easy as well. There are several railroad-diagram generators out there, but none of them had the visual appeal I wanted. [Here's an example of how they look!](http://www.xanthir.com/etc/railroad-diagrams/example.html) And [here's an online generator for you to play with and get SVG code from!](http://www.xanthir.com/etc/railroad-diagrams/generator.html) The library now exists in a Python port as well! See the information further down. Details ------- To use the library, just include the js and css files, and then call the Diagram() function. Its arguments are the components of the diagram (Diagram is a special form of Sequence). An alternative to Diagram() is ComplexDiagram() which is used to describe a complex type diagram. Components are either leaves or containers. The leaves: * Terminal(text) or a bare string - represents literal text * NonTerminal(text) - represents an instruction or another production * Comment(text) - a comment * Skip() - an empty line The containers: * Sequence(children) - like simple concatenation in a regex * Choice(index, children) - like | in a regex. The index argument specifies which child is the "normal" choice and should go in the middle * Optional(child, skip) - like ? in a regex. A shorthand for `Choice(1, [Skip(), child])`. If the optional `skip` parameter has the value `"skip"`, it instead puts the Skip() in the straight-line path, for when the "normal" behavior is to omit the item. * OneOrMore(child, repeat) - like + in a regex. The 'repeat' argument is optional, and specifies something that must go between the repetitions. * ZeroOrMore(child, repeat, skip) - like * in a regex. A shorthand for `Optional(OneOrMore(child, repeat))`. The optional `skip` parameter is identical to Optional(). For convenience, each component can be called with or without `new`. If called without `new`, the container components become n-ary; that is, you can say either `new Sequence([A, B])` or just `Sequence(A,B)`. After constructing a Diagram, call `.format(...padding)` on it, specifying 0-4 padding values (just like CSS) for some additional "breathing space" around the diagram (the paddings default to 20px). The result can either be `.toString()`'d for the markup, or `.toSVG()`'d for an `<svg>` element, which can then be immediately inserted to the document. As a convenience, Diagram also has an `.addTo(element)` method, which immediately converts it to SVG and appends it to the referenced element with default paddings. `element` defaults to `document.body`. Options ------- There are a few options you can tweak, at the bottom of the file. Just tweak either until the diagram looks like what you want. You can also change the CSS file - feel free to tweak to your heart's content. Note, though, that if you change the text sizes in the CSS, you'll have to go adjust the metrics for the leaf nodes as well. * VERTICAL_SEPARATION - sets the minimum amount of vertical separation between two items. Note that the stroke width isn't counted when computing the separation; this shouldn't be relevant unless you have a very small separation or very large stroke width. * ARC_RADIUS - the radius of the arcs used in the branching containers like Choice. This has a relatively large effect on the size of non-trivial diagrams. Both tight and loose values look good, depending on what you're going for. * DIAGRAM_CLASS - the class set on the root `<svg>` element of each diagram, for use in the CSS stylesheet. * STROKE_ODD_PIXEL_LENGTH - the default stylesheet uses odd pixel lengths for 'stroke'. Due to rasterization artifacts, they look best when the item has been translated half a pixel in both directions. If you change the styling to use a stroke with even pixel lengths, you'll want to set this variable to `false`. * INTERNAL_ALIGNMENT - when some branches of a container are narrower than others, this determines how they're aligned in the extra space. Defaults to "center", but can be set to "left" or "right". Caveats ------- At this early stage, the generator is feature-complete and works as intended, but still has several TODOs: * The font-sizes are hard-coded right now, and the font handling in general is very dumb - I'm just guessing at some metrics that are probably "good enough" rather than measuring things properly. Python Port ----------- In addition to the canonical JS version, the library now exists as a Python library as well. Using it is basically identical. The config variables are globals in the file, and so may be adjusted either manually or via tweaking from inside your program. The main difference from the JS port is how you extract the string from the Diagram. You'll find a `writeSvg(writerFunc)` method on `Diagram`, which takes a callback of one argument and passes it the string form of the diagram. For example, it can be used like `Diagram(...).writeSvg(sys.stdout.write)` to write to stdout. **Note**: the callback will be called multiple times as it builds up the string, not just once with the whole thing. If you need it all at once, consider something like a `StringIO` as an easy way to collect it into a single string. License ------- This document and all associated files in the github project are licensed under [CC0](http://creativecommons.org/publicdomain/zero/1.0/) ![](http://i.creativecommons.org/p/zero/1.0/80x15.png). This means you can reuse, remix, or otherwise appropriate this project for your own use **without restriction**. (The actual legal meaning can be found at the above link.) Don't ask me for permission to use any part of this project, **just use it**. I would appreciate attribution, but that is not required by the license. binaryen.js =========== **binaryen.js** is a port of [Binaryen](https://github.com/WebAssembly/binaryen) to the Web, allowing you to generate [WebAssembly](https://webassembly.org) using a JavaScript API. <a href="https://github.com/AssemblyScript/binaryen.js/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/binaryen.js/Build/master?label=build&logo=github" alt="Build status" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen.svg?label=latest&color=007acc&logo=npm" alt="npm version" /></a> <a href="https://www.npmjs.com/package/binaryen"><img src="https://img.shields.io/npm/v/binaryen/nightly.svg?label=nightly&color=007acc&logo=npm" alt="npm nightly version" /></a> Usage ----- ``` $> npm install binaryen ``` ```js var binaryen = require("binaryen"); // Create a module with a single function var myModule = new binaryen.Module(); myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ], myModule.block(null, [ myModule.local.set(2, myModule.i32.add( myModule.local.get(0, binaryen.i32), myModule.local.get(1, binaryen.i32) ) ), myModule.return( myModule.local.get(2, binaryen.i32) ) ]) ); myModule.addFunctionExport("add", "add"); // Optimize the module using default passes and levels myModule.optimize(); // Validate the module if (!myModule.validate()) throw new Error("validation error"); // Generate text format and binary var textData = myModule.emitText(); var wasmData = myModule.emitBinary(); // Example usage with the WebAssembly API var compiled = new WebAssembly.Module(wasmData); var instance = new WebAssembly.Instance(compiled, {}); console.log(instance.exports.add(41, 1)); ``` The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through ``` $> npm install binaryen@nightly ``` or you can use one of the [previous versions](https://github.com/AssemblyScript/binaryen.js/tags) instead if necessary. ### Usage with a CDN * From GitHub via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js` * From npm via [jsDelivr](https://www.jsdelivr.com):<br /> `https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js` * From npm via [unpkg](https://unpkg.com):<br /> `https://unpkg.com/binaryen@VERSION/index.js` Replace `VERSION` with a [specific version](https://github.com/AssemblyScript/binaryen.js/releases) or omit it (not recommended in production) to use master/latest. API --- **Please note** that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating [index.d.ts](./index.d.ts) and [README.md](./README.md) to reflect the [current API](https://github.com/WebAssembly/binaryen/blob/master/src/js/binaryen.js-post.js). <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ### Contents - [Types](#types) - [Module construction](#module-construction) - [Module manipulation](#module-manipulation) - [Module validation](#module-validation) - [Module optimization](#module-optimization) - [Module creation](#module-creation) - [Expression construction](#expression-construction) - [Control flow](#control-flow) - [Variable accesses](#variable-accesses) - [Integer operations](#integer-operations) - [Floating point operations](#floating-point-operations) - [Datatype conversions](#datatype-conversions) - [Function calls](#function-calls) - [Linear memory accesses](#linear-memory-accesses) - [Host operations](#host-operations) - [Vector operations 🦄](#vector-operations-) - [Atomic memory accesses 🦄](#atomic-memory-accesses-) - [Atomic read-modify-write operations 🦄](#atomic-read-modify-write-operations-) - [Atomic wait and notify operations 🦄](#atomic-wait-and-notify-operations-) - [Sign extension operations 🦄](#sign-extension-operations-) - [Multi-value operations 🦄](#multi-value-operations-) - [Exception handling operations 🦄](#exception-handling-operations-) - [Reference types operations 🦄](#reference-types-operations-) - [Expression manipulation](#expression-manipulation) - [Relooper](#relooper) - [Source maps](#source-maps) - [Debugging](#debugging) <!-- END doctoc generated TOC please keep comment here to allow auto update --> [Future features](http://webassembly.org/docs/future-features/) 🦄 might not be supported by all runtimes. ### Types * **none**: `Type`<br /> The none type, e.g., `void`. * **i32**: `Type`<br /> 32-bit integer type. * **i64**: `Type`<br /> 64-bit integer type. * **f32**: `Type`<br /> 32-bit float type. * **f64**: `Type`<br /> 64-bit float (double) type. * **v128**: `Type`<br /> 128-bit vector type. 🦄 * **funcref**: `Type`<br /> A function reference. 🦄 * **anyref**: `Type`<br /> Any host reference. 🦄 * **nullref**: `Type`<br /> A null reference. 🦄 * **exnref**: `Type`<br /> An exception reference. 🦄 * **unreachable**: `Type`<br /> Special type indicating unreachable code when obtaining information about an expression. * **auto**: `Type`<br /> Special type used in **Module#block** exclusively. Lets the API figure out a block's result type automatically. * **createType**(types: `Type[]`): `Type`<br /> Creates a multi-value type from an array of types. * **expandType**(type: `Type`): `Type[]`<br /> Expands a multi-value type to an array of types. ### Module construction * new **Module**()<br /> Constructs a new module. * **parseText**(text: `string`): `Module`<br /> Creates a module from Binaryen's s-expression text format (not official stack-style text format). * **readBinary**(data: `Uint8Array`): `Module`<br /> Creates a module from binary data. ### Module manipulation * Module#**addFunction**(name: `string`, params: `Type`, results: `Type`, vars: `Type[]`, body: `ExpressionRef`): `FunctionRef`<br /> Adds a function. `vars` indicate additional locals, in the given order. * Module#**getFunction**(name: `string`): `FunctionRef`<br /> Gets a function, by name, * Module#**removeFunction**(name: `string`): `void`<br /> Removes a function, by name. * Module#**getNumFunctions**(): `number`<br /> Gets the number of functions within the module. * Module#**getFunctionByIndex**(index: `number`): `FunctionRef`<br /> Gets the function at the specified index. * Module#**addFunctionImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, params: `Type`, results: `Type`): `void`<br /> Adds a function import. * Module#**addTableImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a table import. There's just one table for now, using name `"0"`. * Module#**addMemoryImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`): `void`<br /> Adds a memory import. There's just one memory for now, using name `"0"`. * Module#**addGlobalImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, globalType: `Type`): `void`<br /> Adds a global variable import. Imported globals must be immutable. * Module#**addFunctionExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a function export. * Module#**addTableExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a table export. There's just one table for now, using name `"0"`. * Module#**addMemoryExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a memory export. There's just one memory for now, using name `"0"`. * Module#**addGlobalExport**(internalName: `string`, externalName: `string`): `ExportRef`<br /> Adds a global variable export. Exported globals must be immutable. * Module#**getNumExports**(): `number`<br /> Gets the number of exports witin the module. * Module#**getExportByIndex**(index: `number`): `ExportRef`<br /> Gets the export at the specified index. * Module#**removeExport**(externalName: `string`): `void`<br /> Removes an export, by external name. * Module#**addGlobal**(name: `string`, type: `Type`, mutable: `number`, value: `ExpressionRef`): `GlobalRef`<br /> Adds a global instance variable. * Module#**getGlobal**(name: `string`): `GlobalRef`<br /> Gets a global, by name, * Module#**removeGlobal**(name: `string`): `void`<br /> Removes a global, by name. * Module#**setFunctionTable**(initial: `number`, maximum: `number`, funcs: `string[]`, offset?: `ExpressionRef`): `void`<br /> Sets the contents of the function table. There's just one table for now, using name `"0"`. * Module#**getFunctionTable**(): `{ imported: boolean, segments: TableElement[] }`<br /> Gets the contents of the function table. * TableElement#**offset**: `ExpressionRef` * TableElement#**names**: `string[]` * Module#**setMemory**(initial: `number`, maximum: `number`, exportName: `string | null`, segments: `MemorySegment[]`, flags?: `number[]`, shared?: `boolean`): `void`<br /> Sets the memory. There's just one memory for now, using name `"0"`. Providing `exportName` also creates a memory export. * MemorySegment#**offset**: `ExpressionRef` * MemorySegment#**data**: `Uint8Array` * MemorySegment#**passive**: `boolean` * Module#**getNumMemorySegments**(): `number`<br /> Gets the number of memory segments within the module. * Module#**getMemorySegmentInfoByIndex**(index: `number`): `MemorySegmentInfo`<br /> Gets information about the memory segment at the specified index. * MemorySegmentInfo#**offset**: `number` * MemorySegmentInfo#**data**: `Uint8Array` * MemorySegmentInfo#**passive**: `boolean` * Module#**setStart**(start: `FunctionRef`): `void`<br /> Sets the start function. * Module#**getFeatures**(): `Features`<br /> Gets the WebAssembly features enabled for this module. Note that the return value may be a bitmask indicating multiple features. Possible feature flags are: * Features.**MVP**: `Features` * Features.**Atomics**: `Features` * Features.**BulkMemory**: `Features` * Features.**MutableGlobals**: `Features` * Features.**NontrappingFPToInt**: `Features` * Features.**SignExt**: `Features` * Features.**SIMD128**: `Features` * Features.**ExceptionHandling**: `Features` * Features.**TailCall**: `Features` * Features.**ReferenceTypes**: `Features` * Features.**Multivalue**: `Features` * Features.**All**: `Features` * Module#**setFeatures**(features: `Features`): `void`<br /> Sets the WebAssembly features enabled for this module. * Module#**addCustomSection**(name: `string`, contents: `Uint8Array`): `void`<br /> Adds a custom section to the binary. * Module#**autoDrop**(): `void`<br /> Enables automatic insertion of `drop` operations where needed. Lets you not worry about dropping when creating your code. * **getFunctionInfo**(ftype: `FunctionRef`: `FunctionInfo`<br /> Obtains information about a function. * FunctionInfo#**name**: `string` * FunctionInfo#**module**: `string | null` (if imported) * FunctionInfo#**base**: `string | null` (if imported) * FunctionInfo#**params**: `Type` * FunctionInfo#**results**: `Type` * FunctionInfo#**vars**: `Type` * FunctionInfo#**body**: `ExpressionRef` * **getGlobalInfo**(global: `GlobalRef`): `GlobalInfo`<br /> Obtains information about a global. * GlobalInfo#**name**: `string` * GlobalInfo#**module**: `string | null` (if imported) * GlobalInfo#**base**: `string | null` (if imported) * GlobalInfo#**type**: `Type` * GlobalInfo#**mutable**: `boolean` * GlobalInfo#**init**: `ExpressionRef` * **getExportInfo**(export_: `ExportRef`): `ExportInfo`<br /> Obtains information about an export. * ExportInfo#**kind**: `ExternalKind` * ExportInfo#**name**: `string` * ExportInfo#**value**: `string` Possible `ExternalKind` values are: * **ExternalFunction**: `ExternalKind` * **ExternalTable**: `ExternalKind` * **ExternalMemory**: `ExternalKind` * **ExternalGlobal**: `ExternalKind` * **ExternalEvent**: `ExternalKind` * **getEventInfo**(event: `EventRef`): `EventInfo`<br /> Obtains information about an event. * EventInfo#**name**: `string` * EventInfo#**module**: `string | null` (if imported) * EventInfo#**base**: `string | null` (if imported) * EventInfo#**attribute**: `number` * EventInfo#**params**: `Type` * EventInfo#**results**: `Type` * **getSideEffects**(expr: `ExpressionRef`, features: `FeatureFlags`): `SideEffects`<br /> Gets the side effects of the specified expression. * SideEffects.**None**: `SideEffects` * SideEffects.**Branches**: `SideEffects` * SideEffects.**Calls**: `SideEffects` * SideEffects.**ReadsLocal**: `SideEffects` * SideEffects.**WritesLocal**: `SideEffects` * SideEffects.**ReadsGlobal**: `SideEffects` * SideEffects.**WritesGlobal**: `SideEffects` * SideEffects.**ReadsMemory**: `SideEffects` * SideEffects.**WritesMemory**: `SideEffects` * SideEffects.**ImplicitTrap**: `SideEffects` * SideEffects.**IsAtomic**: `SideEffects` * SideEffects.**Throws**: `SideEffects` * SideEffects.**Any**: `SideEffects` ### Module validation * Module#**validate**(): `boolean`<br /> Validates the module. Returns `true` if valid, otherwise prints validation errors and returns `false`. ### Module optimization * Module#**optimize**(): `void`<br /> Optimizes the module using the default optimization passes. * Module#**optimizeFunction**(func: `FunctionRef | string`): `void`<br /> Optimizes a single function using the default optimization passes. * Module#**runPasses**(passes: `string[]`): `void`<br /> Runs the specified passes on the module. * Module#**runPassesOnFunction**(func: `FunctionRef | string`, passes: `string[]`): `void`<br /> Runs the specified passes on a single function. * **getOptimizeLevel**(): `number`<br /> Gets the currently set optimize level. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **setOptimizeLevel**(level: `number`): `void`<br /> Sets the optimization level to use. `0`, `1`, `2` correspond to `-O0`, `-O1`, `-O2` (default), etc. * **getShrinkLevel**(): `number`<br /> Gets the currently set shrink level. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **setShrinkLevel**(level: `number`): `void`<br /> Sets the shrink level to use. `0`, `1`, `2` correspond to `-O0`, `-Os` (default), `-Oz`. * **getDebugInfo**(): `boolean`<br /> Gets whether generating debug information is currently enabled or not. * **setDebugInfo**(on: `boolean`): `void`<br /> Enables or disables debug information in emitted binaries. * **getLowMemoryUnused**(): `boolean`<br /> Gets whether the low 1K of memory can be considered unused when optimizing. * **setLowMemoryUnused**(on: `boolean`): `void`<br /> Enables or disables whether the low 1K of memory can be considered unused when optimizing. * **getPassArgument**(key: `string`): `string | null`<br /> Gets the value of the specified arbitrary pass argument. * **setPassArgument**(key: `string`, value: `string | null`): `void`<br /> Sets the value of the specified arbitrary pass argument. Removes the respective argument if `value` is `null`. * **clearPassArguments**(): `void`<br /> Clears all arbitrary pass arguments. * **getAlwaysInlineMaxSize**(): `number`<br /> Gets the function size at which we always inline. * **setAlwaysInlineMaxSize**(size: `number`): `void`<br /> Sets the function size at which we always inline. * **getFlexibleInlineMaxSize**(): `number`<br /> Gets the function size which we inline when functions are lightweight. * **setFlexibleInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when functions are lightweight. * **getOneCallerInlineMaxSize**(): `number`<br /> Gets the function size which we inline when there is only one caller. * **setOneCallerInlineMaxSize**(size: `number`): `void`<br /> Sets the function size which we inline when there is only one caller. ### Module creation * Module#**emitBinary**(): `Uint8Array`<br /> Returns the module in binary format. * Module#**emitBinary**(sourceMapUrl: `string | null`): `BinaryWithSourceMap`<br /> Returns the module in binary format with its source map. If `sourceMapUrl` is `null`, source map generation is skipped. * BinaryWithSourceMap#**binary**: `Uint8Array` * BinaryWithSourceMap#**sourceMap**: `string | null` * Module#**emitText**(): `string`<br /> Returns the module in Binaryen's s-expression text format (not official stack-style text format). * Module#**emitAsmjs**(): `string`<br /> Returns the [asm.js](http://asmjs.org/) representation of the module. * Module#**dispose**(): `void`<br /> Releases the resources held by the module once it isn't needed anymore. ### Expression construction #### [Control flow](http://webassembly.org/docs/semantics/#control-constructs-and-instructions) * Module#**block**(label: `string | null`, children: `ExpressionRef[]`, resultType?: `Type`): `ExpressionRef`<br /> Creates a block. `resultType` defaults to `none`. * Module#**if**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse?: `ExpressionRef`): `ExpressionRef`<br /> Creates an if or if/else combination. * Module#**loop**(label: `string | null`, body: `ExpressionRef`): `ExpressionRef`<br /> Creates a loop. * Module#**br**(label: `string`, condition?: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a branch (br) to a label. * Module#**switch**(labels: `string[]`, defaultLabel: `string`, condition: `ExpressionRef`, value?: `ExpressionRef`): `ExpressionRef`<br /> Creates a switch (br_table). * Module#**nop**(): `ExpressionRef`<br /> Creates a no-operation (nop) instruction. * Module#**return**(value?: `ExpressionRef`): `ExpressionRef` Creates a return. * Module#**unreachable**(): `ExpressionRef`<br /> Creates an [unreachable](http://webassembly.org/docs/semantics/#unreachable) instruction that will always trap. * Module#**drop**(value: `ExpressionRef`): `ExpressionRef`<br /> Creates a [drop](http://webassembly.org/docs/semantics/#type-parametric-operators) of a value. * Module#**select**(condition: `ExpressionRef`, ifTrue: `ExpressionRef`, ifFalse: `ExpressionRef`, type?: `Type`): `ExpressionRef`<br /> Creates a [select](http://webassembly.org/docs/semantics/#type-parametric-operators) of one of two values. #### [Variable accesses](http://webassembly.org/docs/semantics/#local-variables) * Module#**local.get**(index: `number`, type: `Type`): `ExpressionRef`<br /> Creates a local.get for the local at the specified index. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**local.set**(index: `number`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a local.set for the local at the specified index. * Module#**local.tee**(index: `number`, value: `ExpressionRef`, type: `Type`): `ExpressionRef`<br /> Creates a local.tee for the local at the specified index. A tee differs from a set in that the value remains on the stack. Note that we must specify the type here as we may not have created the local being accessed yet. * Module#**global.get**(name: `string`, type: `Type`): `ExpressionRef`<br /> Creates a global.get for the global with the specified name. Note that we must specify the type here as we may not have created the global being accessed yet. * Module#**global.set**(name: `string`, value: `ExpressionRef`): `ExpressionRef`<br /> Creates a global.set for the global with the specified name. #### [Integer operations](http://webassembly.org/docs/semantics/#32-bit-integer-operators) * Module#i32.**const**(value: `number`): `ExpressionRef` * Module#i32.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i64.**const**(low: `number`, high: `number`): `ExpressionRef` * Module#i64.**clz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**ctz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**popcnt**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**eqz**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**div_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rem_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**shr_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotl**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**rotr**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**le_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Floating point operations](http://webassembly.org/docs/semantics/#floating-point-operators) * Module#f32.**const**(value: `number`): `ExpressionRef` * Module#f32.**const_bits**(value: `number`): `ExpressionRef` * Module#f32.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#f64.**const**(value: `number`): `ExpressionRef` * Module#f64.**const_bits**(value: `number`): `ExpressionRef` * Module#f64.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**ceil**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**floor**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**trunc**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**nearest**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**copysign**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` #### [Datatype conversions](http://webassembly.org/docs/semantics/#datatype-conversions-truncations-reinterpretations-promotions-and-demotions) * Module#i32.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**wrap**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**trunc_s.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_s.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f32**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**trunc_u.f64**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f32.**demote**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**reinterpret**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_s.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i32**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**convert_u.i64**(value: `ExpressionRef`): `ExpressionRef` * Module#f64.**promote**(value: `ExpressionRef`): `ExpressionRef` #### [Function calls](http://webassembly.org/docs/semantics/#calls) * Module#**call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef` Creates a call to a function. Note that we must specify the return type here as we may not have created the function being called yet. * Module#**return_call**(name: `string`, operands: `ExpressionRef[]`, returnType: `Type`): `ExpressionRef`<br /> Like **call**, but creates a tail-call. 🦄 * Module#**call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Similar to **call**, but calls indirectly, i.e., via a function pointer, so an expression replaces the name as the called value. * Module#**return_call_indirect**(target: `ExpressionRef`, operands: `ExpressionRef[]`, params: `Type`, results: `Type`): `ExpressionRef`<br /> Like **call_indirect**, but creates a tail-call. 🦄 #### [Linear memory accesses](http://webassembly.org/docs/semantics/#linear-memory-accesses) * Module#i32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> * Module#i32.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef`<br /> > * Module#i64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load16_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**load32_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store8**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store16**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**store32**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f32.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f32.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#f64.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#f64.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Host operations](http://webassembly.org/docs/semantics/#resizing) * Module#**memory.size**(): `ExpressionRef` * Module#**memory.grow**(value: `number`): `ExpressionRef` #### [Vector operations](https://github.com/WebAssembly/simd/blob/master/proposals/simd/SIMD.md) 🦄 * Module#v128.**const**(bytes: `Uint8Array`): `ExpressionRef` * Module#v128.**load**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#v128.**store**(offset: `number`, align: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#v128.**not**(value: `ExpressionRef`): `ExpressionRef` * Module#v128.**and**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**or**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**xor**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**andnot**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v128.**bitselect**(left: `ExpressionRef`, right: `ExpressionRef`, cond: `ExpressionRef`): `ExpressionRef` > * Module#i8x16.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i8x16.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i8x16.**narrow_i16x8_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` > * Module#i16x8.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i16x8.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**add_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**sub_saturate_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**avgr_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**narrow_i32x4_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_low_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**widen_high_i8x16_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i16x8.**load8x8_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**gt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**le_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**lt_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**ge_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**min_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**max_u**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**dot_i16x8_s**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**trunc_sat_f32x4_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_low_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**widen_high_i16x8_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32x4.**load16x4_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#i64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**extract_lane_s**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**extract_lane_u**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#i64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**any_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**all_true**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shl**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_s**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**shr_u**(vec: `ExpressionRef`, shift: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**trunc_sat_f64x2_u**(value: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_s**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64x2.**load32x2_u**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#f32x4.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f32x4.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f32x4.**convert_i32x4_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#f64x2.**splat**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**extract_lane**(vec: `ExpressionRef`, index: `number`): `ExpressionRef` * Module#f64x2.**replace_lane**(vec: `ExpressionRef`, index: `number`, value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**eq**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ne**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**lt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**gt**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**le**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**ge**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**abs**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**neg**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sqrt**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfma**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**qfms**(a: `ExpressionRef`, b: `ExpressionRef`, c: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**add**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**sub**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**mul**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**div**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**min**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**max**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_s**(value: `ExpressionRef`): `ExpressionRef` * Module#f64x2.**convert_i64x2_u**(value: `ExpressionRef`): `ExpressionRef` > * Module#v8x16.**shuffle**(left: `ExpressionRef`, right: `ExpressionRef`, mask: `Uint8Array`): `ExpressionRef` * Module#v8x16.**swizzle**(left: `ExpressionRef`, right: `ExpressionRef`): `ExpressionRef` * Module#v8x16.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v16x8.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v32x4.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` > * Module#v64x2.**load_splat**(offset: `number`, align: `number`, ptr: `ExpressionRef`): `ExpressionRef` #### [Atomic memory accesses](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses) 🦄 * Module#i32.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.load**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load8_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load16_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.load32_u**(offset: `number`, ptr: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store8**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store16**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.store32**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` #### [Atomic read-modify-write operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#read-modify-write) 🦄 * Module#i32.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i32.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` > * Module#i64.**atomic.rmw.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw8_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw16_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.add**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.sub**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.and**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.or**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xor**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.xchg**(offset: `number`, ptr: `ExpressionRef`, value: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.rmw32_u.cmpxchg**(offset: `number`, ptr: `ExpressionRef`, expected: `ExpressionRef`, replacement: `ExpressionRef`): `ExpressionRef` #### [Atomic wait and notify operations](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#wait-and-notify-operators) 🦄 * Module#i32.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#i64.**atomic.wait**(ptr: `ExpressionRef`, expected: `ExpressionRef`, timeout: `ExpressionRef`): `ExpressionRef` * Module#**atomic.notify**(ptr: `ExpressionRef`, notifyCount: `ExpressionRef`): `ExpressionRef` * Module#**atomic.fence**(): `ExpressionRef` #### [Sign extension operations](https://github.com/WebAssembly/sign-extension-ops/blob/master/proposals/sign-extension-ops/Overview.md) 🦄 * Module#i32.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` > * Module#i64.**extend8_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend16_s**(value: `ExpressionRef`): `ExpressionRef` * Module#i64.**extend32_s**(value: `ExpressionRef`): `ExpressionRef` #### [Multi-value operations](https://github.com/WebAssembly/multi-value/blob/master/proposals/multi-value/Overview.md) 🦄 Note that these are pseudo instructions enabling Binaryen to reason about multiple values on the stack. * Module#**push**(value: `ExpressionRef`): `ExpressionRef` * Module#i32.**pop**(): `ExpressionRef` * Module#i64.**pop**(): `ExpressionRef` * Module#f32.**pop**(): `ExpressionRef` * Module#f64.**pop**(): `ExpressionRef` * Module#v128.**pop**(): `ExpressionRef` * Module#funcref.**pop**(): `ExpressionRef` * Module#anyref.**pop**(): `ExpressionRef` * Module#nullref.**pop**(): `ExpressionRef` * Module#exnref.**pop**(): `ExpressionRef` * Module#tuple.**make**(elements: `ExpressionRef[]`): `ExpressionRef` * Module#tuple.**extract**(tuple: `ExpressionRef`, index: `number`): `ExpressionRef` #### [Exception handling operations](https://github.com/WebAssembly/exception-handling/blob/master/proposals/Exceptions.md) 🦄 * Module#**try**(body: `ExpressionRef`, catchBody: `ExpressionRef`): `ExpressionRef` * Module#**throw**(event: `string`, operands: `ExpressionRef[]`): `ExpressionRef` * Module#**rethrow**(exnref: `ExpressionRef`): `ExpressionRef` * Module#**br_on_exn**(label: `string`, event: `string`, exnref: `ExpressionRef`): `ExpressionRef` > * Module#**addEvent**(name: `string`, attribute: `number`, params: `Type`, results: `Type`): `Event` * Module#**getEvent**(name: `string`): `Event` * Module#**removeEvent**(name: `stirng`): `void` * Module#**addEventImport**(internalName: `string`, externalModuleName: `string`, externalBaseName: `string`, attribute: `number`, params: `Type`, results: `Type`): `void` * Module#**addEventExport**(internalName: `string`, externalName: `string`): `ExportRef` #### [Reference types operations](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) 🦄 * Module#ref.**null**(): `ExpressionRef` * Module#ref.**is_null**(value: `ExpressionRef`): `ExpressionRef` * Module#ref.**func**(name: `string`): `ExpressionRef` ### Expression manipulation * **getExpressionId**(expr: `ExpressionRef`): `ExpressionId`<br /> Gets the id (kind) of the specified expression. Possible values are: * **InvalidId**: `ExpressionId` * **BlockId**: `ExpressionId` * **IfId**: `ExpressionId` * **LoopId**: `ExpressionId` * **BreakId**: `ExpressionId` * **SwitchId**: `ExpressionId` * **CallId**: `ExpressionId` * **CallIndirectId**: `ExpressionId` * **LocalGetId**: `ExpressionId` * **LocalSetId**: `ExpressionId` * **GlobalGetId**: `ExpressionId` * **GlobalSetId**: `ExpressionId` * **LoadId**: `ExpressionId` * **StoreId**: `ExpressionId` * **ConstId**: `ExpressionId` * **UnaryId**: `ExpressionId` * **BinaryId**: `ExpressionId` * **SelectId**: `ExpressionId` * **DropId**: `ExpressionId` * **ReturnId**: `ExpressionId` * **HostId**: `ExpressionId` * **NopId**: `ExpressionId` * **UnreachableId**: `ExpressionId` * **AtomicCmpxchgId**: `ExpressionId` * **AtomicRMWId**: `ExpressionId` * **AtomicWaitId**: `ExpressionId` * **AtomicNotifyId**: `ExpressionId` * **AtomicFenceId**: `ExpressionId` * **SIMDExtractId**: `ExpressionId` * **SIMDReplaceId**: `ExpressionId` * **SIMDShuffleId**: `ExpressionId` * **SIMDTernaryId**: `ExpressionId` * **SIMDShiftId**: `ExpressionId` * **SIMDLoadId**: `ExpressionId` * **MemoryInitId**: `ExpressionId` * **DataDropId**: `ExpressionId` * **MemoryCopyId**: `ExpressionId` * **MemoryFillId**: `ExpressionId` * **RefNullId**: `ExpressionId` * **RefIsNullId**: `ExpressionId` * **RefFuncId**: `ExpressionId` * **TryId**: `ExpressionId` * **ThrowId**: `ExpressionId` * **RethrowId**: `ExpressionId` * **BrOnExnId**: `ExpressionId` * **PushId**: `ExpressionId` * **PopId**: `ExpressionId` * **getExpressionType**(expr: `ExpressionRef`): `Type`<br /> Gets the type of the specified expression. * **getExpressionInfo**(expr: `ExpressionRef`): `ExpressionInfo`<br /> Obtains information about an expression, always including: * Info#**id**: `ExpressionId` * Info#**type**: `Type` Additional properties depend on the expression's `id` and are usually equivalent to the respective parameters when creating such an expression: * BlockInfo#**name**: `string` * BlockInfo#**children**: `ExpressionRef[]` > * IfInfo#**condition**: `ExpressionRef` * IfInfo#**ifTrue**: `ExpressionRef` * IfInfo#**ifFalse**: `ExpressionRef | null` > * LoopInfo#**name**: `string` * LoopInfo#**body**: `ExpressionRef` > * BreakInfo#**name**: `string` * BreakInfo#**condition**: `ExpressionRef | null` * BreakInfo#**value**: `ExpressionRef | null` > * SwitchInfo#**names**: `string[]` * SwitchInfo#**defaultName**: `string | null` * SwitchInfo#**condition**: `ExpressionRef` * SwitchInfo#**value**: `ExpressionRef | null` > * CallInfo#**target**: `string` * CallInfo#**operands**: `ExpressionRef[]` > * CallImportInfo#**target**: `string` * CallImportInfo#**operands**: `ExpressionRef[]` > * CallIndirectInfo#**target**: `ExpressionRef` * CallIndirectInfo#**operands**: `ExpressionRef[]` > * LocalGetInfo#**index**: `number` > * LocalSetInfo#**isTee**: `boolean` * LocalSetInfo#**index**: `number` * LocalSetInfo#**value**: `ExpressionRef` > * GlobalGetInfo#**name**: `string` > * GlobalSetInfo#**name**: `string` * GlobalSetInfo#**value**: `ExpressionRef` > * LoadInfo#**isAtomic**: `boolean` * LoadInfo#**isSigned**: `boolean` * LoadInfo#**offset**: `number` * LoadInfo#**bytes**: `number` * LoadInfo#**align**: `number` * LoadInfo#**ptr**: `ExpressionRef` > * StoreInfo#**isAtomic**: `boolean` * StoreInfo#**offset**: `number` * StoreInfo#**bytes**: `number` * StoreInfo#**align**: `number` * StoreInfo#**ptr**: `ExpressionRef` * StoreInfo#**value**: `ExpressionRef` > * ConstInfo#**value**: `number | { low: number, high: number }` > * UnaryInfo#**op**: `number` * UnaryInfo#**value**: `ExpressionRef` > * BinaryInfo#**op**: `number` * BinaryInfo#**left**: `ExpressionRef` * BinaryInfo#**right**: `ExpressionRef` > * SelectInfo#**ifTrue**: `ExpressionRef` * SelectInfo#**ifFalse**: `ExpressionRef` * SelectInfo#**condition**: `ExpressionRef` > * DropInfo#**value**: `ExpressionRef` > * ReturnInfo#**value**: `ExpressionRef | null` > * NopInfo > * UnreachableInfo > * HostInfo#**op**: `number` * HostInfo#**nameOperand**: `string | null` * HostInfo#**operands**: `ExpressionRef[]` > * AtomicRMWInfo#**op**: `number` * AtomicRMWInfo#**bytes**: `number` * AtomicRMWInfo#**offset**: `number` * AtomicRMWInfo#**ptr**: `ExpressionRef` * AtomicRMWInfo#**value**: `ExpressionRef` > * AtomicCmpxchgInfo#**bytes**: `number` * AtomicCmpxchgInfo#**offset**: `number` * AtomicCmpxchgInfo#**ptr**: `ExpressionRef` * AtomicCmpxchgInfo#**expected**: `ExpressionRef` * AtomicCmpxchgInfo#**replacement**: `ExpressionRef` > * AtomicWaitInfo#**ptr**: `ExpressionRef` * AtomicWaitInfo#**expected**: `ExpressionRef` * AtomicWaitInfo#**timeout**: `ExpressionRef` * AtomicWaitInfo#**expectedType**: `Type` > * AtomicNotifyInfo#**ptr**: `ExpressionRef` * AtomicNotifyInfo#**notifyCount**: `ExpressionRef` > * AtomicFenceInfo > * SIMDExtractInfo#**op**: `Op` * SIMDExtractInfo#**vec**: `ExpressionRef` * SIMDExtractInfo#**index**: `ExpressionRef` > * SIMDReplaceInfo#**op**: `Op` * SIMDReplaceInfo#**vec**: `ExpressionRef` * SIMDReplaceInfo#**index**: `ExpressionRef` * SIMDReplaceInfo#**value**: `ExpressionRef` > * SIMDShuffleInfo#**left**: `ExpressionRef` * SIMDShuffleInfo#**right**: `ExpressionRef` * SIMDShuffleInfo#**mask**: `Uint8Array` > * SIMDTernaryInfo#**op**: `Op` * SIMDTernaryInfo#**a**: `ExpressionRef` * SIMDTernaryInfo#**b**: `ExpressionRef` * SIMDTernaryInfo#**c**: `ExpressionRef` > * SIMDShiftInfo#**op**: `Op` * SIMDShiftInfo#**vec**: `ExpressionRef` * SIMDShiftInfo#**shift**: `ExpressionRef` > * SIMDLoadInfo#**op**: `Op` * SIMDLoadInfo#**offset**: `number` * SIMDLoadInfo#**align**: `number` * SIMDLoadInfo#**ptr**: `ExpressionRef` > * MemoryInitInfo#**segment**: `number` * MemoryInitInfo#**dest**: `ExpressionRef` * MemoryInitInfo#**offset**: `ExpressionRef` * MemoryInitInfo#**size**: `ExpressionRef` > * MemoryDropInfo#**segment**: `number` > * MemoryCopyInfo#**dest**: `ExpressionRef` * MemoryCopyInfo#**source**: `ExpressionRef` * MemoryCopyInfo#**size**: `ExpressionRef` > * MemoryFillInfo#**dest**: `ExpressionRef` * MemoryFillInfo#**value**: `ExpressionRef` * MemoryFillInfo#**size**: `ExpressionRef` > * TryInfo#**body**: `ExpressionRef` * TryInfo#**catchBody**: `ExpressionRef` > * RefNullInfo > * RefIsNullInfo#**value**: `ExpressionRef` > * RefFuncInfo#**func**: `string` > * ThrowInfo#**event**: `string` * ThrowInfo#**operands**: `ExpressionRef[]` > * RethrowInfo#**exnref**: `ExpressionRef` > * BrOnExnInfo#**name**: `string` * BrOnExnInfo#**event**: `string` * BrOnExnInfo#**exnref**: `ExpressionRef` > * PopInfo > * PushInfo#**value**: `ExpressionRef` * **emitText**(expression: `ExpressionRef`): `string`<br /> Emits the expression in Binaryen's s-expression text format (not official stack-style text format). * **copyExpression**(expression: `ExpressionRef`): `ExpressionRef`<br /> Creates a deep copy of an expression. ### Relooper * new **Relooper**()<br /> Constructs a relooper instance. This lets you provide an arbitrary CFG, and the relooper will structure it for WebAssembly. * Relooper#**addBlock**(code: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block to the CFG, containing the provided code as its body. * Relooper#**addBranch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, condition: `ExpressionRef`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block to another block, with a condition (or nothing, if this is the default branch to take from the origin - each block must have one such branch), and optional code to execute on the branch (useful for phis). * Relooper#**addBlockWithSwitch**(code: `ExpressionRef`, condition: `ExpressionRef`): `RelooperBlockRef`<br /> Adds a new block, which ends with a switch/br_table, with provided code and condition (that determines where we go in the switch). * Relooper#**addBranchForSwitch**(from: `RelooperBlockRef`, to: `RelooperBlockRef`, indexes: `number[]`, code: `ExpressionRef`): `void`<br /> Adds a branch from a block ending in a switch, to another block, using an array of indexes that determine where to go, and optional code to execute on the branch. * Relooper#**renderAndDispose**(entry: `RelooperBlockRef`, labelHelper: `number`, module: `Module`): `ExpressionRef`<br /> Renders and cleans up the Relooper instance. Call this after you have created all the blocks and branches, giving it the entry block (where control flow begins), a label helper variable (an index of a local we can use, necessary for irreducible control flow), and the module. This returns an expression - normal WebAssembly code - that you can use normally anywhere. ### Source maps * Module#**addDebugInfoFileName**(filename: `string`): `number`<br /> Adds a debug info file name to the module and returns its index. * Module#**getDebugInfoFileName**(index: `number`): `string | null` <br /> Gets the name of the debug info file at the specified index. * Module#**setDebugLocation**(func: `FunctionRef`, expr: `ExpressionRef`, fileIndex: `number`, lineNumber: `number`, columnNumber: `number`): `void`<br /> Sets the debug location of the specified `ExpressionRef` within the specified `FunctionRef`. ### Debugging * Module#**interpret**(): `void`<br /> Runs the module in the interpreter, calling the start function. # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:https://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation Node.js version 8 and up: `$ npm install cross-spawn` Node.js version 7 and under: `$ npm install cross-spawn@6` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php). # flat-cache > A stupidly simple key/value storage using files to persist the data [![NPM Version](http://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache) [![Build Status](https://api.travis-ci.org/royriojas/flat-cache.svg?branch=master)](https://travis-ci.org/royriojas/flat-cache) ## install ```bash npm i --save flat-cache ``` ## Usage ```js var flatCache = require('flat-cache') // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var cache = flatCache.load('cacheId'); // sets a key on the cache cache.setKey('key', { foo: 'var' }); // get a key from the cache cache.getKey('key') // { foo: 'var' } // fetch the entire persisted object cache.all() // { 'key': { foo: 'var' } } // remove a key cache.removeKey('key'); // removes a key from the cache // save it to disk cache.save(); // very important, if you don't save no changes will be persisted. // cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys // loads the cache from a given directory, if one does // not exists for the given Id a new one will be prepared to be created var cache = flatCache.load('cacheId', path.resolve('./path/to/folder')); // The following methods are useful to clear the cache // delete a given cache flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists. // delete all cache flatCache.clearAll(); // remove the cache directory ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make a script that will beutify files with `esformatter` only execute on the files that were changed since the last run. To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value` storage was needed and Bam! this module was born. ## Important notes - If no directory is especified when the `load` method is called, a folder named `.cache` will be created inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you might want to ignore the default `.cache` folder, or specify a custom directory. - The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references - All the changes to the cache state are done to memory - I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module intentionally dumb and simple - Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call like: `cache.save( true /* noPrune */ )`. ## License MIT ## Changelog [changelog](./changelog.md) # regexpp [![npm version](https://img.shields.io/npm/v/regexpp.svg)](https://www.npmjs.com/package/regexpp) [![Downloads/month](https://img.shields.io/npm/dm/regexpp.svg)](http://www.npmtrends.com/regexpp) [![Build Status](https://github.com/mysticatea/regexpp/workflows/CI/badge.svg)](https://github.com/mysticatea/regexpp/actions) [![codecov](https://codecov.io/gh/mysticatea/regexpp/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/regexpp) [![Dependency Status](https://david-dm.org/mysticatea/regexpp.svg)](https://david-dm.org/mysticatea/regexpp) A regular expression parser for ECMAScript. ## 💿 Installation ```bash $ npm install regexpp ``` - require Node.js 8 or newer. ## 📖 Usage ```ts import { AST, RegExpParser, RegExpValidator, RegExpVisitor, parseRegExpLiteral, validateRegExpLiteral, visitRegExpAST } from "regexpp" ``` ### parseRegExpLiteral(source, options?) Parse a given regular expression literal then make AST object. This is equivalent to `new RegExpParser(options).parseLiteral(source)`. - **Parameters:** - `source` (`string | RegExp`) The source code to parse. - `options?` ([`RegExpParser.Options`]) The options to parse. - **Return:** - The AST of the regular expression. ### validateRegExpLiteral(source, options?) Validate a given regular expression literal. This is equivalent to `new RegExpValidator(options).validateLiteral(source)`. - **Parameters:** - `source` (`string`) The source code to validate. - `options?` ([`RegExpValidator.Options`]) The options to validate. ### visitRegExpAST(ast, handlers) Visit each node of a given AST. This is equivalent to `new RegExpVisitor(handlers).visit(ast)`. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. ### RegExpParser #### new RegExpParser(options?) - **Parameters:** - `options?` ([`RegExpParser.Options`]) The options to parse. #### parser.parseLiteral(source, start?, end?) Parse a regular expression literal. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"/abc/g"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression. #### parser.parsePattern(source, start?, end?, uFlag?) Parse a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"abc"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. - **Return:** - The AST of the regular expression pattern. #### parser.parseFlags(source, start?, end?) Parse a regular expression flags. - **Parameters:** - `source` (`string`) The source code to parse. E.g. `"gim"`. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - **Return:** - The AST of the regular expression flags. ### RegExpValidator #### new RegExpValidator(options) - **Parameters:** - `options` ([`RegExpValidator.Options`]) The options to validate. #### validator.validateLiteral(source, start, end) Validate a regular expression literal. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. #### validator.validatePattern(source, start, end, uFlag) Validate a regular expression pattern. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. - `uFlag?` (`boolean`) The flag to enable Unicode mode. #### validator.validateFlags(source, start, end) Validate a regular expression flags. - **Parameters:** - `source` (`string`) The source code to validate. - `start?` (`number`) The start index in the source code. Default is `0`. - `end?` (`number`) The end index in the source code. Default is `source.length`. ### RegExpVisitor #### new RegExpVisitor(handlers) - **Parameters:** - `handlers` ([`RegExpVisitor.Handlers`]) The callbacks. #### visitor.visit(ast) Validate a regular expression literal. - **Parameters:** - `ast` ([`AST.Node`]) The AST to visit. ## 📰 Changelog - [GitHub Releases](https://github.com/mysticatea/regexpp/releases) ## 🍻 Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`. - `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`. - `npm run lint` runs ESLint. - `npm run update:test` updates test fixtures. - `npm run update:ids` updates `src/unicode/ids.ts`. - `npm run watch` runs tests with `--watch` option. [`AST.Node`]: src/ast.ts#L4 [`RegExpParser.Options`]: src/parser.ts#L539 [`RegExpValidator.Options`]: src/validator.ts#L127 [`RegExpVisitor.Handlers`]: src/visitor.ts#L204 [Build]: http://img.shields.io/travis/litejs/natural-compare-lite.png [Coverage]: http://img.shields.io/coveralls/litejs/natural-compare-lite.png [1]: https://travis-ci.org/litejs/natural-compare-lite [2]: https://coveralls.io/r/litejs/natural-compare-lite [npm package]: https://npmjs.org/package/natural-compare-lite [GitHub repo]: https://github.com/litejs/natural-compare-lite @version 1.4.0 @date 2015-10-26 @stability 3 - Stable Natural Compare &ndash; [![Build][]][1] [![Coverage][]][2] =============== Compare strings containing a mix of letters and numbers in the way a human being would in sort order. This is described as a "natural ordering". ```text Standard sorting: Natural order sorting: img1.png img1.png img10.png img2.png img12.png img10.png img2.png img12.png ``` String.naturalCompare returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. Use it with builtin sort() function. ### Installation - In browser ```html <script src=min.natural-compare.js></script> ``` - In node.js: `npm install natural-compare-lite` ```javascript require("natural-compare-lite") ``` ### Usage ```javascript // Simple case sensitive example var a = ["z1.doc", "z10.doc", "z17.doc", "z2.doc", "z23.doc", "z3.doc"]; a.sort(String.naturalCompare); // ["z1.doc", "z2.doc", "z3.doc", "z10.doc", "z17.doc", "z23.doc"] // Use wrapper function for case insensitivity a.sort(function(a, b){ return String.naturalCompare(a.toLowerCase(), b.toLowerCase()); }) // In most cases we want to sort an array of objects var a = [ {"street":"350 5th Ave", "room":"A-1021"} , {"street":"350 5th Ave", "room":"A-21046-b"} ]; // sort by street, then by room a.sort(function(a, b){ return String.naturalCompare(a.street, b.street) || String.naturalCompare(a.room, b.room); }) // When text transformation is needed (eg toLowerCase()), // it is best for performance to keep // transformed key in that object. // There are no need to do text transformation // on each comparision when sorting. var a = [ {"make":"Audi", "model":"A6"} , {"make":"Kia", "model":"Rio"} ]; // sort by make, then by model a.map(function(car){ car.sort_key = (car.make + " " + car.model).toLowerCase(); }) a.sort(function(a, b){ return String.naturalCompare(a.sort_key, b.sort_key); }) ``` - Works well with dates in ISO format eg "Rev 2012-07-26.doc". ### Custom alphabet It is possible to configure a custom alphabet to achieve a desired order. ```javascript // Estonian alphabet String.alphabet = "ABDEFGHIJKLMNOPRSŠZŽTUVÕÄÖÜXYabdefghijklmnoprsšzžtuvõäöüxy" ["t", "z", "x", "õ"].sort(String.naturalCompare) // ["z", "t", "õ", "x"] // Russian alphabet String.alphabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя" ["Ё", "А", "Б"].sort(String.naturalCompare) // ["А", "Б", "Ё"] ``` External links -------------- - [GitHub repo][https://github.com/litejs/natural-compare-lite] - [jsperf test](http://jsperf.com/natural-sort-2/12) Licence ------- Copyright (c) 2012-2015 Lauri Rooden &lt;[email protected]&gt; [The MIT License](http://lauri.rooden.ee/mit-license.txt) assemblyscript-json # assemblyscript-json ## Table of contents ### Namespaces - [JSON](modules/json.md) ### Classes - [DecoderState](classes/decoderstate.md) - [JSONDecoder](classes/jsondecoder.md) - [JSONEncoder](classes/jsonencoder.md) - [JSONHandler](classes/jsonhandler.md) - [ThrowingJSONHandler](classes/throwingjsonhandler.md) # line-column [![Build Status](https://travis-ci.org/io-monad/line-column.svg?branch=master)](https://travis-ci.org/io-monad/line-column) [![Coverage Status](https://coveralls.io/repos/github/io-monad/line-column/badge.svg?branch=master)](https://coveralls.io/github/io-monad/line-column?branch=master) [![npm version](https://badge.fury.io/js/line-column.svg)](https://badge.fury.io/js/line-column) Node module to convert efficiently index to/from line-column in a string. ## Install npm install line-column ## Usage ### lineColumn(str, options = {}) Returns a `LineColumnFinder` instance for given string `str`. #### Options | Key | Description | Default | | ------- | ----------- | ------- | | `origin` | The origin value of line number and column number | `1` | ### lineColumn(str, index) This is just a shorthand for `lineColumn(str).fromIndex(index)`. ### LineColumnFinder#fromIndex(index) Find line and column from index in the string. Parameters: - `index` - `number` Index in the string. (0-origin) Returns: - `{ line: x, col: y }` Found line number and column number. - `null` if the given index is out of range. ### LineColumnFinder#toIndex(line, column) Find index from line and column in the string. Parameters: - `line` - `number` Line number in the string. - `column` - `number` Column number in the string. or - `{ line: x, col: y }` - `Object` line and column numbers in the string.<br>A key name `column` can be used instead of `col`. or - `[ line, col ]` - `Array` line and column numbers in the string. Returns: - `number` Found index in the string. - `-1` if the given line or column is out of range. ## Example ```js var lineColumn = require("line-column"); var testString = [ "ABCDEFG\n", // line:0, index:0 "HIJKLMNOPQRSTU\n", // line:1, index:8 "VWXYZ\n", // line:2, index:23 "日本語の文字\n", // line:3, index:29 "English words" // line:4, index:36 ].join(""); // length:49 lineColumn(testString).fromIndex(3) // { line: 1, col: 4 } lineColumn(testString).fromIndex(33) // { line: 4, col: 5 } lineColumn(testString).toIndex(1, 4) // 3 lineColumn(testString).toIndex(4, 5) // 33 // Shorthand of .fromIndex (compatible with find-line-column) lineColumn(testString, 33) // { line:4, col: 5 } // Object or Array is also acceptable lineColumn(testString).toIndex({ line: 4, col: 5 }) // 33 lineColumn(testString).toIndex({ line: 4, column: 5 }) // 33 lineColumn(testString).toIndex([4, 5]) // 33 // You can cache it for the same string. It is so efficient. (See benchmark) var finder = lineColumn(testString); finder.fromIndex(33) // { line: 4, column: 5 } finder.toIndex(4, 5) // 33 // For 0-origin line and column numbers var oneOrigin = lineColumn(testString, { origin: 0 }); oneOrigin.fromIndex(33) // { line: 3, column: 4 } oneOrigin.toIndex(3, 4) // 33 ``` ## Testing npm test ## Benchmark The popular package [find-line-column](https://www.npmjs.com/package/find-line-column) provides the same "index to line-column" feature. Here is some benchmarking on `line-column` vs `find-line-column`. You can run this benchmark by `npm run benchmark`. See [benchmark/](benchmark/) for the source code. ``` long text + line-column (not cached) x 72,989 ops/sec ±0.83% (89 runs sampled) long text + line-column (cached) x 13,074,242 ops/sec ±0.32% (89 runs sampled) long text + find-line-column x 33,887 ops/sec ±0.54% (84 runs sampled) short text + line-column (not cached) x 1,636,766 ops/sec ±0.77% (82 runs sampled) short text + line-column (cached) x 21,699,686 ops/sec ±1.04% (82 runs sampled) short text + find-line-column x 382,145 ops/sec ±1.04% (85 runs sampled) ``` As you might have noticed, even not cached version of `line-column` is 2x - 4x faster than `find-line-column`, and cached version of `line-column` is remarkable 50x - 380x faster. ## Contributing 1. Fork it! 2. Create your feature branch: `git checkout -b my-new-feature` 3. Commit your changes: `git commit -am 'Add some feature'` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D ## License MIT (See LICENSE) functional-red-black-tree ========================= A [fully persistent](http://en.wikipedia.org/wiki/Persistent_data_structure) [red-black tree](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) written 100% in JavaScript. Works both in node.js and in the browser via [browserify](http://browserify.org/). Functional (or fully presistent) data structures allow for non-destructive updates. So if you insert an element into the tree, it returns a new tree with the inserted element rather than destructively updating the existing tree in place. Doing this requires using extra memory, and if one were naive it could cost as much as reallocating the entire tree. Instead, this data structure saves some memory by recycling references to previously allocated subtrees. This requires using only O(log(n)) additional memory per update instead of a full O(n) copy. Some advantages of this is that it is possible to apply insertions and removals to the tree while still iterating over previous versions of the tree. Functional and persistent data structures can also be useful in many geometric algorithms like point location within triangulations or ray queries, and can be used to analyze the history of executing various algorithms. This added power though comes at a cost, since it is generally a bit slower to use a functional data structure than an imperative version. However, if your application needs this behavior then you may consider using this module. # Install npm install functional-red-black-tree # Example Here is an example of some basic usage: ```javascript //Load the library var createTree = require("functional-red-black-tree") //Create a tree var t1 = createTree() //Insert some items into the tree var t2 = t1.insert(1, "foo") var t3 = t2.insert(2, "bar") //Remove something var t4 = t3.remove(1) ``` # API ```javascript var createTree = require("functional-red-black-tree") ``` ## Overview - [Tree methods](#tree-methods) - [`var tree = createTree([compare])`](#var-tree-=-createtreecompare) - [`tree.keys`](#treekeys) - [`tree.values`](#treevalues) - [`tree.length`](#treelength) - [`tree.get(key)`](#treegetkey) - [`tree.insert(key, value)`](#treeinsertkey-value) - [`tree.remove(key)`](#treeremovekey) - [`tree.find(key)`](#treefindkey) - [`tree.ge(key)`](#treegekey) - [`tree.gt(key)`](#treegtkey) - [`tree.lt(key)`](#treeltkey) - [`tree.le(key)`](#treelekey) - [`tree.at(position)`](#treeatposition) - [`tree.begin`](#treebegin) - [`tree.end`](#treeend) - [`tree.forEach(visitor(key,value)[, lo[, hi]])`](#treeforEachvisitorkeyvalue-lo-hi) - [`tree.root`](#treeroot) - [Node properties](#node-properties) - [`node.key`](#nodekey) - [`node.value`](#nodevalue) - [`node.left`](#nodeleft) - [`node.right`](#noderight) - [Iterator methods](#iterator-methods) - [`iter.key`](#iterkey) - [`iter.value`](#itervalue) - [`iter.node`](#iternode) - [`iter.tree`](#itertree) - [`iter.index`](#iterindex) - [`iter.valid`](#itervalid) - [`iter.clone()`](#iterclone) - [`iter.remove()`](#iterremove) - [`iter.update(value)`](#iterupdatevalue) - [`iter.next()`](#iternext) - [`iter.prev()`](#iterprev) - [`iter.hasNext`](#iterhasnext) - [`iter.hasPrev`](#iterhasprev) ## Tree methods ### `var tree = createTree([compare])` Creates an empty functional tree * `compare` is an optional comparison function, same semantics as array.sort() **Returns** An empty tree ordered by `compare` ### `tree.keys` A sorted array of all the keys in the tree ### `tree.values` An array array of all the values in the tree ### `tree.length` The number of items in the tree ### `tree.get(key)` Retrieves the value associated to the given key * `key` is the key of the item to look up **Returns** The value of the first node associated to `key` ### `tree.insert(key, value)` Creates a new tree with the new pair inserted. * `key` is the key of the item to insert * `value` is the value of the item to insert **Returns** A new tree with `key` and `value` inserted ### `tree.remove(key)` Removes the first item with `key` in the tree * `key` is the key of the item to remove **Returns** A new tree with the given item removed if it exists ### `tree.find(key)` Returns an iterator pointing to the first item in the tree with `key`, otherwise `null`. ### `tree.ge(key)` Find the first item in the tree whose key is `>= key` * `key` is the key to search for **Returns** An iterator at the given element. ### `tree.gt(key)` Finds the first item in the tree whose key is `> key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.lt(key)` Finds the last item in the tree whose key is `< key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.le(key)` Finds the last item in the tree whose key is `<= key` * `key` is the key to search for **Returns** An iterator at the given element ### `tree.at(position)` Finds an iterator starting at the given element * `position` is the index at which the iterator gets created **Returns** An iterator starting at position ### `tree.begin` An iterator pointing to the first element in the tree ### `tree.end` An iterator pointing to the last element in the tree ### `tree.forEach(visitor(key,value)[, lo[, hi]])` Walks a visitor function over the nodes of the tree in order. * `visitor(key,value)` is a callback that gets executed on each node. If a truthy value is returned from the visitor, then iteration is stopped. * `lo` is an optional start of the range to visit (inclusive) * `hi` is an optional end of the range to visit (non-inclusive) **Returns** The last value returned by the callback ### `tree.root` Returns the root node of the tree ## Node properties Each node of the tree has the following properties: ### `node.key` The key associated to the node ### `node.value` The value associated to the node ### `node.left` The left subtree of the node ### `node.right` The right subtree of the node ## Iterator methods ### `iter.key` The key of the item referenced by the iterator ### `iter.value` The value of the item referenced by the iterator ### `iter.node` The value of the node at the iterator's current position. `null` is iterator is node valid. ### `iter.tree` The tree associated to the iterator ### `iter.index` Returns the position of this iterator in the sequence. ### `iter.valid` Checks if the iterator is valid ### `iter.clone()` Makes a copy of the iterator ### `iter.remove()` Removes the item at the position of the iterator **Returns** A new binary search tree with `iter`'s item removed ### `iter.update(value)` Updates the value of the node in the tree at this iterator **Returns** A new binary search tree with the corresponding node updated ### `iter.next()` Advances the iterator to the next position ### `iter.prev()` Moves the iterator backward one element ### `iter.hasNext` If true, then the iterator is not at the end of the sequence ### `iter.hasPrev` If true, then the iterator is not at the beginning of the sequence # Credits (c) 2013 Mikola Lysenko. MIT License # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. [![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). The AssemblyScript Runtime ========================== The runtime provides the functionality necessary to dynamically allocate and deallocate memory of objects, arrays and buffers, as well as collect garbage that is no longer used. The current implementation is either a Two-Color Mark & Sweep (TCMS) garbage collector that must be called manually when the execution stack is unwound or an Incremental Tri-Color Mark & Sweep (ITCMS) garbage collector that is fully automated with a shadow stack, implemented on top of a Two-Level Segregate Fit (TLSF) memory manager. It's not designed to be the fastest of its kind, but intentionally focuses on simplicity and ease of integration until we can replace it with the real deal, i.e. Wasm GC. Interface --------- ### Garbage collector / `--exportRuntime` * **__new**(size: `usize`, id: `u32` = 0): `usize`<br /> Dynamically allocates a GC object of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. GC-allocated objects cannot be used with `__realloc` and `__free`. * **__pin**(ptr: `usize`): `usize`<br /> Pins the object pointed to by `ptr` externally so it and its directly reachable members and indirectly reachable objects do not become garbage collected. * **__unpin**(ptr: `usize`): `void`<br /> Unpins the object pointed to by `ptr` externally so it can become garbage collected. * **__collect**(): `void`<br /> Performs a full garbage collection. ### Internals * **__alloc**(size: `usize`): `usize`<br /> Dynamically allocates a chunk of memory of at least the specified size and returns its address. Alignment is guaranteed to be 16 bytes to fit up to v128 values naturally. * **__realloc**(ptr: `usize`, size: `usize`): `usize`<br /> Dynamically changes the size of a chunk of memory, possibly moving it to a new address. * **__free**(ptr: `usize`): `void`<br /> Frees a dynamically allocated chunk of memory by its address. * **__renew**(ptr: `usize`, size: `usize`): `usize`<br /> Like `__realloc`, but for `__new`ed GC objects. * **__link**(parentPtr: `usize`, childPtr: `usize`, expectMultiple: `bool`): `void`<br /> Introduces a link from a parent object to a child object, i.e. upon `parent.field = child`. * **__visit**(ptr: `usize`, cookie: `u32`): `void`<br /> Concrete visitor implementation called during traversal. Cookie can be used to indicate one of multiple operations. * **__visit_globals**(cookie: `u32`): `void`<br /> Calls `__visit` on each global that is of a managed type. * **__visit_members**(ptr: `usize`, cookie: `u32`): `void`<br /> Calls `__visit` on each member of the object pointed to by `ptr`. * **__typeinfo**(id: `u32`): `RTTIFlags`<br /> Obtains the runtime type information for objects with the specified runtime id. Runtime type information is a set of flags indicating whether a type is managed, an array or similar, and what the relevant alignments when creating an instance externally are etc. * **__instanceof**(ptr: `usize`, classId: `u32`): `bool`<br /> Tests if the object pointed to by `ptr` is an instance of the specified class id. ITCMS / `--runtime incremental` ----- The Incremental Tri-Color Mark & Sweep garbage collector maintains a separate shadow stack of managed values in the background to achieve full automation. Maintaining another stack introduces some overhead compared to the simpler Two-Color Mark & Sweep garbage collector, but makes it independent of whether the execution stack is unwound or not when it is invoked, so the garbage collector can run interleaved with the program. There are several constants one can experiment with to tweak ITCMS's automation: * `--use ASC_GC_GRANULARITY=1024`<br /> How often to interrupt. The default of 1024 means "interrupt each 1024 bytes allocated". * `--use ASC_GC_STEPFACTOR=200`<br /> How long to interrupt. The default of 200% means "run at double the speed of allocations". * `--use ASC_GC_IDLEFACTOR=200`<br /> How long to idle. The default of 200% means "wait for memory to double before kicking in again". * `--use ASC_GC_MARKCOST=1`<br /> How costly it is to mark one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. * `--use ASC_GC_SWEEPCOST=10`<br /> How costly it is to sweep one object. Budget per interrupt is `GRANULARITY * STEPFACTOR / 100`. TCMS / `--runtime minimal` ---- If automation and low pause times aren't strictly necessary, using the Two-Color Mark & Sweep garbage collector instead by invoking collection manually at appropriate times when the execution stack is unwound may be more performant as it simpler and has less overhead. The execution stack is typically unwound when invoking the collector externally, at a place that is not indirectly called from Wasm. STUB / `--runtime stub` ---- The stub is a maximally minimal runtime substitute, consisting of a simple and fast bump allocator with no means of freeing up memory again, except when freeing the respective most recently allocated object on top of the bump. Useful where memory is not a concern, and/or where it is sufficient to destroy the whole module including any potential garbage after execution. See also: [Garbage collection](https://www.assemblyscript.org/garbage-collection.html) # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # flatted [![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg) ![snow flake](./flatted.jpg) <sup>**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**</sup> ## Announcement 📣 There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme). Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general. The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax. However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍 - - - A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson). Now available also for **[PHP](./php/flatted.php)**. ```js npm i flatted ``` Usable via [CDN](https://unpkg.com/flatted) or as regular module. ```js // ESM import {parse, stringify, toJSON, fromJSON} from 'flatted'; // CJS const {parse, stringify, toJSON, fromJSON} = require('flatted'); const a = [{}]; a[0].a = a; a.push(a); stringify(a); // [["1","0"],{"a":"0"}] ``` ## toJSON and fromJSON If you'd like to implicitly survive JSON serialization, these two helpers helps: ```js import {toJSON, fromJSON} from 'flatted'; class RecursiveMap extends Map { static fromJSON(any) { return new this(fromJSON(any)); } toJSON() { return toJSON([...this.entries()]); } } const recursive = new RecursiveMap; const same = {}; same.same = same; recursive.set('same', same); const asString = JSON.stringify(recursive); const asMap = RecursiveMap.fromJSON(JSON.parse(asString)); asMap.get('same') === asMap.get('same').same; // true ``` ## Flatted VS JSON As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`. The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity. Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected. ### New in V1: Exact same JSON API * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects. * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature. ### Compatibility All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled. ### How does it work ? While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*` Once parsed, all indexes will be replaced through the flattened collection. <sup><sub>`*` represented as string to avoid conflicts with numbers</sub></sup> ```js // logic example var a = [{one: 1}, {two: '2'}]; a[0].a = a; // a is the main object, will be at index '0' // {one: 1} is the second object, index '1' // {two: '2'} the third, in '2', and it has a string // which will be found at index '3' Flatted.stringify(a); // [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"] // a[one,two] {one: 1, a} {two: '2'} '2' ``` ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Shims used when bundling asc for browser usage. Standard library ================ Standard library components for use with `tsc` (portable) and `asc` (assembly). Base configurations (.json) and definition files (.d.ts) are relevant to `tsc` only and not used by `asc`. ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browserify Usage Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects. If you are *only* targeting the browser, then this library has little value for you. If you want to write cross platform code for node and the browser, `follow-redirects` provides a great solution for making the native node modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code you should tell browserify to swap out `follow-redirects` with the standard modules when bundling. To make this easier, you need to change how you require the modules: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` You can then replace `follow-redirects` in your browserify configuration like so: ```javascript "browser": { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native module when running in the browser. If you are experiencing problems, you may want to check out [browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should look something like this: ```javascript "browser": { "follow-redirects/http" : "browserify-http-2/http", "follow-redirects/https" : "browserify-http-2/https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License) # tr46.js > An implementation of the [Unicode TR46 specification](http://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) `>= 6` is required. To install, type this at the command line: ```shell npm install tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation. # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Specification conformance whatwg-url is currently up to date with the URL spec up to commit [7ae1c69](https://github.com/whatwg/url/commit/7ae1c691c96f0d82fafa24c33aa1e8df9ffbf2bc). For `file:` URLs, whose [origin is left unspecified](https://url.spec.whatwg.org/#concept-url-origin), whatwg-url chooses to use a new opaque origin (which serializes to `"null"`). ## API ### The `URL` and `URLSearchParams` classes The main API is provided by the [`URL`](https://url.spec.whatwg.org/#url-class) and [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) exports, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use these. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They mostly operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` - [Percent decode](https://url.spec.whatwg.org/#percent-decode): `percentDecode(buffer)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by `null`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ `null`. ## Development instructions First, install [Node.js](https://nodejs.org/). Then, fetch the dependencies of whatwg-url, by running from this directory: npm install To run tests: npm test To generate a coverage report: npm run coverage To build and run the live viewer: npm run build npm run build-live-viewer Serve the contents of the `live-viewer` directory using any web server. ## Supporting whatwg-url The jsdom project (including whatwg-url) is a community-driven project maintained by a team of [volunteers](https://github.com/orgs/jsdom/people). You could support us by: - [Getting professional support for whatwg-url](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) as part of a Tidelift subscription. Tidelift helps making open source sustainable for us while giving teams assurances for maintenance, licensing, and security. - Contributing directly to the project. # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 10.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree ![](cow.png) Moo! ==== Moo is a highly-optimised tokenizer/lexer generator. Use it to tokenize your strings, before parsing 'em with a parser like [nearley](https://github.com/hardmath123/nearley) or whatever else you're into. * [Fast](#is-it-fast) * [Convenient](#usage) * uses [Regular Expressions](#on-regular-expressions) * tracks [Line Numbers](#line-numbers) * handles [Keywords](#keywords) * supports [States](#states) * custom [Errors](#errors) * is even [Iterable](#iteration) * has no dependencies * 4KB minified + gzipped * Moo! Is it fast? ----------- Yup! Flying-cows-and-singed-steak fast. Moo is the fastest JS tokenizer around. It's **~2–10x** faster than most other tokenizers; it's a **couple orders of magnitude** faster than some of the slower ones. Define your tokens **using regular expressions**. Moo will compile 'em down to a **single RegExp for performance**. It uses the new ES6 **sticky flag** where possible to make things faster; otherwise it falls back to an almost-as-efficient workaround. (For more than you ever wanted to know about this, read [adventures in the land of substrings and RegExps](http://mrale.ph/blog/2016/11/23/making-less-dart-faster.html).) You _might_ be able to go faster still by writing your lexer by hand rather than using RegExps, but that's icky. Oh, and it [avoids parsing RegExps by itself](https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983#.2l8qu3l76). Because that would be horrible. Usage ----- First, you need to do the needful: `$ npm install moo`, or whatever will ship this code to your computer. Alternatively, grab the `moo.js` file by itself and slap it into your web page via a `<script>` tag; moo is completely standalone. Then you can start roasting your very own lexer/tokenizer: ```js const moo = require('moo') let lexer = moo.compile({ WS: /[ \t]+/, comment: /\/\/.*?$/, number: /0|[1-9][0-9]*/, string: /"(?:\\["\\]|[^\n"\\])*"/, lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], NL: { match: /\n/, lineBreaks: true }, }) ``` And now throw some text at it: ```js lexer.reset('while (10) cows\nmoo') lexer.next() // -> { type: 'keyword', value: 'while' } lexer.next() // -> { type: 'WS', value: ' ' } lexer.next() // -> { type: 'lparen', value: '(' } lexer.next() // -> { type: 'number', value: '10' } // ... ``` When you reach the end of Moo's internal buffer, next() will return `undefined`. You can always `reset()` it and feed it more data when that happens. On Regular Expressions ---------------------- RegExps are nifty for making tokenizers, but they can be a bit of a pain. Here are some things to be aware of: * You often want to use **non-greedy quantifiers**: e.g. `*?` instead of `*`. Otherwise your tokens will be longer than you expect: ```js let lexer = moo.compile({ string: /".*"/, // greedy quantifier * // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo" "bar' } ``` Better: ```js let lexer = moo.compile({ string: /".*?"/, // non-greedy quantifier *? // ... }) lexer.reset('"foo" "bar"') lexer.next() // -> { type: 'string', value: 'foo' } lexer.next() // -> { type: 'space', value: ' ' } lexer.next() // -> { type: 'string', value: 'bar' } ``` * The **order of your rules** matters. Earlier ones will take precedence. ```js moo.compile({ identifier: /[a-z0-9]+/, number: /[0-9]+/, }).reset('42').next() // -> { type: 'identifier', value: '42' } moo.compile({ number: /[0-9]+/, identifier: /[a-z0-9]+/, }).reset('42').next() // -> { type: 'number', value: '42' } ``` * Moo uses **multiline RegExps**. This has a few quirks: for example, the **dot `/./` doesn't include newlines**. Use `[^]` instead if you want to match newlines too. * Since an excluding character ranges like `/[^ ]/` (which matches anything but a space) _will_ include newlines, you have to be careful not to include them by accident! In particular, the whitespace metacharacter `\s` includes newlines. Line Numbers ------------ Moo tracks detailed information about the input for you. It will track line numbers, as long as you **apply the `lineBreaks: true` option to any rules which might contain newlines**. Moo will try to warn you if you forget to do this. Note that this is `false` by default, for performance reasons: counting the number of lines in a matched token has a small cost. For optimal performance, only match newlines inside a dedicated token: ```js newline: {match: '\n', lineBreaks: true}, ``` ### Token Info ### Token objects (returned from `next()`) have the following attributes: * **`type`**: the name of the group, as passed to compile. * **`text`**: the string that was matched. * **`value`**: the string that was matched, transformed by your `value` function (if any). * **`offset`**: the number of bytes from the start of the buffer where the match starts. * **`lineBreaks`**: the number of line breaks found in the match. (Always zero if this rule has `lineBreaks: false`.) * **`line`**: the line number of the beginning of the match, starting from 1. * **`col`**: the column where the match begins, starting from 1. ### Value vs. Text ### The `value` is the same as the `text`, unless you provide a [value transform](#transform). ```js const moo = require('moo') const lexer = moo.compile({ ws: /[ \t]+/, string: {match: /"(?:\\["\\]|[^\n"\\])*"/, value: s => s.slice(1, -1)}, }) lexer.reset('"test"') lexer.next() /* { value: 'test', text: '"test"', ... } */ ``` ### Reset ### Calling `reset()` on your lexer will empty its internal buffer, and set the line, column, and offset counts back to their initial value. If you don't want this, you can `save()` the state, and later pass it as the second argument to `reset()` to explicitly control the internal state of the lexer. ```js    lexer.reset('some line\n') let info = lexer.save() // -> { line: 10 } lexer.next() // -> { line: 10 } lexer.next() // -> { line: 11 } // ... lexer.reset('a different line\n', info) lexer.next() // -> { line: 10 } ``` Keywords -------- Moo makes it convenient to define literals. ```js moo.compile({ lparen: '(', rparen: ')', keyword: ['while', 'if', 'else', 'moo', 'cows'], }) ``` It'll automatically compile them into regular expressions, escaping them where necessary. **Keywords** should be written using the `keywords` transform. ```js moo.compile({ IDEN: {match: /[a-zA-Z]+/, type: moo.keywords({ KW: ['while', 'if', 'else', 'moo', 'cows'], })}, SPACE: {match: /\s+/, lineBreaks: true}, }) ``` ### Why? ### You need to do this to ensure the **longest match** principle applies, even in edge cases. Imagine trying to parse the input `className` with the following rules: ```js keyword: ['class'], identifier: /[a-zA-Z]+/, ``` You'll get _two_ tokens — `['class', 'Name']` -- which is _not_ what you want! If you swap the order of the rules, you'll fix this example; but now you'll lex `class` wrong (as an `identifier`). The keywords helper checks matches against the list of keywords; if any of them match, it uses the type `'keyword'` instead of `'identifier'` (for this example). ### Keyword Types ### Keywords can also have **individual types**. ```js let lexer = moo.compile({ name: {match: /[a-zA-Z]+/, type: moo.keywords({ 'kw-class': 'class', 'kw-def': 'def', 'kw-if': 'if', })}, // ... }) lexer.reset('def foo') lexer.next() // -> { type: 'kw-def', value: 'def' } lexer.next() // space lexer.next() // -> { type: 'name', value: 'foo' } ``` You can use [itt](https://github.com/nathan/itt)'s iterator adapters to make constructing keyword objects easier: ```js itt(['class', 'def', 'if']) .map(k => ['kw-' + k, k]) .toObject() ``` States ------ Moo allows you to define multiple lexer **states**. Each state defines its own separate set of token rules. Your lexer will start off in the first state given to `moo.states({})`. Rules can be annotated with `next`, `push`, and `pop`, to change the current state after that token is matched. A "stack" of past states is kept, which is used by `push` and `pop`. * **`next: 'bar'`** moves to the state named `bar`. (The stack is not changed.) * **`push: 'bar'`** moves to the state named `bar`, and pushes the old state onto the stack. * **`pop: 1`** removes one state from the top of the stack, and moves to that state. (Only `1` is supported.) Only rules from the current state can be matched. You need to copy your rule into all the states you want it to be matched in. For example, to tokenize JS-style string interpolation such as `a${{c: d}}e`, you might use: ```js let lexer = moo.states({ main: { strstart: {match: '`', push: 'lit'}, ident: /\w+/, lbrace: {match: '{', push: 'main'}, rbrace: {match: '}', pop: true}, colon: ':', space: {match: /\s+/, lineBreaks: true}, }, lit: { interp: {match: '${', push: 'main'}, escape: /\\./, strend: {match: '`', pop: true}, const: {match: /(?:[^$`]|\$(?!\{))+/, lineBreaks: true}, }, }) // <= `a${{c: d}}e` // => strstart const interp lbrace ident colon space ident rbrace rbrace const strend ``` The `rbrace` rule is annotated with `pop`, so it moves from the `main` state into either `lit` or `main`, depending on the stack. Errors ------ If none of your rules match, Moo will throw an Error; since it doesn't know what else to do. If you prefer, you can have moo return an error token instead of throwing an exception. The error token will contain the whole of the rest of the buffer. ```js moo.compile({ // ... myError: moo.error, }) moo.reset('invalid') moo.next() // -> { type: 'myError', value: 'invalid', text: 'invalid', offset: 0, lineBreaks: 0, line: 1, col: 1 } moo.next() // -> undefined ``` You can have a token type that both matches tokens _and_ contains error values. ```js moo.compile({ // ... myError: {match: /[\$?`]/, error: true}, }) ``` ### Formatting errors ### If you want to throw an error from your parser, you might find `formatError` helpful. Call it with the offending token: ```js throw new Error(lexer.formatError(token, "invalid syntax")) ``` It returns a string with a pretty error message. ``` Error: invalid syntax at line 2 col 15: totally valid `syntax` ^ ``` Iteration --------- Iterators: we got 'em. ```js for (let here of lexer) { // here = { type: 'number', value: '123', ... } } ``` Create an array of tokens. ```js let tokens = Array.from(lexer); ``` Use [itt](https://github.com/nathan/itt)'s iteration tools with Moo. ```js for (let [here, next] = itt(lexer).lookahead()) { // pass a number if you need more tokens // enjoy! } ``` Transform --------- Moo doesn't allow capturing groups, but you can supply a transform function, `value()`, which will be called on the value before storing it in the Token object. ```js moo.compile({ STRING: [ {match: /"""[^]*?"""/, lineBreaks: true, value: x => x.slice(3, -3)}, {match: /"(?:\\["\\rn]|[^"\\])*?"/, lineBreaks: true, value: x => x.slice(1, -1)}, {match: /'(?:\\['\\rn]|[^'\\])*?'/, lineBreaks: true, value: x => x.slice(1, -1)}, ], // ... }) ``` Contributing ------------ Do check the [FAQ](https://github.com/tjvr/moo/issues?q=label%3Aquestion). Before submitting an issue, [remember...](https://github.com/tjvr/moo/blob/master/.github/CONTRIBUTING.md) <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage : ### Simple Example ```javascript #!/usr/bin/env node const {argv} = require('yargs') if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ## Webpack See usage examples of yargs with webpack in [docs](/docs/webpack.md). ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # AssemblyScript Rtrace A tiny utility to sanitize the AssemblyScript runtime. Records allocations and frees performed by the runtime and emits an error if something is off. Also checks for leaks. Instructions ------------ Compile your module that uses the full or half runtime with `-use ASC_RTRACE=1 --explicitStart` and include an instance of this module as the import named `rtrace`. ```js const rtrace = new Rtrace({ onerror(err, info) { // handle error }, oninfo(msg) { // print message, optional }, getMemory() { // obtain the module's memory, // e.g. with --explicitStart: return instance.exports.memory; } }); const { module, instance } = await WebAssembly.instantiate(..., rtrace.install({ ...imports... }) ); instance.exports._start(); ... if (rtrace.active) { let leakCount = rtr.check(); if (leakCount) { // handle error } } ``` Note that references in globals which are not cleared before collection is performed appear as leaks, including their inner members. A TypedArray would leak itself and its backing ArrayBuffer in this case for example. This is perfectly normal and clearing all globals avoids this. [![NPM version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/eslint/doctrine](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/eslint/doctrine?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # Doctrine Doctrine is a [JSDoc](http://usejsdoc.org) parser that parses documentation comments from JavaScript (you need to pass in the comment, not a whole JavaScript file). ## Installation You can install Doctrine using [npm](https://npmjs.com): ``` $ npm install doctrine --save-dev ``` Doctrine can also be used in web browsers using [Browserify](http://browserify.org). ## Usage Require doctrine inside of your JavaScript: ```js var doctrine = require("doctrine"); ``` ### parse() The primary method is `parse()`, which accepts two arguments: the JSDoc comment to parse and an optional options object. The available options are: * `unwrap` - set to `true` to delete the leading `/**`, any `*` that begins a line, and the trailing `*/` from the source text. Default: `false`. * `tags` - an array of tags to return. When specified, Doctrine returns only tags in this array. For example, if `tags` is `["param"]`, then only `@param` tags will be returned. Default: `null`. * `recoverable` - set to `true` to keep parsing even when syntax errors occur. Default: `false`. * `sloppy` - set to `true` to allow optional parameters to be specified in brackets (`@param {string} [foo]`). Default: `false`. * `lineNumbers` - set to `true` to add `lineNumber` to each node, specifying the line on which the node is found in the source. Default: `false`. * `range` - set to `true` to add `range` to each node, specifying the start and end index of the node in the original comment. Default: `false`. Here's a simple example: ```js var ast = doctrine.parse( [ "/**", " * This function comment is parsed by doctrine", " * @param {{ok:String}} userName", "*/" ].join('\n'), { unwrap: true }); ``` This example returns the following AST: { "description": "This function comment is parsed by doctrine", "tags": [ { "title": "param", "description": null, "type": { "type": "RecordType", "fields": [ { "type": "FieldType", "key": "ok", "value": { "type": "NameExpression", "name": "String" } } ] }, "name": "userName" } ] } See the [demo page](http://eslint.org/doctrine/demo/) more detail. ## Team These folks keep the project moving and are resources for help: * Nicholas C. Zakas ([@nzakas](https://github.com/nzakas)) - project lead * Yusuke Suzuki ([@constellation](https://github.com/constellation)) - reviewer ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/doctrine/issues). ## Frequently Asked Questions ### Can I pass a whole JavaScript file to Doctrine? No. Doctrine can only parse JSDoc comments, so you'll need to pass just the JSDoc comment to Doctrine in order to work. ### License #### doctrine Copyright JS Foundation and other contributors, https://js.foundation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #### esprima some of functions is derived from esprima Copyright (C) 2012, 2011 [Ariya Hidayat](http://ariya.ofilabs.com/about) (twitter: [@ariyahidayat](http://twitter.com/ariyahidayat)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #### closure-compiler some of extensions is derived from closure-compiler Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ ### Where to ask for help? Join our [Chatroom](https://gitter.im/eslint/doctrine) [npm-image]: https://img.shields.io/npm/v/doctrine.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/doctrine [travis-image]: https://img.shields.io/travis/eslint/doctrine/master.svg?style=flat-square [travis-url]: https://travis-ci.org/eslint/doctrine [coveralls-image]: https://img.shields.io/coveralls/eslint/doctrine/master.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/eslint/doctrine?branch=master [downloads-image]: http://img.shields.io/npm/dm/doctrine.svg?style=flat-square [downloads-url]: https://www.npmjs.com/package/doctrine # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # lodash.truncate v4.4.2 The [lodash](https://lodash.com/) method `_.truncate` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.truncate ``` In Node.js: ```js var truncate = require('lodash.truncate'); ``` See the [documentation](https://lodash.com/docs#truncate) or [package source](https://github.com/lodash/lodash/blob/4.4.2-npm-packages/lodash.truncate) for more details. # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. Compiler frontend for node.js ============================= Usage ----- For an up to date list of available command line options, see: ``` $> asc --help ``` API --- The API accepts the same options as the CLI but also lets you override stdout and stderr and/or provide a callback. Example: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { asc.main([ "myModule.ts", "--binaryFile", "myModule.wasm", "--optimize", "--sourceMap", "--measure" ], { stdout: process.stdout, stderr: process.stderr }, function(err) { if (err) throw err; ... }); }); ``` Available command line options can also be obtained programmatically: ```js const options = require("assemblyscript/cli/asc.json"); ... ``` You can also compile a source string directly, for example in a browser environment: ```js const asc = require("assemblyscript/cli/asc"); asc.ready.then(() => { const { binary, text, stdout, stderr } = asc.compileString(`...`, { optimize: 2 }); }); ... ``` # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm (beta)](https://img.shields.io/npm/v/ajv/beta)](https://www.npmjs.com/package/ajv/v/7.0.0-beta.0) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv v7 beta is released [Ajv version 7.0.0-beta.0](https://github.com/ajv-validator/ajv/tree/v7-beta) is released with these changes: - to reduce the mistakes in JSON schemas and unexpected validation results, [strict mode](./docs/strict-mode.md) is added - it prohibits ignored or ambiguous JSON Schema elements. - to make code injection from untrusted schemas impossible, [code generation](./docs/codegen.md) is fully re-written to be safe. - to simplify Ajv extensions, the new keyword API that is used by pre-defined keywords is available to user-defined keywords - it is much easier to define any keywords now, especially with subschemas. - schemas are compiled to ES6 code (ES5 code generation is supported with an option). - to improve reliability and maintainability the code is migrated to TypeScript. **Please note**: - the support for JSON-Schema draft-04 is removed - if you have schemas using "id" attributes you have to replace them with "\$id" (or continue using version 6 that will be supported until 02/28/2021). - all formats are separated to ajv-formats package - they have to be explicitely added if you use them. See [release notes](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) for the details. To install the new version: ```bash npm install ajv@beta ``` See [Getting started with v7](https://github.com/ajv-validator/ajv/tree/v7-beta#usage) for code example. ## Mozilla MOSS grant and OpenJS Foundation [<img src="https://www.poberezkin.com/images/mozilla.png" width="240" height="68">](https://www.mozilla.org/en-US/moss/) &nbsp;&nbsp;&nbsp; [<img src="https://www.poberezkin.com/images/openjs.png" width="220" height="68">](https://openjsf.org/blog/2020/08/14/ajv-joins-openjs-foundation-as-an-incubation-project/) Ajv has been awarded a grant from Mozilla’s [Open Source Support (MOSS) program](https://www.mozilla.org/en-US/moss/) in the “Foundational Technology” track! It will sponsor the development of Ajv support of [JSON Schema version 2019-09](https://tools.ietf.org/html/draft-handrews-json-schema-02) and of [JSON Type Definition](https://tools.ietf.org/html/draft-ucarion-json-type-definition-04). Ajv also joined [OpenJS Foundation](https://openjsf.org/) – having this support will help ensure the longevity and stability of Ajv for all its users. This [blog post](https://www.poberezkin.com/posts/2020-08-14-ajv-json-validator-mozilla-open-source-grant-openjs-foundation.html) has more details. I am looking for the long term maintainers of Ajv – working with [ReadySet](https://www.thereadyset.co/), also sponsored by Mozilla, to establish clear guidelines for the role of a "maintainer" and the contribution standards, and to encourage a wider, more inclusive, contribution from the community. ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can allow specific format(s) that will be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 7.0.0-beta](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0-beta.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE) # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) # Visitor utilities for AssemblyScript Compiler transformers ## Example ### List Fields The transformer: ```ts import { ClassDeclaration, FieldDeclaration, MethodDeclaration, } from "../../as"; import { ClassDecorator, registerDecorator } from "../decorator"; import { toString } from "../utils"; class ListMembers extends ClassDecorator { visitFieldDeclaration(node: FieldDeclaration): void { if (!node.name) console.log(toString(node) + "\n"); const name = toString(node.name); const _type = toString(node.type!); this.stdout.write(name + ": " + _type + "\n"); } visitMethodDeclaration(node: MethodDeclaration): void { const name = toString(node.name); if (name == "constructor") { return; } const sig = toString(node.signature); this.stdout.write(name + ": " + sig + "\n"); } visitClassDeclaration(node: ClassDeclaration): void { this.visit(node.members); } get name(): string { return "list"; } } export = registerDecorator(new ListMembers()); ``` assembly/foo.ts: ```ts @list class Foo { a: u8; b: bool; i: i32; } ``` And then compile with `--transform` flag: ``` asc assembly/foo.ts --transform ./dist/examples/list --noEmit ``` Which prints the following to the console: ``` a: u8 b: bool i: i32 ``` A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # prelude.ls [![Build Status](https://travis-ci.org/gkz/prelude-ls.png?branch=master)](https://travis-ci.org/gkz/prelude-ls) is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, <a href="http://livescript.net">LiveScript</a>. See **[the prelude.ls site](http://preludels.com)** for examples, a reference, and more. You can install via npm `npm install prelude-ls` ### Development `make test` to test `make build` to build `lib` from `src` `make build-browser` to build browser versions # assemblyscript-regex A regex engine for AssemblyScript. [AssemblyScript](https://www.assemblyscript.org/) is a new language, based on TypeScript, that runs on WebAssembly. AssemblyScript has a lightweight standard library, but lacks support for Regular Expression. The project fills that gap! This project exposes an API that mirrors the JavaScript [RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) class: ```javascript const regex = new RegExp("fo*", "g"); const str = "table football, foul"; let match: Match | null = regex.exec(str); while (match != null) { // first iteration // match.index = 6 // match.matches[0] = "foo" // second iteration // match.index = 16 // match.matches[0] = "fo" match = regex.exec(str); } ``` ## Project status The initial focus of this implementation has been feature support and functionality over performance. It currently supports a sufficient number of regex features to be considered useful, including most character classes, common assertions, groups, alternations, capturing groups and quantifiers. The next phase of development will focussed on more extensive testing and performance. The project currently has reasonable unit test coverage, focussed on positive and negative test cases on a per-feature basis. It also includes a more exhaustive test suite with test cases borrowed from another regex library. ### Feature support Based on the classfication within the [MDN cheatsheet](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet) **Character sets** - [x] . - [x] \d - [x] \D - [x] \w - [x] \W - [x] \s - [x] \S - [x] \t - [x] \r - [x] \n - [x] \v - [x] \f - [ ] [\b] - [ ] \0 - [ ] \cX - [x] \xhh - [x] \uhhhh - [ ] \u{hhhh} or \u{hhhhh} - [x] \ **Assertions** - [x] ^ - [x] $ - [ ] \b - [ ] \B **Other assertions** - [ ] x(?=y) Lookahead assertion - [ ] x(?!y) Negative lookahead assertion - [ ] (?<=y)x Lookbehind assertion - [ ] (?<!y)x Negative lookbehind assertion **Groups and ranges** - [x] x|y - [x] [xyz][a-c] - [x] [^xyz][^a-c] - [x] (x) capturing group - [ ] \n back reference - [ ] (?<Name>x) named capturing group - [x] (?:x) Non-capturing group **Quantifiers** - [x] x\* - [x] x+ - [x] x? - [x] x{n} - [x] x{n,} - [x] x{n,m} - [ ] x\*? / x+? / ... **RegExp** - [x] global - [ ] sticky - [x] case insensitive - [x] multiline - [x] dotAll - [ ] unicode ### Development This project is open source, MIT licenced and your contributions are very much welcomed. To get started, check out the repository and install dependencies: ``` $ npm install ``` A few general points about the tools and processes this project uses: - This project uses prettier for code formatting and eslint to provide additional syntactic checks. These are both run on `npm test` and as part of the CI build. - The unit tests are executed using [as-pect](https://github.com/jtenner/as-pect) - a native AssemblyScript test runner - The specification tests are within the `spec` folder. The `npm run test:generate` target transforms these tests into as-pect tests which execute as part of the standard build / test cycle - In order to support improved debugging you can execute this library as TypeScript (rather than WebAssembly), via the `npm run tsrun` target. # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` ## Test Strategy - tests are copied from the [polyfill implementation](https://github.com/tc39/proposal-temporal/tree/main/polyfill/test) - tests should be removed if they relate to features that do not make sense for TS/AS, i.e. tests that validate the shape of an object do not make sense in a language with compile-time type checking - tests that fail because a feature has not been implemented yet should be left as failures. # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard <img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/img/ajv.svg"> &nbsp; # Ajv JSON schema validator The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). [![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![SimpleX](https://img.shields.io/badge/chat-on%20SimpleX-%2307b4b9)](https://simplex.chat/contact#/?v=1&smp=smp%3A%2F%2Fu2dS9sG8nMNURyZwqASV4yROM28Er0luVTx5X1CsMrU%3D%40smp4.simplex.im%2Fap4lMFzfXF8Hzmh-Vz0WNxp_1jKiOa-h%23MCowBQYDK2VuAyEAcdefddRvDfI8iAuBpztm_J3qFucj8MDZoVs_2EcMTzU%3D) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Ajv sponsors [<img src="https://ajv.js.org/img/mozilla.svg" width="45%" alt="Mozilla">](https://www.mozilla.org)<img src="https://ajv.js.org/img/gap.svg" width="9%">[<img src="https://ajv.js.org/img/reserved.svg" width="45%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/microsoft.png" width="31%" alt="Microsoft">](https://opensource.microsoft.com)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="31%">](https://opencollective.com/ajv) [<img src="https://ajv.js.org/img/retool.svg" width="22.5%" alt="Retool">](https://retool.com/?utm_source=sponsor&utm_campaign=ajv)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/tidelift.svg" width="22.5%" alt="Tidelift">](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=enterprise)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/simplex.svg" width="22.5%" alt="SimpleX">](https://github.com/simplex-chat/simplex-chat)<img src="https://ajv.js.org/img/gap.svg" width="3%">[<img src="https://ajv.js.org/img/reserved.svg" width="22.5%">](https://opencollective.com/ajv) ## Contributing More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation. Please review [Contributing guidelines](./CONTRIBUTING.md) and [Code components](https://ajv.js.org/components.html). ## Documentation All documentation is available on the [Ajv website](https://ajv.js.org). Some useful site links: - [Getting started](https://ajv.js.org/guide/getting-started.html) - [JSON Schema vs JSON Type Definition](https://ajv.js.org/guide/schema-language.html) - [API reference](https://ajv.js.org/api.html) - [Strict mode](https://ajv.js.org/strict-mode.html) - [Standalone validation code](https://ajv.js.org/standalone.html) - [Security considerations](https://ajv.js.org/security.html) - [Command line interface](https://ajv.js.org/packages/ajv-cli.html) - [Frequently Asked Questions](https://ajv.js.org/faq.html) ## <a name="sponsors"></a>Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant! Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released. Please sponsor Ajv via: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) Thank you. #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/10/website"><img src="https://opencollective.com/ajv/organization/10/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/11/website"><img src="https://opencollective.com/ajv/organization/11/avatar.svg"></a> ## Performance Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=62,4,1&chs=600x416&chxl=-1:|ajv|@exodus&#x2F;schemasafe|is-my-json-valid|djv|@cfworker&#x2F;json-schema|jsonschema&chd=t:100,69.2,51.5,13.1,5.1,1.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements JSON Schema [draft-06/07/2019-09/2020-12](http://json-schema.org/) standards (draft-04 is supported in v6): - all validation keywords (see [JSON Schema validation keywords](https://ajv.js.org/json-schema.html)) - [OpenAPI](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.3.md) extensions: - NEW: keyword [discriminator](https://ajv.js.org/json-schema.html#discriminator). - keyword [nullable](https://ajv.js.org/json-schema.html#nullable). - full support of remote references (remote schemas have to be added with `addSchema` or compiled to be available) - support of recursive references between schemas - correct string lengths for strings with unicode pairs - JSON Schema [formats](https://ajv.js.org/guide/formats.html) (with [ajv-formats](https://github.com/ajv-validator/ajv-formats) plugin). - [validates schemas against meta-schema](https://ajv.js.org/api.html#api-validateschema) - NEW: supports [JSON Type Definition](https://datatracker.ietf.org/doc/rfc8927/): - all keywords (see [JSON Type Definition schema forms](https://ajv.js.org/json-type-definition.html)) - meta-schema for JTD schemas - "union" keyword and user-defined keywords (can be used inside "metadata" member of the schema) - supports [browsers](https://ajv.js.org/guide/environments.html#browsers) and Node.js 10.x - current - [asynchronous loading](https://ajv.js.org/guide/managing-schemas.html#asynchronous-schema-loading) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](https://ajv.js.org/options.html#allerrors) - [error messages with parameters](https://ajv.js.org/api.html#validation-errors) describing error reasons to allow error message generation - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [removing-additional-properties](https://ajv.js.org/guide/modifying-data.html#removing-additional-properties) - [assigning defaults](https://ajv.js.org/guide/modifying-data.html#assigning-defaults) to missing properties and items - [coercing data](https://ajv.js.org/guide/modifying-data.html#coercing-data-types) to the types specified in `type` keywords - [user-defined keywords](https://ajv.js.org/guide/user-keywords.html) - additional extension keywords with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [\$data reference](https://ajv.js.org/guide/combining-schemas.html#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](https://ajv.js.org/guide/async-validation.html) of user-defined formats and keywords ## Install To install version 8: ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://runkit.com/npm/ajv In JavaScript: ```javascript // or ESM/TypeScript import import Ajv from "ajv" // Node.js require: const Ajv = require("ajv") const ajv = new Ajv() // options can be passed, e.g. {allErrors: true} const schema = { type: "object", properties: { foo: {type: "integer"}, bar: {type: "string"} }, required: ["foo"], additionalProperties: false, } const data = { foo: 1, bar: "abc" } const validate = ajv.compile(schema) const valid = validate(data) if (!valid) console.log(validate.errors) ``` Learn how to use Ajv and see more examples in the [Guide: getting started](https://ajv.js.org/guide/getting-started.html) ## Changes history See [https://github.com/ajv-validator/ajv/releases](https://github.com/ajv-validator/ajv/releases) **Please note**: [Changes in version 8.0.0](https://github.com/ajv-validator/ajv/releases/tag/v8.0.0) [Version 7.0.0](https://github.com/ajv-validator/ajv/releases/tag/v7.0.0) [Version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). ## Code of conduct Please review and follow the [Code of conduct](./CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](./LICENSE) <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg [![npm version](https://img.shields.io/npm/v/eslint.svg)](https://www.npmjs.com/package/eslint) [![Downloads](https://img.shields.io/npm/dm/eslint.svg)](https://www.npmjs.com/package/eslint) [![Build Status](https://github.com/eslint/eslint/workflows/CI/badge.svg)](https://github.com/eslint/eslint/actions) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_shield) <br /> [![Open Collective Backers](https://img.shields.io/opencollective/backers/eslint)](https://opencollective.com/eslint) [![Open Collective Sponsors](https://img.shields.io/opencollective/sponsors/eslint)](https://opencollective.com/eslint) [![Follow us on Twitter](https://img.shields.io/twitter/follow/geteslint?label=Follow&style=social)](https://twitter.com/intent/user?screen_name=geteslint) # ESLint [Website](https://eslint.org) | [Configuring](https://eslint.org/docs/user-guide/configuring) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/developer-guide/contributing) | [Reporting Bugs](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) | [Code of Conduct](https://eslint.org/conduct) | [Twitter](https://twitter.com/geteslint) | [Mailing List](https://groups.google.com/group/eslint) | [Chat Room](https://eslint.org/chat) ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code. In many ways, it is similar to JSLint and JSHint with a few exceptions: * ESLint uses [Espree](https://github.com/eslint/espree) for JavaScript parsing. * ESLint uses an AST to evaluate patterns in code. * ESLint is completely pluggable, every single rule is a plugin and you can add more at runtime. ## Table of Contents 1. [Installation and Usage](#installation-and-usage) 2. [Configuration](#configuration) 3. [Code of Conduct](#code-of-conduct) 4. [Filing Issues](#filing-issues) 5. [Frequently Asked Questions](#faq) 6. [Releases](#releases) 7. [Security Policy](#security-policy) 8. [Semantic Versioning Policy](#semantic-versioning-policy) 9. [Stylistic Rule Updates](#stylistic-rule-updates) 10. [License](#license) 11. [Team](#team) 12. [Sponsors](#sponsors) 13. [Technology Sponsors](#technology-sponsors) ## <a name="installation-and-usage"></a>Installation and Usage Prerequisites: [Node.js](https://nodejs.org/) (`^10.12.0`, or `>=12.0.0`) built with SSL support. (If you are using an official Node.js distribution, SSL is always built in.) You can install ESLint using npm: ``` $ npm install eslint --save-dev ``` You should then set up a configuration file: ``` $ ./node_modules/.bin/eslint --init ``` After that, you can run ESLint on any file or directory like this: ``` $ ./node_modules/.bin/eslint yourfile.js ``` ## <a name="configuration"></a>Configuration After running `eslint --init`, you'll have a `.eslintrc` file in your directory. In it, you'll see some rules configured like this: ```json { "rules": { "semi": ["error", "always"], "quotes": ["error", "double"] } } ``` The names `"semi"` and `"quotes"` are the names of [rules](https://eslint.org/docs/rules) in ESLint. The first value is the error level of the rule and can be one of these values: * `"off"` or `0` - turn the rule off * `"warn"` or `1` - turn the rule on as a warning (doesn't affect exit code) * `"error"` or `2` - turn the rule on as an error (exit code will be 1) The three error levels allow you fine-grained control over how ESLint applies rules (for more configuration options and details, see the [configuration docs](https://eslint.org/docs/user-guide/configuring)). ## <a name="code-of-conduct"></a>Code of Conduct ESLint adheres to the [JS Foundation Code of Conduct](https://eslint.org/conduct). ## <a name="filing-issues"></a>Filing Issues Before filing an issue, please be sure to read the guidelines for what you're reporting: * [Bug Report](https://eslint.org/docs/developer-guide/contributing/reporting-bugs) * [Propose a New Rule](https://eslint.org/docs/developer-guide/contributing/new-rules) * [Proposing a Rule Change](https://eslint.org/docs/developer-guide/contributing/rule-changes) * [Request a Change](https://eslint.org/docs/developer-guide/contributing/changes) ## <a name="faq"></a>Frequently Asked Questions ### I'm using JSCS, should I migrate to ESLint? Yes. [JSCS has reached end of life](https://eslint.org/blog/2016/07/jscs-end-of-life) and is no longer supported. We have prepared a [migration guide](https://eslint.org/docs/user-guide/migrating-from-jscs) to help you convert your JSCS settings to an ESLint configuration. We are now at or near 100% compatibility with JSCS. If you try ESLint and believe we are not yet compatible with a JSCS rule/configuration, please create an issue (mentioning that it is a JSCS compatibility issue) and we will evaluate it as per our normal process. ### Does Prettier replace ESLint? No, ESLint does both traditional linting (looking for problematic patterns) and style checking (enforcement of conventions). You can use ESLint for everything, or you can combine both using Prettier to format your code and ESLint to catch possible errors. ### Why can't ESLint find my plugins? * Make sure your plugins (and ESLint) are both in your project's `package.json` as devDependencies (or dependencies, if your project uses ESLint at runtime). * Make sure you have run `npm install` and all your dependencies are installed. * Make sure your plugins' peerDependencies have been installed as well. You can use `npm view eslint-plugin-myplugin peerDependencies` to see what peer dependencies `eslint-plugin-myplugin` has. ### Does ESLint support JSX? Yes, ESLint natively supports parsing JSX syntax (this must be enabled in [configuration](https://eslint.org/docs/user-guide/configuring)). Please note that supporting JSX syntax *is not* the same as supporting React. React applies specific semantics to JSX syntax that ESLint doesn't recognize. We recommend using [eslint-plugin-react](https://www.npmjs.com/package/eslint-plugin-react) if you are using React and want React semantics. ### What ECMAScript versions does ESLint support? ESLint has full support for ECMAScript 3, 5 (default), 2015, 2016, 2017, 2018, 2019, and 2020. You can set your desired ECMAScript syntax (and other settings, like global variables or your target environments) through [configuration](https://eslint.org/docs/user-guide/configuring). ### What about experimental features? ESLint's parser only officially supports the latest final ECMAScript standard. We will make changes to core rules in order to avoid crashes on stage 3 ECMAScript syntax proposals (as long as they are implemented using the correct experimental ESTree syntax). We may make changes to core rules to better work with language extensions (such as JSX, Flow, and TypeScript) on a case-by-case basis. In other cases (including if rules need to warn on more or fewer cases due to new syntax, rather than just not crashing), we recommend you use other parsers and/or rule plugins. If you are using Babel, you can use the [babel-eslint](https://github.com/babel/babel-eslint) parser and [eslint-plugin-babel](https://github.com/babel/eslint-plugin-babel) to use any option available in Babel. Once a language feature has been adopted into the ECMAScript standard (stage 4 according to the [TC39 process](https://tc39.github.io/process-document/)), we will accept issues and pull requests related to the new feature, subject to our [contributing guidelines](https://eslint.org/docs/developer-guide/contributing). Until then, please use the appropriate parser and plugin(s) for your experimental feature. ### Where to ask for help? Join our [Mailing List](https://groups.google.com/group/eslint) or [Chatroom](https://eslint.org/chat). ### Why doesn't ESLint lock dependency versions? Lock files like `package-lock.json` are helpful for deployed applications. They ensure that dependencies are consistent between environments and across deployments. Packages like `eslint` that get published to the npm registry do not include lock files. `npm install eslint` as a user will respect version constraints in ESLint's `package.json`. ESLint and its dependencies will be included in the user's lock file if one exists, but ESLint's own lock file would not be used. We intentionally don't lock dependency versions so that we have the latest compatible dependency versions in development and CI that our users get when installing ESLint in a project. The Twilio blog has a [deeper dive](https://www.twilio.com/blog/lockfiles-nodejs) to learn more. ## <a name="releases"></a>Releases We have scheduled releases every two weeks on Friday or Saturday. You can follow a [release issue](https://github.com/eslint/eslint/issues?q=is%3Aopen+is%3Aissue+label%3Arelease) for updates about the scheduling of any particular release. ## <a name="security-policy"></a>Security Policy ESLint takes security seriously. We work hard to ensure that ESLint is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## <a name="semantic-versioning-policy"></a>Semantic Versioning Policy ESLint follows [semantic versioning](https://semver.org). However, due to the nature of ESLint as a code quality tool, it's not always clear when a minor or major version bump occurs. To help clarify this for everyone, we've defined the following semantic versioning policy for ESLint: * Patch release (intended to not break your lint build) * A bug fix in a rule that results in ESLint reporting fewer linting errors. * A bug fix to the CLI or core (including formatters). * Improvements to documentation. * Non-user-facing changes such as refactoring code, adding, deleting, or modifying tests, and increasing test coverage. * Re-releasing after a failed release (i.e., publishing a release that doesn't work for anyone). * Minor release (might break your lint build) * A bug fix in a rule that results in ESLint reporting more linting errors. * A new rule is created. * A new option to an existing rule that does not result in ESLint reporting more linting errors by default. * A new addition to an existing rule to support a newly-added language feature (within the last 12 months) that will result in ESLint reporting more linting errors by default. * An existing rule is deprecated. * A new CLI capability is created. * New capabilities to the public API are added (new classes, new methods, new arguments to existing methods, etc.). * A new formatter is created. * `eslint:recommended` is updated and will result in strictly fewer linting errors (e.g., rule removals). * Major release (likely to break your lint build) * `eslint:recommended` is updated and may result in new linting errors (e.g., rule additions, most rule option updates). * A new option to an existing rule that results in ESLint reporting more linting errors by default. * An existing formatter is removed. * Part of the public API is removed or changed in an incompatible way. The public API includes: * Rule schemas * Configuration schema * Command-line options * Node.js API * Rule, formatter, parser, plugin APIs According to our policy, any minor update may report more linting errors than the previous release (ex: from a bug fix). As such, we recommend using the tilde (`~`) in `package.json` e.g. `"eslint": "~3.1.0"` to guarantee the results of your builds. ## <a name="stylistic-rule-updates"></a>Stylistic Rule Updates Stylistic rules are frozen according to [our policy](https://eslint.org/blog/2020/05/changes-to-rules-policies) on how we evaluate new rules and rule changes. This means: * **Bug fixes**: We will still fix bugs in stylistic rules. * **New ECMAScript features**: We will also make sure stylistic rules are compatible with new ECMAScript features. * **New options**: We will **not** add any new options to stylistic rules unless an option is the only way to fix a bug or support a newly-added ECMAScript feature. ## <a name="license"></a>License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Feslint%2Feslint?ref=badge_large) ## <a name="team"></a>Team These folks keep the project moving and are resources for help. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--teamstart--> ### Technical Steering Committee (TSC) The people who manage releases, review feature requests, and meet regularly to ensure ESLint is properly maintained. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/nzakas"> <img src="https://github.com/nzakas.png?s=75" width="75" height="75"><br /> Nicholas C. Zakas </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/btmills"> <img src="https://github.com/btmills.png?s=75" width="75" height="75"><br /> Brandon Mills </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/mdjermanovic"> <img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br /> Milos Djermanovic </a> </td></tr></tbody></table> ### Reviewers The people who review and implement new features. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/mysticatea"> <img src="https://github.com/mysticatea.png?s=75" width="75" height="75"><br /> Toru Nagashima </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/aladdin-add"> <img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br /> 薛定谔的猫 </a> </td></tr></tbody></table> ### Committers The people who review and fix bugs and help triage issues. <table><tbody><tr><td align="center" valign="top" width="11%"> <a href="https://github.com/brettz9"> <img src="https://github.com/brettz9.png?s=75" width="75" height="75"><br /> Brett Zamir </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/bmish"> <img src="https://github.com/bmish.png?s=75" width="75" height="75"><br /> Bryan Mishkin </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/g-plane"> <img src="https://github.com/g-plane.png?s=75" width="75" height="75"><br /> Pig Fang </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/anikethsaha"> <img src="https://github.com/anikethsaha.png?s=75" width="75" height="75"><br /> Anix </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/yeonjuan"> <img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br /> YeonJuan </a> </td><td align="center" valign="top" width="11%"> <a href="https://github.com/snitin315"> <img src="https://github.com/snitin315.png?s=75" width="75" height="75"><br /> Nitin Kumar </a> </td></tr></tbody></table> <!--teamend--> ## <a name="sponsors"></a>Sponsors The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://opencollective.com/eslint) to get your logo on our README and website. <!-- NOTE: This section is autogenerated. Do not manually edit.--> <!--sponsorsstart--> <h3>Platinum Sponsors</h3> <p><a href="https://automattic.com"><img src="https://images.opencollective.com/photomatt/d0ef3e1/logo.png" alt="Automattic" height="undefined"></a></p><h3>Gold Sponsors</h3> <p><a href="https://nx.dev"><img src="https://images.opencollective.com/nx/0efbe42/logo.png" alt="Nx (by Nrwl)" height="96"></a> <a href="https://google.com/chrome"><img src="https://images.opencollective.com/chrome/dc55bd4/logo.png" alt="Chrome's Web Framework & Tools Performance Fund" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a> <a href="https://coinbase.com"><img src="https://avatars.githubusercontent.com/u/1885080?v=4" alt="Coinbase" height="96"></a> <a href="https://substack.com/"><img src="https://avatars.githubusercontent.com/u/53023767?v=4" alt="Substack" height="96"></a></p><h3>Silver Sponsors</h3> <p><a href="https://retool.com/"><img src="https://images.opencollective.com/retool/98ea68e/logo.png" alt="Retool" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a></p><h3>Bronze Sponsors</h3> <p><a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="null"><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8: free icons, photos, illustrations, and music" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a> <a href="https://www.practiceignition.com"><img src="https://avatars.githubusercontent.com/u/5753491?v=4" alt="Practice Ignition" height="32"></a></p> <!--sponsorsend--> ## <a name="technology-sponsors"></a>Technology Sponsors * Site search ([eslint.org](https://eslint.org)) is sponsored by [Algolia](https://www.algolia.com) * Hosting for ([eslint.org](https://eslint.org)) is sponsored by [Netlify](https://www.netlify.com) * Password management is sponsored by [1Password](https://www.1password.com) # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019) or 11 (2020, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 10. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n # type-check [![Build Status](https://travis-ci.org/gkz/type-check.png?branch=master)](https://travis-ci.org/gkz/type-check) <a name="type-check" /> `type-check` is a library which allows you to check the types of JavaScript values at runtime with a Haskell like type syntax. It is great for checking external input, for testing, or even for adding a bit of safety to your internal code. It is a major component of [levn](https://github.com/gkz/levn). MIT license. Version 0.4.0. Check out the [demo](http://gkz.github.io/type-check/). For updates on `type-check`, [follow me on twitter](https://twitter.com/gkzahariev). npm install type-check ## Quick Examples ```js // Basic types: var typeCheck = require('type-check').typeCheck; typeCheck('Number', 1); // true typeCheck('Number', 'str'); // false typeCheck('Error', new Error); // true typeCheck('Undefined', undefined); // true // Comment typeCheck('count::Number', 1); // true // One type OR another type: typeCheck('Number | String', 2); // true typeCheck('Number | String', 'str'); // true // Wildcard, matches all types: typeCheck('*', 2) // true // Array, all elements of a single type: typeCheck('[Number]', [1, 2, 3]); // true typeCheck('[Number]', [1, 'str', 3]); // false // Tuples, or fixed length arrays with elements of different types: typeCheck('(String, Number)', ['str', 2]); // true typeCheck('(String, Number)', ['str']); // false typeCheck('(String, Number)', ['str', 2, 5]); // false // Object properties: typeCheck('{x: Number, y: Boolean}', {x: 2, y: false}); // true typeCheck('{x: Number, y: Boolean}', {x: 2}); // false typeCheck('{x: Number, y: Maybe Boolean}', {x: 2}); // true typeCheck('{x: Number, y: Boolean}', {x: 2, y: false, z: 3}); // false typeCheck('{x: Number, y: Boolean, ...}', {x: 2, y: false, z: 3}); // true // A particular type AND object properties: typeCheck('RegExp{source: String, ...}', /re/i); // true typeCheck('RegExp{source: String, ...}', {source: 're'}); // false // Custom types: var opt = {customTypes: {Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; }}}}; typeCheck('Even', 2, opt); // true // Nested: var type = '{a: (String, [Number], {y: Array, ...}), b: Error{message: String, ...}}' typeCheck(type, {a: ['hi', [1, 2, 3], {y: [1, 'ms']}], b: new Error('oh no')}); // true ``` Check out the [type syntax format](#syntax) and [guide](#guide). ## Usage `require('type-check');` returns an object that exposes four properties. `VERSION` is the current version of the library as a string. `typeCheck`, `parseType`, and `parsedTypeCheck` are functions. ```js // typeCheck(type, input, options); typeCheck('Number', 2); // true // parseType(type); var parsedType = parseType('Number'); // object // parsedTypeCheck(parsedType, input, options); parsedTypeCheck(parsedType, 2); // true ``` ### typeCheck(type, input, options) `typeCheck` checks a JavaScript value `input` against `type` written in the [type format](#type-format) (and taking account the optional `options`) and returns whether the `input` matches the `type`. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js typeCheck('Number', 2); // true ``` ### parseType(type) `parseType` parses string `type` written in the [type format](#type-format) into an object representing the parsed type. ##### arguments * type - `String` - the type written in the [type format](#type-format) which to parse ##### returns `Object` - an object in the parsed type format representing the parsed type ##### example ```js parseType('Number'); // [{type: 'Number'}] ``` ### parsedTypeCheck(parsedType, input, options) `parsedTypeCheck` checks a JavaScript value `input` against parsed `type` in the parsed type format (and taking account the optional `options`) and returns whether the `input` matches the `type`. Use this in conjunction with `parseType` if you are going to use a type more than once. ##### arguments * type - `Object` - the type in the parsed type format which to check against * input - `*` - any JavaScript value, which is to be checked against the type * options - `Maybe Object` - an optional parameter specifying additional options, currently the only available option is specifying [custom types](#custom-types) ##### returns `Boolean` - whether the input matches the type ##### example ```js parsedTypeCheck([{type: 'Number'}], 2); // true var parsedType = parseType('String'); parsedTypeCheck(parsedType, 'str'); // true ``` <a name="type-format" /> ## Type Format ### Syntax White space is ignored. The root node is a __Types__. * __Identifier__ = `[\$\w]+` - a group of any lower or upper case letters, numbers, underscores, or dollar signs - eg. `String` * __Type__ = an `Identifier`, an `Identifier` followed by a `Structure`, just a `Structure`, or a wildcard `*` - eg. `String`, `Object{x: Number}`, `{x: Number}`, `Array{0: String, 1: Boolean, length: Number}`, `*` * __Types__ = optionally a comment (an `Identifier` followed by a `::`), optionally the identifier `Maybe`, one or more `Type`, separated by `|` - eg. `Number`, `String | Date`, `Maybe Number`, `Maybe Boolean | String` * __Structure__ = `Fields`, or a `Tuple`, or an `Array` - eg. `{x: Number}`, `(String, Number)`, `[Date]` * __Fields__ = a `{`, followed one or more `Field` separated by a comma `,` (trailing comma `,` is permitted), optionally an `...` (always preceded by a comma `,`), followed by a `}` - eg. `{x: Number, y: String}`, `{k: Function, ...}` * __Field__ = an `Identifier`, followed by a colon `:`, followed by `Types` - eg. `x: Date | String`, `y: Boolean` * __Tuple__ = a `(`, followed by one or more `Types` separated by a comma `,` (trailing comma `,` is permitted), followed by a `)` - eg `(Date)`, `(Number, Date)` * __Array__ = a `[` followed by exactly one `Types` followed by a `]` - eg. `[Boolean]`, `[Boolean | Null]` ### Guide `type-check` uses `Object.toString` to find out the basic type of a value. Specifically, ```js {}.toString.call(VALUE).slice(8, -1) {}.toString.call(true).slice(8, -1) // 'Boolean' ``` A basic type, eg. `Number`, uses this check. This is much more versatile than using `typeof` - for example, with `document`, `typeof` produces `'object'` which isn't that useful, and our technique produces `'HTMLDocument'`. You may check for multiple types by separating types with a `|`. The checker proceeds from left to right, and passes if the value is any of the types - eg. `String | Boolean` first checks if the value is a string, and then if it is a boolean. If it is none of those, then it returns false. Adding a `Maybe` in front of a list of multiple types is the same as also checking for `Null` and `Undefined` - eg. `Maybe String` is equivalent to `Undefined | Null | String`. You may add a comment to remind you of what the type is for by following an identifier with a `::` before a type (or multiple types). The comment is simply thrown out. The wildcard `*` matches all types. There are three types of structures for checking the contents of a value: 'fields', 'tuple', and 'array'. If used by itself, a 'fields' structure will pass with any type of object as long as it is an instance of `Object` and the properties pass - this allows for duck typing - eg. `{x: Boolean}`. To check if the properties pass, and the value is of a certain type, you can specify the type - eg. `Error{message: String}`. If you want to make a field optional, you can simply use `Maybe` - eg. `{x: Boolean, y: Maybe String}` will still pass if `y` is undefined (or null). If you don't care if the value has properties beyond what you have specified, you can use the 'etc' operator `...` - eg. `{x: Boolean, ...}` will match an object with an `x` property that is a boolean, and with zero or more other properties. For an array, you must specify one or more types (separated by `|`) - it will pass for something of any length as long as each element passes the types provided - eg. `[Number]`, `[Number | String]`. A tuple checks for a fixed number of elements, each of a potentially different type. Each element is separated by a comma - eg. `(String, Number)`. An array and tuple structure check that the value is of type `Array` by default, but if another type is specified, they will check for that instead - eg. `Int32Array[Number]`. You can use the wildcard `*` to search for any type at all. Check out the [type precedence](https://github.com/zaboco/type-precedence) library for type-check. ## Options Options is an object. It is an optional parameter to the `typeCheck` and `parsedTypeCheck` functions. The only current option is `customTypes`. <a name="custom-types" /> ### Custom Types __Example:__ ```js var options = { customTypes: { Even: { typeOf: 'Number', validate: function(x) { return x % 2 === 0; } } } }; typeCheck('Even', 2, options); // true typeCheck('Even', 3, options); // false ``` `customTypes` allows you to set up custom types for validation. The value of this is an object. The keys of the object are the types you will be matching. Each value of the object will be an object having a `typeOf` property - a string, and `validate` property - a function. The `typeOf` property is the type the value should be (optional - if not set only `validate` will be used), and `validate` is a function which should return true if the value is of that type. `validate` receives one parameter, which is the value that we are checking. ## Technical About `type-check` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It also uses the [prelude.ls](http://preludels.com/) library. [![npm version](https://img.shields.io/npm/v/espree.svg)](https://www.npmjs.com/package/espree) [![Build Status](https://travis-ci.org/eslint/espree.svg?branch=master)](https://travis-ci.org/eslint/espree) [![npm downloads](https://img.shields.io/npm/dm/espree.svg)](https://www.npmjs.com/package/espree) [![Bountysource](https://www.bountysource.com/badge/tracker?tracker_id=9348450)](https://www.bountysource.com/trackers/9348450-eslint?utm_source=9348450&utm_medium=shield&utm_campaign=TRACKER_BADGE) # Espree Espree started out as a fork of [Esprima](http://esprima.org) v1.2.2, the last stable published released of Esprima before work on ECMAScript 6 began. Espree is now built on top of [Acorn](https://github.com/ternjs/acorn), which has a modular architecture that allows extension of core functionality. The goal of Espree is to produce output that is similar to Esprima with a similar API so that it can be used in place of Esprima. ## Usage Install: ``` npm i espree ``` And in your Node.js code: ```javascript const espree = require("espree"); const ast = espree.parse(code); ``` ## API ### `parse()` `parse` parses the given code and returns a abstract syntax tree (AST). It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). ```javascript const espree = require("espree"); const ast = espree.parse(code, options); ``` **Example :** ```js const ast = espree.parse('let foo = "bar"', { ecmaVersion: 6 }); console.log(ast); ``` <details><summary>Output</summary> <p> ``` Node { type: 'Program', start: 0, end: 15, body: [ Node { type: 'VariableDeclaration', start: 0, end: 15, declarations: [Array], kind: 'let' } ], sourceType: 'script' } ``` </p> </details> ### `tokenize()` `tokenize` returns the tokens of a given code. It takes two parameters. - `code` [string]() - the code which needs to be parsed. - `options (Optional)` [Object]() - read more about this [here](#options). Even if `options` is empty or undefined or `options.tokens` is `false`, it assigns it to `true` in order to get the `tokens` array **Example :** ```js const tokens = espree.tokenize('let foo = "bar"', { ecmaVersion: 6 }); console.log(tokens); ``` <details><summary>Output</summary> <p> ``` Token { type: 'Keyword', value: 'let', start: 0, end: 3 }, Token { type: 'Identifier', value: 'foo', start: 4, end: 7 }, Token { type: 'Punctuator', value: '=', start: 8, end: 9 }, Token { type: 'String', value: '"bar"', start: 10, end: 15 } ``` </p> </details> ### `version` Returns the current `espree` version ### `VisitorKeys` Returns all visitor keys for traversing the AST from [eslint-visitor-keys](https://github.com/eslint/eslint-visitor-keys) ### `latestEcmaVersion` Returns the latest ECMAScript supported by `espree` ### `supportedEcmaVersions` Returns an array of all supported ECMAScript versions ## Options ```js const options = { // attach range information to each node range: false, // attach line/column location information to each node loc: false, // create a top-level comments array containing all comments comment: false, // create a top-level tokens array containing all tokens tokens: false, // Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. // You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming. ecmaVersion: 5, // specify which type of script you're parsing ("script" or "module") sourceType: "script", // specify additional language features ecmaFeatures: { // enable JSX parsing jsx: false, // enable return in global scope globalReturn: false, // enable implied strict mode (if ecmaVersion >= 5) impliedStrict: false } } ``` ## Esprima Compatibility Going Forward The primary goal is to produce the exact same AST structure and tokens as Esprima, and that takes precedence over anything else. (The AST structure being the [ESTree](https://github.com/estree/estree) API with JSX extensions.) Separate from that, Espree may deviate from what Esprima outputs in terms of where and how comments are attached, as well as what additional information is available on AST nodes. That is to say, Espree may add more things to the AST nodes than Esprima does but the overall AST structure produced will be the same. Espree may also deviate from Esprima in the interface it exposes. ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/espree/issues). Espree is licensed under a permissive BSD 2-clause license. ## Security Policy We work hard to ensure that Espree is safe for everyone and that security issues are addressed quickly and responsibly. Read the full [security policy](https://github.com/eslint/.github/blob/master/SECURITY.md). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting * `npm run browserify` - creates a version of Espree that is usable in a browser ## Differences from Espree 2.x * The `tokenize()` method does not use `ecmaFeatures`. Any string will be tokenized completely based on ECMAScript 6 semantics. * Trailing whitespace no longer is counted as part of a node. * `let` and `const` declarations are no longer parsed by default. You must opt-in by using an `ecmaVersion` newer than `5` or setting `sourceType` to `module`. * The `esparse` and `esvalidate` binary scripts have been removed. * There is no `tolerant` option. We will investigate adding this back in the future. ## Known Incompatibilities In an effort to help those wanting to transition from other parsers to Espree, the following is a list of noteworthy incompatibilities with other parsers. These are known differences that we do not intend to change. ### Esprima 1.2.2 * Esprima counts trailing whitespace as part of each AST node while Espree does not. In Espree, the end of a node is where the last token occurs. * Espree does not parse `let` and `const` declarations by default. * Error messages returned for parsing errors are different. * There are two addition properties on every node and token: `start` and `end`. These represent the same data as `range` and are used internally by Acorn. ### Esprima 2.x * Esprima 2.x uses a different comment attachment algorithm that results in some comments being added in different places than Espree. The algorithm Espree uses is the same one used in Esprima 1.2.2. ## Frequently Asked Questions ### Why another parser [ESLint](http://eslint.org) had been relying on Esprima as its parser from the beginning. While that was fine when the JavaScript language was evolving slowly, the pace of development increased dramatically and Esprima had fallen behind. ESLint, like many other tools reliant on Esprima, has been stuck in using new JavaScript language features until Esprima updates, and that caused our users frustration. We decided the only way for us to move forward was to create our own parser, bringing us inline with JSHint and JSLint, and allowing us to keep implementing new features as we need them. We chose to fork Esprima instead of starting from scratch in order to move as quickly as possible with a compatible API. With Espree 2.0.0, we are no longer a fork of Esprima but rather a translation layer between Acorn and Esprima syntax. This allows us to put work back into a community-supported parser (Acorn) that is continuing to grow and evolve while maintaining an Esprima-compatible parser for those utilities still built on Esprima. ### Have you tried working with Esprima? Yes. Since the start of ESLint, we've regularly filed bugs and feature requests with Esprima and will continue to do so. However, there are some different philosophies around how the projects work that need to be worked through. The initial goal was to have Espree track Esprima and eventually merge the two back together, but we ultimately decided that building on top of Acorn was a better choice due to Acorn's plugin support. ### Why don't you just use Acorn? Acorn is a great JavaScript parser that produces an AST that is compatible with Esprima. Unfortunately, ESLint relies on more than just the AST to do its job. It relies on Esprima's tokens and comment attachment features to get a complete picture of the source code. We investigated switching to Acorn, but the inconsistencies between Esprima and Acorn created too much work for a project like ESLint. We are building on top of Acorn, however, so that we can contribute back and help make Acorn even better. ### What ECMAScript features do you support? Espree supports all ECMAScript 2020 features and partially supports ECMAScript 2021 features. Because ECMAScript 2021 is still under development, we are implementing features as they are finalized. Currently, Espree supports: * [Logical Assignment Operators](https://github.com/tc39/proposal-logical-assignment) * [Numeric Separators](https://github.com/tc39/proposal-numeric-separator) See [finished-proposals.md](https://github.com/tc39/proposals/blob/master/finished-proposals.md) to know what features are finalized. ### How do you determine which experimental features to support? In general, we do not support experimental JavaScript features. We may make exceptions from time to time depending on the maturity of the features. # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![build](https://github.com/epoberezkin/json-schema-traverse/workflows/build/badge.svg)](https://github.com/epoberezkin/json-schema-traverse/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/json-schema-traverse)](https://www.npmjs.com/package/json-schema-traverse) [![coverage](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## Enterprise support json-schema-traverse package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-json-schema-traverse?utm_source=npm-json-schema-traverse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # ts-mixer [version-badge]: https://badgen.net/npm/v/ts-mixer [version-link]: https://npmjs.com/package/ts-mixer [build-badge]: https://img.shields.io/github/workflow/status/tannerntannern/ts-mixer/ts-mixer%20CI [build-link]: https://github.com/tannerntannern/ts-mixer/actions [ts-versions]: https://badgen.net/badge/icon/3.8,3.9,4.0,4.1,4.2?icon=typescript&label&list=| [node-versions]: https://badgen.net/badge/node/10%2C12%2C14/blue/?list=| [![npm version][version-badge]][version-link] [![github actions][build-badge]][build-link] [![TS Versions][ts-versions]][build-link] [![Node.js Versions][node-versions]][build-link] [![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) [![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) ## Overview `ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. [Quick start guide](#quick-start) ### Features * mixes plain classes * mixes classes that extend other classes * mixes classes that were mixed with `ts-mixer` * supports static properties * supports protected/private properties (the popular function-that-returns-a-class solution does not) * mixes abstract classes (with caveats [[1](#caveats)]) * mixes generic classes (with caveats [[2](#caveats)]) * supports class, method, and property decorators (with caveats [[3, 6](#caveats)]) * mostly supports the complexity presented by constructor functions (with caveats [[4](#caveats)]) * comes with an `instanceof`-like replacement (with caveats [[5, 6](#caveats)]) * [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) ### Caveats 1. Mixing abstract classes requires a bit of a hack that may break in future versions of TypeScript. See [mixing abstract classes](#mixing-abstract-classes) below. 2. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. 3. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. 4. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. 5. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. 6. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. ## Quick Start ### Installation ``` $ npm install ts-mixer ``` or if you prefer [Yarn](https://yarnpkg.com): ``` $ yarn add ts-mixer ``` ### Basic Example ```typescript import { Mixin } from 'ts-mixer'; class Foo { protected makeFoo() { return 'foo'; } } class Bar { protected makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { public makeFooBar() { return this.makeFoo() + this.makeBar(); } } const fooBar = new FooBar(); console.log(fooBar.makeFooBar()); // "foobar" ``` ## Special Cases ### Mixing Abstract Classes Abstract classes, by definition, cannot be constructed, which means they cannot take on the type, `new(...args) => any`, and by extension, are incompatible with `ts-mixer`. BUT, you can "trick" TypeScript into giving you all the benefits of an abstract class without making it technically abstract. The trick is just some strategic `// @ts-ignore`'s: ```typescript import { Mixin } from 'ts-mixer'; // note that Foo is not marked as an abstract class class Foo { // @ts-ignore: "Abstract methods can only appear within an abstract class" public abstract makeFoo(): string; } class Bar { public makeBar() { return 'bar'; } } class FooBar extends Mixin(Foo, Bar) { // we still get all the benefits of abstract classes here, because TypeScript // will still complain if this method isn't implemented public makeFoo() { return 'foo'; } } ``` Do note that while this does work quite well, it is a bit of a hack and I can't promise that it will continue to work in future TypeScript versions. ### Mixing Generic Classes Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: ```typescript import { mix } from 'ts-mixer'; class Foo<T> { public fooMethod(input: T): T { return input; } } class Bar<T> { public barMethod(input: T): T { return input; } } interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { } @mix(Foo, Bar) class FooBar<T1, T2> { public fooBarMethod(input1: T1, input2: T2) { return [this.fooMethod(input1), this.barMethod(input2)]; } } ``` Key takeaways from this example: * `interface FooBar<T1, T2> extends Foo<T1>, Bar<T2> { }` makes sure `FooBar` has the typing we want, thanks to declaration merging * `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. * The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. ### Mixing with Decorators Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: ```typescript import { IsBoolean, IsIn, validate } from 'class-validator'; import { Mixin, decorate } from 'ts-mixer'; class Disposable { @decorate(IsBoolean()) // instead of @IsBoolean() isDisposed: boolean = false; } class Statusable { @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) status: string = 'green'; } class ExtendedObject extends Mixin(Disposable, Statusable) {} const extendedObject = new ExtendedObject(); extendedObject.status = 'blue'; validate(extendedObject).then(errors => { console.log(errors); }); ``` ### Dealing with Constructors As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. **This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: ```typescript import { Mixin, settings } from 'ts-mixer'; settings.initFunction = 'init'; class Person { public static allPeople: Set<Person> = new Set(); protected init() { Person.allPeople.add(this); } } type PartyAffiliation = 'democrat' | 'republican'; class PoliticalParticipant { public static democrats: Set<PoliticalParticipant> = new Set(); public static republicans: Set<PoliticalParticipant> = new Set(); public party: PartyAffiliation; // note that these same args will also be passed to init function public constructor(party: PartyAffiliation) { this.party = party; } protected init(party: PartyAffiliation) { if (party === 'democrat') PoliticalParticipant.democrats.add(this); else PoliticalParticipant.republicans.add(this); } } class Voter extends Mixin(Person, PoliticalParticipant) {} const v1 = new Voter('democrat'); const v2 = new Voter('democrat'); const v3 = new Voter('republican'); const v4 = new Voter('republican'); ``` Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. ## Other Features ### hasMixin As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: ```typescript import { Mixin, hasMixin } from 'ts-mixer'; class Foo {} class Bar {} class FooBar extends Mixin(Foo, Bar) {} const instance = new FooBar(); // doesn't work with instanceof... console.log(instance instanceof FooBar) // true console.log(instance instanceof Foo) // false console.log(instance instanceof Bar) // false // but everything works nicely with hasMixin! console.log(hasMixin(instance, FooBar)) // true console.log(hasMixin(instance, Foo)) // true console.log(hasMixin(instance, Bar)) // true ``` `hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): ```typescript if (hasMixin(instance, Foo)) { // inferred type of instance is "Foo" } if (hasMixin(instance, Bar)) { // inferred type of instance of "Bar" } ``` ## Settings ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: ```typescript import { settings, Mixin } from 'ts-mixer'; settings.prototypeStrategy = 'proxy'; // then use `Mixin` as normal... ``` ### `settings.prototypeStrategy` * Determines how ts-mixer will mix class prototypes together * Possible values: - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. ### `settings.staticsStrategy` * Determines how static properties are inherited * Possible values: - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. ### `settings.initFunction` * If set, `ts-mixer` will automatically call the function with this name upon construction * Possible values: - `null` (default) - disables the behavior - a string - function name to call upon construction * Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) ### `settings.decoratorInheritance` * Determines how decorators are inherited from classes passed to `Mixin(...)` * Possible values: - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors - `'direct'` - Only inherits decorators defined directly on the given classes - `'none'` - Skips decorator inheritance # Author Tanner Nielsen <[email protected]> * Website - [tannernielsen.com](http://tannernielsen.com) * Github - [tannerntannern](https://github.com/tannerntannern) <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # Optionator <a name="optionator" /> Optionator is a JavaScript/Node.js option parsing and help generation library used by [eslint](http://eslint.org), [Grasp](http://graspjs.com), [LiveScript](http://livescript.net), [esmangle](https://github.com/estools/esmangle), [escodegen](https://github.com/estools/escodegen), and [many more](https://www.npmjs.com/browse/depended/optionator). For an online demo, check out the [Grasp online demo](http://www.graspjs.com/#demo). [About](#about) &middot; [Usage](#usage) &middot; [Settings Format](#settings-format) &middot; [Argument Format](#argument-format) ## Why? The problem with other option parsers, such as `yargs` or `minimist`, is they just accept all input, valid or not. With Optionator, if you mistype an option, it will give you an error (with a suggestion for what you meant). If you give the wrong type of argument for an option, it will give you an error rather than supplying the wrong input to your application. $ cmd --halp Invalid option '--halp' - perhaps you meant '--help'? $ cmd --count str Invalid value for option 'count' - expected type Int, received value: str. Other helpful features include reformatting the help text based on the size of the console, so that it fits even if the console is narrow, and accepting not just an array (eg. process.argv), but a string or object as well, making things like testing much easier. ## About Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types. MIT license. Version 0.9.1 npm install optionator For updates on Optionator, [follow me on twitter](https://twitter.com/gkzahariev). Optionator is a Node.js module, but can be used in the browser as well if packed with webpack/browserify. ## Usage `require('optionator');` returns a function. It has one property, `VERSION`, the current version of the library as a string. This function is called with an object specifying your options and other information, see the [settings format section](#settings-format). This in turn returns an object with three properties, `parse`, `parseArgv`, `generateHelp`, and `generateHelpForOption`, which are all functions. ```js var optionator = require('optionator')({ prepend: 'Usage: cmd [options]', append: 'Version 1.0.0', options: [{ option: 'help', alias: 'h', type: 'Boolean', description: 'displays help' }, { option: 'count', alias: 'c', type: 'Int', description: 'number of things', example: 'cmd --count 2' }] }); var options = optionator.parseArgv(process.argv); if (options.help) { console.log(optionator.generateHelp()); } ... ``` ### parse(input, parseOptions) `parse` processes the `input` according to your settings, and returns an object with the results. ##### arguments * input - `[String] | Object | String` - the input you wish to parse * parseOptions - `{slice: Int}` - all options optional - `slice` specifies how much to slice away from the beginning if the input is an array or string - by default `0` for string, `2` for array (works with `process.argv`) ##### returns `Object` - the parsed options, each key is a camelCase version of the option name (specified in dash-case), and each value is the processed value for that option. Positional values are in an array under the `_` key. ##### example ```js parse(['node', 't.js', '--count', '2', 'positional']); // {count: 2, _: ['positional']} parse('--count 2 positional'); // {count: 2, _: ['positional']} parse({count: 2, _:['positional']}); // {count: 2, _: ['positional']} ``` ### parseArgv(input) `parseArgv` works exactly like `parse`, but only for array input and it slices off the first two elements. ##### arguments * input - `[String]` - the input you wish to parse ##### returns See "returns" section in "parse" ##### example ```js parseArgv(process.argv); ``` ### generateHelp(helpOptions) `generateHelp` produces help text based on your settings. ##### arguments * helpOptions - `{showHidden: Boolean, interpolate: Object}` - all options optional - `showHidden` specifies whether to show options with `hidden: true` specified, by default it is `false` - `interpolate` specify data to be interpolated in `prepend` and `append` text, `{{key}}` is the format - eg. `generateHelp({interpolate:{version: '0.4.2'}})`, will change this `append` text: `Version {{version}}` to `Version 0.4.2` ##### returns `String` - the generated help text ##### example ```js generateHelp(); /* "Usage: cmd [options] positional -h, --help displays help -c, --count Int number of things Version 1.0.0 "*/ ``` ### generateHelpForOption(optionName) `generateHelpForOption` produces expanded help text for the specified with `optionName` option. If an `example` was specified for the option, it will be displayed, and if a `longDescription` was specified, it will display that instead of the `description`. ##### arguments * optionName - `String` - the name of the option to display ##### returns `String` - the generated help text for the option ##### example ```js generateHelpForOption('count'); /* "-c, --count Int description: number of things example: cmd --count 2 "*/ ``` ## Settings Format When your `require('optionator')`, you get a function that takes in a settings object. This object has the type: { prepend: String, append: String, options: [{heading: String} | { option: String, alias: [String] | String, type: String, enum: [String], default: String, restPositional: Boolean, required: Boolean, overrideRequired: Boolean, dependsOn: [String] | String, concatRepeatedArrays: Boolean | (Boolean, Object), mergeRepeatedObjects: Boolean, description: String, longDescription: String, example: [String] | String }], helpStyle: { aliasSeparator: String, typeSeparator: String, descriptionSeparator: String, initialIndent: Int, secondaryIndent: Int, maxPadFactor: Number }, mutuallyExclusive: [[String | [String]]], concatRepeatedArrays: Boolean | (Boolean, Object), // deprecated, set in defaults object mergeRepeatedObjects: Boolean, // deprecated, set in defaults object positionalAnywhere: Boolean, typeAliases: Object, defaults: Object } All of the properties are optional (the `Maybe` has been excluded for brevities sake), except for having either `heading: String` or `option: String` in each object in the `options` array. ### Top Level Properties * `prepend` is an optional string to be placed before the options in the help text * `append` is an optional string to be placed after the options in the help text * `options` is a required array specifying your options and headings, the options and headings will be displayed in the order specified * `helpStyle` is an optional object which enables you to change the default appearance of some aspects of the help text * `mutuallyExclusive` is an optional array of arrays of either strings or arrays of strings. The top level array is a list of rules, each rule is a list of elements - each element can be either a string (the name of an option), or a list of strings (a group of option names) - there will be an error if more than one element is present * `concatRepeatedArrays` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `mergeRepeatedObjects` see description under the "Option Properties" heading - use at the top level is deprecated, if you want to set this for all options, use the `defaults` property * `positionalAnywhere` is an optional boolean (defaults to `true`) - when `true` it allows positional arguments anywhere, when `false`, all arguments after the first positional one are taken to be positional as well, even if they look like a flag. For example, with `positionalAnywhere: false`, the arguments `--flag --boom 12 --crack` would have two positional arguments: `12` and `--crack` * `typeAliases` is an optional object, it allows you to set aliases for types, eg. `{Path: 'String'}` would allow you to use the type `Path` as an alias for the type `String` * `defaults` is an optional object following the option properties format, which specifies default values for all options. A default will be overridden if manually set. For example, you can do `default: { type: "String" }` to set the default type of all options to `String`, and then override that default in an individual option by setting the `type` property #### Heading Properties * `heading` a required string, the name of the heading #### Option Properties * `option` the required name of the option - use dash-case, without the leading dashes * `alias` is an optional string or array of strings which specify any aliases for the option * `type` is a required string in the [type check](https://github.com/gkz/type-check) [format](https://github.com/gkz/type-check#type-format), this will be used to cast the inputted value and validate it * `enum` is an optional array of strings, each string will be parsed by [levn](https://github.com/gkz/levn) - the argument value must be one of the resulting values - each potential value must validate against the specified `type` * `default` is a optional string, which will be parsed by [levn](https://github.com/gkz/levn) and used as the default value if none is set - the value must validate against the specified `type` * `restPositional` is an optional boolean - if set to `true`, everything after the option will be taken to be a positional argument, even if it looks like a named argument * `required` is an optional boolean - if set to `true`, the option parsing will fail if the option is not defined * `overrideRequired` is a optional boolean - if set to `true` and the option is used, and there is another option which is required but not set, it will override the need for the required option and there will be no error - this is useful if you have required options and want to use `--help` or `--version` flags * `concatRepeatedArrays` is an optional boolean or tuple with boolean and options object (defaults to `false`) - when set to `true` and an option contains an array value and is repeated, the subsequent values for the flag will be appended rather than overwriting the original value - eg. option `g` of type `[String]`: `-g a -g b -g c,d` will result in `['a','b','c','d']` You can supply an options object by giving the following value: `[true, options]`. The one currently supported option is `oneValuePerFlag`, this only allows one array value per flag. This is useful if your potential values contain a comma. * `mergeRepeatedObjects` is an optional boolean (defaults to `false`) - when set to `true` and an option contains an object value and is repeated, the subsequent values for the flag will be merged rather than overwriting the original value - eg. option `g` of type `Object`: `-g a:1 -g b:2 -g c:3,d:4` will result in `{a: 1, b: 2, c: 3, d: 4}` * `dependsOn` is an optional string or array of strings - if simply a string (the name of another option), it will make sure that that other option is set, if an array of strings, depending on whether `'and'` or `'or'` is first, it will either check whether all (`['and', 'option-a', 'option-b']`), or at least one (`['or', 'option-a', 'option-b']`) other options are set * `description` is an optional string, which will be displayed next to the option in the help text * `longDescription` is an optional string, it will be displayed instead of the `description` when `generateHelpForOption` is used * `example` is an optional string or array of strings with example(s) for the option - these will be displayed when `generateHelpForOption` is used #### Help Style Properties * `aliasSeparator` is an optional string, separates multiple names from each other - default: ' ,' * `typeSeparator` is an optional string, separates the type from the names - default: ' ' * `descriptionSeparator` is an optional string , separates the description from the padded name and type - default: ' ' * `initialIndent` is an optional int - the amount of indent for options - default: 2 * `secondaryIndent` is an optional int - the amount of indent if wrapped fully (in addition to the initial indent) - default: 4 * `maxPadFactor` is an optional number - affects the default level of padding for the names/type, it is multiplied by the average of the length of the names/type - default: 1.5 ## Argument Format At the highest level there are two types of arguments: named, and positional. Name arguments of any length are prefixed with `--` (eg. `--go`), and those of one character may be prefixed with either `--` or `-` (eg. `-g`). There are two types of named arguments: boolean flags (eg. `--problemo`, `-p`) which take no value and result in a `true` if they are present, the falsey `undefined` if they are not present, or `false` if present and explicitly prefixed with `no` (eg. `--no-problemo`). Named arguments with values (eg. `--tseries 800`, `-t 800`) are the other type. If the option has a type `Boolean` it will automatically be made into a boolean flag. Any other type results in a named argument that takes a value. For more information about how to properly set types to get the value you want, take a look at the [type check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) pages. You can group single character arguments that use a single `-`, however all except the last must be boolean flags (which take no value). The last may be a boolean flag, or an argument which takes a value - eg. `-ba 2` is equivalent to `-b -a 2`. Positional arguments are all those values which do not fall under the above - they can be anywhere, not just at the end. For example, in `cmd -b one -a 2 two` where `b` is a boolean flag, and `a` has the type `Number`, there are two positional arguments, `one` and `two`. Everything after an `--` is positional, even if it looks like a named argument. You may optionally use `=` to separate option names from values, for example: `--count=2`. If you specify the option `NUM`, then any argument using a single `-` followed by a number will be valid and will set the value of `NUM`. Eg. `-2` will be parsed into `NUM: 2`. If duplicate named arguments are present, the last one will be taken. ## Technical About `optionator` is written in [LiveScript](http://livescript.net/) - a language that compiles to JavaScript. It uses [levn](https://github.com/gkz/levn) to cast arguments to their specified type, and uses [type-check](https://github.com/gkz/type-check) to validate values. It also uses the [prelude.ls](http://preludels.com/) library. # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // or promise which('node').then(resolvedPath => { ... }).catch(er => { ... not found ... }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. # near-sdk-core This package contain a convenient interface for interacting with NEAR's host runtime. To see the functions that are provided by the host node see [`env.ts`](./assembly/env/env.ts). ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <a name="table"></a> # Table > Produces a string that represents array data in a text table. [![Github action status](https://github.com/gajus/table/actions/workflows/main.yml/badge.svg)](https://github.com/gajus/table/actions) [![Coveralls](https://img.shields.io/coveralls/gajus/table.svg?style=flat-square)](https://coveralls.io/github/gajus/table) [![NPM version](http://img.shields.io/npm/v/table.svg?style=flat-square)](https://www.npmjs.org/package/table) [![Canonical Code Style](https://img.shields.io/badge/code%20style-canonical-blue.svg?style=flat-square)](https://github.com/gajus/canonical) [![Twitter Follow](https://img.shields.io/twitter/follow/kuizinas.svg?style=social&label=Follow)](https://twitter.com/kuizinas) * [Table](#table) * [Features](#table-features) * [Install](#table-install) * [Usage](#table-usage) * [API](#table-api) * [table](#table-api-table-1) * [createStream](#table-api-createstream) * [getBorderCharacters](#table-api-getbordercharacters) ![Demo of table displaying a list of missions to the Moon.](./.README/demo.png) <a name="table-features"></a> ## Features * Works with strings containing [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) characters. * Works with strings containing [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code). * Configurable border characters. * Configurable content alignment per column. * Configurable content padding per column. * Configurable column width. * Text wrapping. <a name="table-install"></a> ## Install ```bash npm install table ``` [![Buy Me A Coffee](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://www.buymeacoffee.com/gajus) [![Become a Patron](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/gajus) <a name="table-usage"></a> ## Usage ```js import { table } from 'table'; // Using commonjs? // const { table } = require('table'); const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; console.log(table(data)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ ``` <a name="table-api"></a> ## API <a name="table-api-table-1"></a> ### table Returns the string in the table format **Parameters:** - **_data_:** The data to display - Type: `any[][]` - Required: `true` - **_config_:** Table configuration - Type: `object` - Required: `false` <a name="table-api-table-1-config-border"></a> ##### config.border Type: `{ [type: string]: string }`\ Default: `honeywell` [template](#getbordercharacters) Custom borders. The keys are any of: - `topLeft`, `topRight`, `topBody`,`topJoin` - `bottomLeft`, `bottomRight`, `bottomBody`, `bottomJoin` - `joinLeft`, `joinRight`, `joinBody`, `joinJoin` - `bodyLeft`, `bodyRight`, `bodyJoin` - `headerJoin` ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: { topBody: `─`, topJoin: `┬`, topLeft: `┌`, topRight: `┐`, bottomBody: `─`, bottomJoin: `┴`, bottomLeft: `└`, bottomRight: `┘`, bodyLeft: `│`, bodyRight: `│`, bodyJoin: `│`, joinBody: `─`, joinLeft: `├`, joinRight: `┤`, joinJoin: `┼` } }; console.log(table(data, config)); ``` ``` ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ ``` <a name="table-api-table-1-config-drawverticalline"></a> ##### config.drawVerticalLine Type: `(lineIndex: number, columnCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a vertical line. This callback is called for each vertical border of the table. If the table has `n` columns, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawVerticalLine: (lineIndex, columnCount) => { return lineIndex === 0 || lineIndex === columnCount; } }; console.log(table(data, config)); ``` ``` ╔════════════╗ ║ 0A 0B 0C ║ ╟────────────╢ ║ 1A 1B 1C ║ ╟────────────╢ ║ 2A 2B 2C ║ ╟────────────╢ ║ 3A 3B 3C ║ ╟────────────╢ ║ 4A 4B 4C ║ ╚════════════╝ ``` <a name="table-api-table-1-config-drawhorizontalline"></a> ##### config.drawHorizontalLine Type: `(lineIndex: number, rowCount: number) => boolean`\ Default: `() => true` It is used to tell whether to draw a horizontal line. This callback is called for each horizontal border of the table. If the table has `n` rows, then the `index` parameter is alternatively received all numbers in range `[0, n]` inclusively. If the table has `n` rows and contains the header, then the range will be `[0, n+1]` inclusively. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ['3A', '3B', '3C'], ['4A', '4B', '4C'] ]; const config = { drawHorizontalLine: (lineIndex, rowCount) => { return lineIndex === 0 || lineIndex === 1 || lineIndex === rowCount - 1 || lineIndex === rowCount; } }; console.log(table(data, config)); ``` ``` ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ║ 2A │ 2B │ 2C ║ ║ 3A │ 3B │ 3C ║ ╟────┼────┼────╢ ║ 4A │ 4B │ 4C ║ ╚════╧════╧════╝ ``` <a name="table-api-table-1-config-singleline"></a> ##### config.singleLine Type: `boolean`\ Default: `false` If `true`, horizontal lines inside the table are not drawn. This option also overrides the `config.drawHorizontalLine` if specified. ```js const data = [ ['-rw-r--r--', '1', 'pandorym', 'staff', '1529', 'May 23 11:25', 'LICENSE'], ['-rw-r--r--', '1', 'pandorym', 'staff', '16327', 'May 23 11:58', 'README.md'], ['drwxr-xr-x', '76', 'pandorym', 'staff', '2432', 'May 23 12:02', 'dist'], ['drwxr-xr-x', '634', 'pandorym', 'staff', '20288', 'May 23 11:54', 'node_modules'], ['-rw-r--r--', '1,', 'pandorym', 'staff', '525688', 'May 23 11:52', 'package-lock.json'], ['-rw-r--r--@', '1', 'pandorym', 'staff', '2440', 'May 23 11:25', 'package.json'], ['drwxr-xr-x', '27', 'pandorym', 'staff', '864', 'May 23 11:25', 'src'], ['drwxr-xr-x', '20', 'pandorym', 'staff', '640', 'May 23 11:25', 'test'], ]; const config = { singleLine: true }; console.log(table(data, config)); ``` ``` ╔═════════════╤═════╤══════════╤═══════╤════════╤══════════════╤═══════════════════╗ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 1529 │ May 23 11:25 │ LICENSE ║ ║ -rw-r--r-- │ 1 │ pandorym │ staff │ 16327 │ May 23 11:58 │ README.md ║ ║ drwxr-xr-x │ 76 │ pandorym │ staff │ 2432 │ May 23 12:02 │ dist ║ ║ drwxr-xr-x │ 634 │ pandorym │ staff │ 20288 │ May 23 11:54 │ node_modules ║ ║ -rw-r--r-- │ 1, │ pandorym │ staff │ 525688 │ May 23 11:52 │ package-lock.json ║ ║ -rw-r--r--@ │ 1 │ pandorym │ staff │ 2440 │ May 23 11:25 │ package.json ║ ║ drwxr-xr-x │ 27 │ pandorym │ staff │ 864 │ May 23 11:25 │ src ║ ║ drwxr-xr-x │ 20 │ pandorym │ staff │ 640 │ May 23 11:25 │ test ║ ╚═════════════╧═════╧══════════╧═══════╧════════╧══════════════╧═══════════════════╝ ``` <a name="table-api-table-1-config-columns"></a> ##### config.columns Type: `Column[] | { [columnIndex: number]: Column }` Column specific configurations. <a name="table-api-table-1-config-columns-config-columns-width"></a> ###### config.columns[*].width Type: `number`\ Default: the maximum cell widths of the column Column width (excluding the paddings). ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: { 1: { width: 10 } } }; console.log(table(data, config)); ``` ``` ╔════╤════════════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────────────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────────────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════════════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-alignment"></a> ###### config.columns[*].alignment Type: `'center' | 'justify' | 'left' | 'right'`\ Default: `'left'` Cell content horizontal alignment ```js const data = [ ['0A', '0B', '0C', '0D 0E 0F'], ['1A', '1B', '1C', '1D 1E 1F'], ['2A', '2B', '2C', '2D 2E 2F'], ]; const config = { columnDefault: { width: 10, }, columns: [ { alignment: 'left' }, { alignment: 'center' }, { alignment: 'right' }, { alignment: 'justify' } ], }; console.log(table(data, config)); ``` ``` ╔════════════╤════════════╤════════════╤════════════╗ ║ 0A │ 0B │ 0C │ 0D 0E 0F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C │ 1D 1E 1F ║ ╟────────────┼────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C │ 2D 2E 2F ║ ╚════════════╧════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-verticalalignment"></a> ###### config.columns[*].verticalAlignment Type: `'top' | 'middle' | 'bottom'`\ Default: `'top'` Cell content vertical alignment ```js const data = [ ['A', 'B', 'C', 'DEF'], ]; const config = { columnDefault: { width: 1, }, columns: [ { verticalAlignment: 'top' }, { verticalAlignment: 'middle' }, { verticalAlignment: 'bottom' }, ], }; console.log(table(data, config)); ``` ``` ╔═══╤═══╤═══╤═══╗ ║ A │ │ │ D ║ ║ │ B │ │ E ║ ║ │ │ C │ F ║ ╚═══╧═══╧═══╧═══╝ ``` <a name="table-api-table-1-config-columns-config-columns-paddingleft"></a> ###### config.columns[*].paddingLeft Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the left. <a name="table-api-table-1-config-columns-config-columns-paddingright"></a> ###### config.columns[*].paddingRight Type: `number`\ Default: `1` The number of whitespaces used to pad the content on the right. The `paddingLeft` and `paddingRight` options do not count on the column width. So the column has `width = 5`, `paddingLeft = 2` and `paddingRight = 2` will have the total width is `9`. ```js const data = [ ['0A', 'AABBCC', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { columns: [ { paddingLeft: 3 }, { width: 2, paddingRight: 3 } ] }; console.log(table(data, config)); ``` ``` ╔══════╤══════╤════╗ ║ 0A │ AA │ 0C ║ ║ │ BB │ ║ ║ │ CC │ ║ ╟──────┼──────┼────╢ ║ 1A │ 1B │ 1C ║ ╟──────┼──────┼────╢ ║ 2A │ 2B │ 2C ║ ╚══════╧══════╧════╝ ``` <a name="table-api-table-1-config-columns-config-columns-truncate"></a> ###### config.columns[*].truncate Type: `number`\ Default: `Infinity` The number of characters is which the content will be truncated. To handle a content that overflows the container width, `table` package implements [text wrapping](#config.columns[*].wrapWord). However, sometimes you may want to truncate content that is too long to be displayed in the table. ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20, truncate: 100 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convall… ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columns-config-columns-wrapword"></a> ###### config.columns[*].wrapWord Type: `boolean`\ Default: `false` The `table` package implements auto text wrapping, i.e., text that has the width greater than the container width will be separated into multiple lines at the nearest space or one of the special characters: `\|/_.,;-`. When `wrapWord` is `false`: ```js const data = [ ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus pulvinar nibh sed mauris convallis dapibus. Nunc venenatis tempus nulla sit amet viverra.'] ]; const config = { columns: [ { width: 20 } ] }; console.log(table(data, config)); ``` ``` ╔══════════════════════╗ ║ Lorem ipsum dolor si ║ ║ t amet, consectetur ║ ║ adipiscing elit. Pha ║ ║ sellus pulvinar nibh ║ ║ sed mauris convallis ║ ║ dapibus. Nunc venena ║ ║ tis tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` When `wrapWord` is `true`: ``` ╔══════════════════════╗ ║ Lorem ipsum dolor ║ ║ sit amet, ║ ║ consectetur ║ ║ adipiscing elit. ║ ║ Phasellus pulvinar ║ ║ nibh sed mauris ║ ║ convallis dapibus. ║ ║ Nunc venenatis ║ ║ tempus nulla sit ║ ║ amet viverra. ║ ╚══════════════════════╝ ``` <a name="table-api-table-1-config-columndefault"></a> ##### config.columnDefault Type: `Column`\ Default: `{}` The default configuration for all columns. Column-specific settings will overwrite the default values. <a name="table-api-table-1-config-header"></a> ##### config.header Type: `object` Header configuration. *Deprecated in favor of the new spanning cells API.* The header configuration inherits the most of the column's, except: - `content` **{string}**: the header content. - `width:` calculate based on the content width automatically. - `alignment:` `center` be default. - `verticalAlignment:` is not supported. - `config.border.topJoin` will be `config.border.topBody` for prettier. ```js const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'], ]; const config = { columnDefault: { width: 10, }, header: { alignment: 'center', content: 'THE HEADER\nThis is the table about something', }, } console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════╗ ║ THE HEADER ║ ║ This is the table about something ║ ╟────────────┬────────────┬────────────╢ ║ 0A │ 0B │ 0C ║ ╟────────────┼────────────┼────────────╢ ║ 1A │ 1B │ 1C ║ ╟────────────┼────────────┼────────────╢ ║ 2A │ 2B │ 2C ║ ╚════════════╧════════════╧════════════╝ ``` <a name="table-api-table-1-config-spanningcells"></a> ##### config.spanningCells Type: `SpanningCellConfig[]` Spanning cells configuration. The configuration should be straightforward: just specify an array of minimal cell configurations including the position of top-left cell and the number of columns and/or rows will be expanded from it. The content of overlap cells will be ignored to make the `data` shape be consistent. By default, the configuration of column that the top-left cell belongs to will be applied to the whole spanning cell, except: * The `width` will be summed up of all spanning columns. * The `paddingRight` will be received from the right-most column intentionally. Advances customized column-like styles can be configurable to each spanning cell to overwrite the default behavior. ```js const data = [ ['Test Coverage Report', '', '', '', '', ''], ['Module', 'Component', 'Test Cases', 'Failures', 'Durations', 'Success Rate'], ['Services', 'User', '50', '30', '3m 7s', '60.0%'], ['', 'Payment', '100', '80', '7m 15s', '80.0%'], ['Subtotal', '', '150', '110', '10m 22s', '73.3%'], ['Controllers', 'User', '24', '18', '1m 30s', '75.0%'], ['', 'Payment', '30', '24', '50s', '80.0%'], ['Subtotal', '', '54', '42', '2m 20s', '77.8%'], ['Total', '', '204', '152', '12m 42s', '74.5%'], ]; const config = { columns: [ { alignment: 'center', width: 12 }, { alignment: 'center', width: 10 }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' }, { alignment: 'right' } ], spanningCells: [ { col: 0, row: 0, colSpan: 6 }, { col: 0, row: 2, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 4, colSpan: 2, alignment: 'right'}, { col: 0, row: 5, rowSpan: 2, verticalAlignment: 'middle'}, { col: 0, row: 7, colSpan: 2, alignment: 'right' }, { col: 0, row: 8, colSpan: 2, alignment: 'right' } ], }; console.log(table(data, config)); ``` ``` ╔══════════════════════════════════════════════════════════════════════════════╗ ║ Test Coverage Report ║ ╟──────────────┬────────────┬────────────┬──────────┬───────────┬──────────────╢ ║ Module │ Component │ Test Cases │ Failures │ Durations │ Success Rate ║ ╟──────────────┼────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 50 │ 30 │ 3m 7s │ 60.0% ║ ║ Services ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 100 │ 80 │ 7m 15s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 150 │ 110 │ 10m 22s │ 73.3% ║ ╟──────────────┬────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ User │ 24 │ 18 │ 1m 30s │ 75.0% ║ ║ Controllers ├────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ │ Payment │ 30 │ 24 │ 50s │ 80.0% ║ ╟──────────────┴────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Subtotal │ 54 │ 42 │ 2m 20s │ 77.8% ║ ╟───────────────────────────┼────────────┼──────────┼───────────┼──────────────╢ ║ Total │ 204 │ 152 │ 12m 42s │ 74.5% ║ ╚═══════════════════════════╧════════════╧══════════╧═══════════╧══════════════╝ ``` <a name="table-api-createstream"></a> ### createStream `table` package exports `createStream` function used to draw a table and append rows. **Parameter:** - _**config:**_ the same as `table`'s, except `config.columnDefault.width` and `config.columnCount` must be provided. ```js import { createStream } from 'table'; const config = { columnDefault: { width: 50 }, columnCount: 1 }; const stream = createStream(config); setInterval(() => { stream.write([new Date()]); }, 500); ``` ![Streaming current date.](./.README/api/stream/streaming.gif) `table` package uses ANSI escape codes to overwrite the output of the last line when a new row is printed. The underlying implementation is explained in this [Stack Overflow answer](http://stackoverflow.com/a/32938658/368691). Streaming supports all of the configuration properties and functionality of a static table (such as auto text wrapping, alignment and padding), e.g. ```js import { createStream } from 'table'; import _ from 'lodash'; const config = { columnDefault: { width: 50 }, columnCount: 3, columns: [ { width: 10, alignment: 'right' }, { alignment: 'center' }, { width: 10 } ] }; const stream = createStream(config); let i = 0; setInterval(() => { let random; random = _.sample('abcdefghijklmnopqrstuvwxyz', _.random(1, 30)).join(''); stream.write([i++, new Date(), random]); }, 500); ``` ![Streaming random data.](./.README/api/stream/streaming-random.gif) <a name="table-api-getbordercharacters"></a> ### getBorderCharacters **Parameter:** - **_template_** - Type: `'honeywell' | 'norc' | 'ramac' | 'void'` - Required: `true` You can load one of the predefined border templates using `getBorderCharacters` function. ```js import { table, getBorderCharacters } from 'table'; const data = [ ['0A', '0B', '0C'], ['1A', '1B', '1C'], ['2A', '2B', '2C'] ]; const config = { border: getBorderCharacters(`name of the template`) }; console.log(table(data, config)); ``` ``` # honeywell ╔════╤════╤════╗ ║ 0A │ 0B │ 0C ║ ╟────┼────┼────╢ ║ 1A │ 1B │ 1C ║ ╟────┼────┼────╢ ║ 2A │ 2B │ 2C ║ ╚════╧════╧════╝ # norc ┌────┬────┬────┐ │ 0A │ 0B │ 0C │ ├────┼────┼────┤ │ 1A │ 1B │ 1C │ ├────┼────┼────┤ │ 2A │ 2B │ 2C │ └────┴────┴────┘ # ramac (ASCII; for use in terminals that do not support Unicode characters) +----+----+----+ | 0A | 0B | 0C | |----|----|----| | 1A | 1B | 1C | |----|----|----| | 2A | 2B | 2C | +----+----+----+ # void (no borders; see "borderless table" section of the documentation) 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` Raise [an issue](https://github.com/gajus/table/issues) if you'd like to contribute a new border template. <a name="table-api-getbordercharacters-borderless-table"></a> #### Borderless Table Simply using `void` border character template creates a table with a lot of unnecessary spacing. To create a more pleasant to the eye table, reset the padding and remove the joining rows, e.g. ```js const output = table(data, { border: getBorderCharacters('void'), columnDefault: { paddingLeft: 0, paddingRight: 1 }, drawHorizontalLine: () => false } ); console.log(output); ``` ``` 0A 0B 0C 1A 1B 1C 2A 2B 2C ``` # hasurl [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] > Determine whether Node.js' native [WHATWG `URL`](https://nodejs.org/api/url.html#url_the_whatwg_url_api) implementation is available. ## Installation [Node.js](http://nodejs.org/) `>= 4` is required. To install, type this at the command line: ```shell npm install hasurl ``` ## Usage ```js const hasURL = require('hasurl'); if (hasURL()) { // supported } else { // fallback } ``` [npm-image]: https://img.shields.io/npm/v/hasurl.svg [npm-url]: https://npmjs.org/package/hasurl [travis-image]: https://img.shields.io/travis/stevenvachon/hasurl.svg [travis-url]: https://travis-ci.org/stevenvachon/hasurl # near-sdk-as Collection of packages used in developing NEAR smart contracts in AssemblyScript including: - [`runtime library`](https://github.com/near/near-sdk-as/tree/master/sdk-core) - AssemblyScript near runtime library - [`bindgen`](https://github.com/near/near-sdk-as/tree/master/bindgen) - AssemblyScript transformer that adds the bindings needed to (de)serialize input and outputs. - [`near-mock-vm`](https://github.com/near/near-sdk-as/tree/master/near-mock-vm) - Core of the NEAR VM compiled to WebAssembly used for running unit tests. - [`@as-pect/cli`](https://github.com/jtenner/as-pect) - AssemblyScript testing framework similar to jest. ## To Install ```sh yarn add -D near-sdk-as ``` ## Project Setup To set up a AS project to compile with the sdk add the following `asconfig.json` file to the root: ```json { "extends": "near-sdk-as/asconfig.json" } ``` Then if your main file is `assembly/index.ts`, then the project can be build with [`asbuild`](https://github.com/willemneal/asbuild): ```sh yarn asb ``` will create a release build and place it `./build/release/<name-in-package.json>.wasm` ```sh yarn asb --target debug ``` will create a debug build and place it in `./build/debug/..` ## Testing ### Unit Testing See the [sdk's as-pect tests for an example](./sdk/assembly/__tests__) of creating unit tests. Must be ending in `.spec.ts` in a `assembly/__tests__`. ## License `near-sdk-as` is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT) and [LICENSE-APACHE](LICENSE-APACHE) for details. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # `asbuild` [![Stars](https://img.shields.io/github/stars/AssemblyScript/asbuild.svg?style=social&maxAge=3600&label=Star)](https://github.com/AssemblyScript/asbuild/stargazers) *A simple build tool for [AssemblyScript](https://assemblyscript.org) projects, similar to `cargo`, etc.* ## 🚩 Table of Contents - [Installing](#-installing) - [Usage](#-usage) - [`asb init`](#asb-init---create-an-empty-project) - [`asb test`](#asb-test---run-as-pect-tests) - [`asb fmt`](#asb-fmt---format-as-files-using-eslint) - [`asb run`](#asb-run---run-a-wasi-binary) - [`asb build`](#asb-build---compile-the-project-using-asc) - [Background](#-background) ## 🔧 Installing Install it globally ``` npm install -g asbuild ``` Or, locally as dev dependencies ``` npm install --save-dev asbuild ``` ## 💡 Usage ``` Build tool for AssemblyScript projects. Usage: asb [command] [options] Commands: asb Alias of build command, to maintain back-ward compatibility [default] asb build Compile a local package and all of its dependencies [aliases: compile, make] asb init [baseDir] Create a new AS package in an given directory asb test Run as-pect tests asb fmt [paths..] This utility formats current module using eslint. [aliases: format, lint] Options: --version Show version number [boolean] --help Show help [boolean] ``` ### `asb init` - Create an empty project ``` asb init [baseDir] Create a new AS package in an given directory Positionals: baseDir Create a sample AS project in this directory [string] [default: "."] Options: --version Show version number [boolean] --help Show help [boolean] --yes Skip the interactive prompt [boolean] [default: false] ``` ### `asb test` - Run as-pect tests ``` asb test Run as-pect tests USAGE: asb test [options] -- [aspect_options] Options: --version Show version number [boolean] --help Show help [boolean] --verbose, --vv Print out arguments passed to as-pect [boolean] [default: false] ``` ### `asb fmt` - Format AS files using ESlint ``` asb fmt [paths..] This utility formats current module using eslint. Positionals: paths Paths to format [array] [default: ["."]] Initialisation: --init Generates recommended eslint config for AS Projects [boolean] Miscellaneous --lint, --dry-run Tries to fix problems without saving the changes to the file system [boolean] [default: false] Options: --version Show version number [boolean] --help Show help ``` ### `asb run` - Run a WASI binary ``` asb run Run a WASI binary USAGE: asb run [options] [binary path] -- [binary options] Positionals: binary path to Wasm binary [string] [required] Options: --version Show version number [boolean] --help Show help [boolean] --preopen, -p comma separated list of directories to open. [default: "."] ``` ### `asb build` - Compile the project using asc ``` asb build Compile a local package and all of its dependencies USAGE: asb build [entry_file] [options] -- [asc_options] Options: --version Show version number [boolean] --help Show help [boolean] --baseDir, -d Base directory of project. [string] [default: "."] --config, -c Path to asconfig file [string] [default: "./asconfig.json"] --wat Output wat file to outDir [boolean] [default: false] --outDir Directory to place built binaries. Default "./build/<target>/" [string] --target Target for compilation [string] [default: "release"] --verbose Print out arguments passed to asc [boolean] [default: false] Examples: asb build Build release of 'assembly/index.ts to build/release/packageName.wasm asb build --target release Build a release binary asb build -- --measure Pass argument to 'asc' ``` #### Defaults ##### Project structure ``` project/ package.json asconfig.json assembly/ index.ts build/ release/ project.wasm debug/ project.wasm ``` - If no entry file passed and no `entry` field is in `asconfig.json`, `project/assembly/index.ts` is assumed. - `asconfig.json` allows for options for different compile targets, e.g. release, debug, etc. `asc` defaults to the release target. - The default build directory is `./build`, and artifacts are placed at `./build/<target>/packageName.wasm`. ##### Workspaces If a `workspace` field is added to a top level `asconfig.json` file, then each path in the array is built and placed into the top level `outDir`. For example, `asconfig.json`: ```json { "workspaces": ["a", "b"] } ``` Running `asb` in the directory below will use the top level build directory to place all the binaries. ``` project/ package.json asconfig.json a/ asconfig.json assembly/ index.ts b/ asconfig.json assembly/ index.ts build/ release/ a.wasm b.wasm debug/ a.wasm b.wasm ``` To see an example in action check out the [test workspace](./tests/build_test) ## 📖 Background Asbuild started as wrapper around `asc` to provide an easier CLI interface and now has been extened to support other commands like `init`, `test` and `fmt` just like `cargo` to become a one stop build tool for AS Projects. ## 📜 License This library is provided under the open-source [MIT license](https://choosealicense.com/licenses/mit/). bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # universal-url [![NPM Version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Dependency Monitor][greenkeeper-image]][greenkeeper-url] > WHATWG [`URL`](https://developer.mozilla.org/en/docs/Web/API/URL) for Node & Browser. * For Node.js versions `>= 8`, the native implementation will be used. * For Node.js versions `< 8`, a [shim](https://npmjs.com/whatwg-url) will be used. * For web browsers without a native implementation, the same shim will be used. ## Installation [Node.js](http://nodejs.org/) `>= 6` is required. To install, type this at the command line: ```shell npm install universal-url ``` ## Usage ```js const {URL, URLSearchParams} = require('universal-url'); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` Global shim: ```js require('universal-url').shim(); const url = new URL('http://domain/'); const params = new URLSearchParams('?param=value'); ``` ## Browserify/etc The bundled file size of this library can be large for a web browser. If this is a problem, try using [universal-url-lite](https://npmjs.com/universal-url-lite) in your build as an alias for this module. [npm-image]: https://img.shields.io/npm/v/universal-url.svg [npm-url]: https://npmjs.org/package/universal-url [travis-image]: https://img.shields.io/travis/stevenvachon/universal-url.svg [travis-url]: https://travis-ci.org/stevenvachon/universal-url [greenkeeper-image]: https://badges.greenkeeper.io/stevenvachon/universal-url.svg [greenkeeper-url]: https://greenkeeper.io/ discontinuous-range =================== ``` DiscontinuousRange(1, 10).subtract(4, 6); // [ 1-3, 7-10 ] ``` [![Build Status](https://travis-ci.org/dtudury/discontinuous-range.png)](https://travis-ci.org/dtudury/discontinuous-range) this is a pretty simple module, but it exists to service another project so this'll be pretty lacking documentation. reading the test to see how this works may help. otherwise, here's an example that I think pretty much sums it up ###Example ``` var all_numbers = new DiscontinuousRange(1, 100); var bad_numbers = DiscontinuousRange(13).add(8).add(60,80); var good_numbers = all_numbers.clone().subtract(bad_numbers); console.log(good_numbers.toString()); //[ 1-7, 9-12, 14-59, 81-100 ] var random_good_number = good_numbers.index(Math.floor(Math.random() * good_numbers.length)); ``` # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `Diff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `Diff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `Diff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `Diff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `Diff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `Diff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `Diff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `Diff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `Diff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `Diff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. - `context` describes how many lines of context should be included. - `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. - `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. * `Diff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like Diff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `Diff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `Diff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `Diff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `Diff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `Diff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); const Diff = require('diff'); const one = 'beep boop'; const other = 'beep boob blah'; const diff = Diff.diffChars(one, other); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> const one = 'beep boop', other = 'beep boob blah', color = ''; let span = null; const diff = Diff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach((part) => { // green for additions, red for deletions // grey for common parts const color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](https://kpdecker.github.io/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). <p align="center"> <a href="https://assemblyscript.org" target="_blank" rel="noopener"><img width="100" src="https://avatars1.githubusercontent.com/u/28916798?s=200&v=4" alt="AssemblyScript logo"></a> </p> <p align="center"> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3ATest"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Test/master?label=test&logo=github" alt="Test status" /></a> <a href="https://github.com/AssemblyScript/assemblyscript/actions?query=workflow%3APublish"><img src="https://img.shields.io/github/workflow/status/AssemblyScript/assemblyscript/Publish/master?label=publish&logo=github" alt="Publish status" /></a> <a href="https://www.npmjs.com/package/assemblyscript"><img src="https://img.shields.io/npm/v/assemblyscript.svg?label=compiler&color=007acc&logo=npm" alt="npm compiler version" /></a> <a href="https://www.npmjs.com/package/@assemblyscript/loader"><img src="https://img.shields.io/npm/v/@assemblyscript/loader.svg?label=loader&color=007acc&logo=npm" alt="npm loader version" /></a> <a href="https://discord.gg/assemblyscript"><img src="https://img.shields.io/discord/721472913886281818.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2" alt="Discord online" /></a> </p> <p align="justify"><strong>AssemblyScript</strong> compiles a strict variant of <a href="http://www.typescriptlang.org">TypeScript</a> (basically JavaScript with types) to <a href="http://webassembly.org">WebAssembly</a> using <a href="https://github.com/WebAssembly/binaryen">Binaryen</a>. It generates lean and mean WebAssembly modules while being just an <code>npm install</code> away.</p> <h3 align="center"> <a href="https://assemblyscript.org">About</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/introduction.html">Introduction</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/quick-start.html">Quick&nbsp;start</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/examples.html">Examples</a> &nbsp;·&nbsp; <a href="https://assemblyscript.org/development.html">Development&nbsp;instructions</a> </h3> <br> <h2 align="center">Contributors</h2> <p align="center"> <a href="https://assemblyscript.org/#contributors"><img src="https://assemblyscript.org/contributors.svg" alt="Contributor logos" width="720" /></a> </p> <h2 align="center">Thanks to our sponsors!</h2> <p align="justify">Most of the core team members and most contributors do this open source work in their free time. If you use AssemblyScript for a serious task or plan to do so, and you'd like us to invest more time on it, <a href="https://opencollective.com/assemblyscript/donate" target="_blank" rel="noopener">please donate</a> to our <a href="https://opencollective.com/assemblyscript" target="_blank" rel="noopener">OpenCollective</a>. By sponsoring this project, your logo will show up below. Thank you so much for your support!</p> <p align="center"> <a href="https://assemblyscript.org/#sponsors"><img src="https://assemblyscript.org/sponsors.svg" alt="Sponsor logos" width="720" /></a> </p> [![NPM registry](https://img.shields.io/npm/v/as-bignum.svg?style=for-the-badge)](https://www.npmjs.com/package/as-bignum)[![Build Status](https://img.shields.io/travis/com/MaxGraey/as-bignum/master?style=for-the-badge)](https://travis-ci.com/MaxGraey/as-bignum)[![NPM license](https://img.shields.io/badge/license-Apache%202.0-ba68c8.svg?style=for-the-badge)](LICENSE.md) ## WebAssembly fixed length big numbers written on [AssemblyScript](https://github.com/AssemblyScript/assemblyscript) ### Status: Work in progress Provide wide numeric types such as `u128`, `u256`, `i128`, `i256` and fixed points and also its arithmetic operations. Namespace `safe` contain equivalents with overflow/underflow traps. All kind of types pretty useful for economical and cryptographic usages and provide deterministic behavior. ### Install > yarn add as-bignum or > npm i as-bignum ### Usage via AssemblyScript ```ts import { u128 } from "as-bignum"; declare function logF64(value: f64): void; declare function logU128(hi: u64, lo: u64): void; var a = u128.One; var b = u128.from(-32); // same as u128.from<i32>(-32) var c = new u128(0x1, -0xF); var d = u128.from(0x0123456789ABCDEF); // same as u128.from<i64>(0x0123456789ABCDEF) var e = u128.from('0x0123456789ABCDEF01234567'); var f = u128.fromString('11100010101100101', 2); // same as u128.from('0b11100010101100101') var r = d / c + (b << 5) + e; logF64(r.as<f64>()); logU128(r.hi, r.lo); ``` ### Usage via JavaScript/Typescript ```ts TODO ``` ### List of types - [x] [`u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u128.ts) unsigned type (tested) - [ ] [`u256`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/u256.ts) unsigned type (very basic) - [ ] `i128` signed type - [ ] `i256` signed type --- - [x] [`safe.u128`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/integer/safe/u128.ts) unsigned type (tested) - [ ] `safe.u256` unsigned type - [ ] `safe.i128` signed type - [ ] `safe.i256` signed type --- - [ ] [`fp128<Q>`](https://github.com/MaxGraey/as-bignum/blob/master/assembly/fixed/fp128.ts) generic fixed point signed type٭ (very basic for now) - [ ] `fp256<Q>` generic fixed point signed type٭ --- - [ ] `safe.fp128<Q>` generic fixed point signed type٭ - [ ] `safe.fp256<Q>` generic fixed point signed type٭ ٭ _typename_ `Q` _is a type representing count of fractional bits_ # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.4kb (gzipped, 17kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * ws \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * wss \[[RFC 6455](http://www.ietf.org/rfc/rfc6455.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP/HTTPS Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true URI.equal("https://abc.com", "HTTPS://ABC.COM:443/") === true ### WS/WSS Support URI.parse("wss://example.com/foo?bar=baz"); //returns: //{ // scheme : "wss", // host: "example.com", // resourceName: "/foo?bar=baz", // secure: true, //} URI.equal("WS://ABC.COM:80/chat#one", "ws://abc.com/chat") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "uuid", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS/Module environment, first install with npm/yarn by running on the command line: npm install uri-js # OR yarn add uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. ```sh npm install ``` ó ```sh yarn install ``` Una vez hecho esto, podemos compilar el código. ```sh npm run build ``` ó ```sh yarn build ``` El contrato compilado en WebAssembly se guarda en la carpeta `/build/release/`. Ahora solo es necesario desplegarlo en una cuenta de desarrollo. ```sh near dev-deploy build/debug/contrato.wasm ``` ### Usando variables de entorno Una vez compilado y desplegado tu proyecto, vamos a requerir identificar la cuenta neardev. Esta la puedes encontrar en el archivo `/neardev/neardev`. Podemos almacenar este contrato en una variable de entorno ejecutando lo siguiente en la consola, y sustituyendo por tu cuenta de desarrollo: ```sh export CONTRATO=dev-0000000000000-000000000 ``` Haciendo esto, podemos comprobar que la variable `CONTRATO` tiene almacenada nuestra cuenta dev. ```sh echo $CONTRATO ``` ``` ```sh npm install ``` ó ```sh yarn install ``` Una vez hecho esto, podemos compilar el código. ```sh npm run build ``` ó ```sh yarn build ``` El contrato compilado en WebAssembly se guarda en la carpeta `/build/release/`. Ahora solo es necesario desplegarlo en una cuenta de desarrollo. ```sh near dev-deploy build/debug/contrato.wasm ``` ### Usando variables de entorno Una vez compilado y desplegado tu proyecto, vamos a requerir identificar la cuenta neardev. Esta la puedes encontrar en el archivo `/neardev/neardev`. Podemos almacenar este contrato en una variable de entorno ejecutando lo siguiente en la consola, y sustituyendo por tu cuenta de desarrollo: ```sh export CONTRATO=dev-0000000000000-000000000 ``` Haciendo esto, podemos comprobar que la variable `CONTRATO` tiene almacenada nuestra cuenta dev. ```sh echo $CONTRATO ``` En este contrato tenemos las siguientes funciones: - `setSala(fecha: string)`: esta función nos permite crear la sala de la clase con un profesor asociado a esta. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near call dev-0000000000000-000000000 setSala '{"fecha":"02/06/2022"}' --accountId account.testnet ``` La respuesta esperada a la ejecución de este comando debería ser: ```sh '¡La sala fue dada de alta correctamente!' ``` - `getSalas()`: esta función nos permite ver las salas creadas hasta el momento con sus respectivo profesor, fecha, alumno, y si es que hubo alguien presente en ella con covid o no. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near view dev-0000000000000-000000000 getSalas ``` La respuesta esperada a la ejecución de este comando debería ser: ``` [ { profesor: 'account.testnet', fecha: '02/06/2022', alumnos: [], covid: false } ] ``` - `setAlumnoSala`: esta función nos permite agregar un alumno a una sala con una determinada fecha y profesor. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near call dev-0000000000000-000000000 setAlumnoSala '{"profesor":"account.testnet", "fecha":"02/06/2022"}' --accountId account2.testnet ``` La respuesta esperada a la ejecución de este comando debería ser: ``` '¡Se dio de alta al alumno en la clase seleccionada!' ``` - Re-ejecución de `getSalas()`: esta función nos permite ver las salas creadas hasta el momento con sus respectivo profesor, fecha, alumno, y si es que hubo alguien presente en ella con covid o no. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near view dev-0000000000000-000000000 getSalas ``` La respuesta esperada a la ejecución de este comando `con el nuevo alumno` debería ser: ``` [ { profesor: 'account.testnet', fecha: '02/06/2022', alumnos: [ { sender: 'account2.testnet' } ], covid: false } ] ``` - `setCovid(fecha:string)`: esta función nos permite que una persona diga en qué fechas estuvo presente en salas en caso de que presente covid. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near call dev-0000000000000-000000000 setCovid '{"fecha":"02/06/2022"}' --accountId account.testnet ``` La respuesta esperada a la ejecución de este comando `para un profesor` debería ser: ``` 'Se dara aviso urgente a todos los integrantes de las clases que diste.' ``` La respuesta esperada a la ejecución de este comando `para un alumno` debería ser: ``` 'Se dara aviso urgente a todos los integrantes de las clases a las que asististe.' ``` - Última ejecución de `getSalas()`: esta función nos permite ver las salas creadas hasta el momento con sus respectivo profesor, fecha, alumno, y si es que hubo alguien presente en ella con covid o no. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near view dev-0000000000000-000000000 getSalas ``` La respuesta esperada a la ejecución de este comando `ya sea con un profesor o alumno que avisó que tuvo covid ese día` debería ser: ``` [ { profesor: 'account.testnet', fecha: '02/06/2022', alumnos: [ { sender: 'account2.testnet' } ], covid: true } ] ``` -`setAyuda()`: esta función nos permite mandar una donación a las personas afectadas con Covid. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near call dev-0000000000000-000000000 setAyuda '' --accountId account.testnet ``` La respuesta esperada a la ejecución de este comando debería ser: ``` '¡La ayuda esta en camino!' ``` -`getCovid()`: esta función nos permite ver a quien se envió o no la donación. Para poder ejecutarla tenemos que usar el siguiente comando: ``` near view dev-0000000000000-000000000 getCovid ``` # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # [nearley](http://nearley.js.org) ↗️ [![JS.ORG](https://img.shields.io/badge/js.org-nearley-ffb400.svg?style=flat-square)](http://js.org) [![npm version](https://badge.fury.io/js/nearley.svg)](https://badge.fury.io/js/nearley) nearley is a simple, fast and powerful parsing toolkit. It consists of: 1. [A powerful, modular DSL for describing languages](https://nearley.js.org/docs/grammar) 2. [An efficient, lightweight Earley parser](https://nearley.js.org/docs/parser) 3. [Loads of tools, editor plug-ins, and other goodies!](https://nearley.js.org/docs/tooling) nearley is a **streaming** parser with support for catching **errors** gracefully and providing _all_ parsings for **ambiguous** grammars. It is compatible with a variety of **lexers** (we recommend [moo](http://github.com/tjvr/moo)). It comes with tools for creating **tests**, **railroad diagrams** and **fuzzers** from your grammars, and has support for a variety of editors and platforms. It works in both node and the browser. Unlike most other parser generators, nearley can handle *any* grammar you can define in BNF (and more!). In particular, while most existing JS parsers such as PEGjs and Jison choke on certain grammars (e.g. [left recursive ones](http://en.wikipedia.org/wiki/Left_recursion)), nearley handles them easily and efficiently by using the [Earley parsing algorithm](https://en.wikipedia.org/wiki/Earley_parser). nearley is used by a wide variety of projects: - [artificial intelligence](https://github.com/ChalmersGU-AI-course/shrdlite-course-project) and - [computational linguistics](https://wiki.eecs.yorku.ca/course_archive/2014-15/W/6339/useful_handouts) classes at universities; - [file format parsers](https://github.com/raymond-h/node-dmi); - [data-driven markup languages](https://github.com/idyll-lang/idyll-compiler); - [compilers for real-world programming languages](https://github.com/sizigi/lp5562); - and nearley itself! The nearley compiler is bootstrapped. nearley is an npm [staff pick](https://www.npmjs.com/package/npm-collection-staff-picks). ## Documentation Please visit our website https://nearley.js.org to get started! You will find a tutorial, detailed reference documents, and links to several real-world examples to get inspired. ## Contributing Please read [this document](.github/CONTRIBUTING.md) *before* working on nearley. If you are interested in contributing but unsure where to start, take a look at the issues labeled "up for grabs" on the issue tracker, or message a maintainer (@kach or @tjvr on Github). nearley is MIT licensed. A big thanks to Nathan Dinsmore for teaching me how to Earley, Aria Stewart for helping structure nearley into a mature module, and Robin Windels for bootstrapping the grammar. Additionally, Jacob Edelman wrote an experimental JavaScript parser with nearley and contributed ideas for EBNF support. Joshua T. Corbin refactored the compiler to be much, much prettier. Bojidar Marinov implemented postprocessors-in-other-languages. Shachar Itzhaky fixed a subtle bug with nullables. ## Citing nearley If you are citing nearley in academic work, please use the following BibTeX entry. ```bibtex @misc{nearley, author = "Kartik Chandra and Tim Radvan", title = "{nearley}: a parsing toolkit for {JavaScript}", year = {2014}, doi = {10.5281/zenodo.3897993}, url = {https://github.com/kach/nearley} } ``` # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # eslint-utils [![npm version](https://img.shields.io/npm/v/eslint-utils.svg)](https://www.npmjs.com/package/eslint-utils) [![Downloads/month](https://img.shields.io/npm/dm/eslint-utils.svg)](http://www.npmtrends.com/eslint-utils) [![Build Status](https://github.com/mysticatea/eslint-utils/workflows/CI/badge.svg)](https://github.com/mysticatea/eslint-utils/actions) [![Coverage Status](https://codecov.io/gh/mysticatea/eslint-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/eslint-utils) [![Dependency Status](https://david-dm.org/mysticatea/eslint-utils.svg)](https://david-dm.org/mysticatea/eslint-utils) ## 🏁 Goal This package provides utility functions and classes for make ESLint custom rules. For examples: - [getStaticValue](https://eslint-utils.mysticatea.dev/api/ast-utils.html#getstaticvalue) evaluates static value on AST. - [ReferenceTracker](https://eslint-utils.mysticatea.dev/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring. ## 📖 Usage See [documentation](https://eslint-utils.mysticatea.dev/). ## 📰 Changelog See [releases](https://github.com/mysticatea/eslint-utils/releases). ## ❤️ Contributing Welcome contributing! Please use GitHub's Issues/PRs. ### Development Tools - `npm test` runs tests and measures coverage. - `npm run clean` removes the coverage result of `npm test` command. - `npm run coverage` shows the coverage result of the last `npm test` command. - `npm run lint` runs ESLint. - `npm run watch` runs tests on each file change. # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Managing interceptors - Handling config # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` The solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. There is no way to unpipe. When data is emitted, it is immediately written to any and all pipe destinations. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` ESQuery is a library for querying the AST output by Esprima for patterns of syntax using a CSS style selector system. Check out the demo: [demo](https://estools.github.io/esquery/) The following selectors are supported: * AST node type: `ForStatement` * [wildcard](http://dev.w3.org/csswg/selectors4/#universal-selector): `*` * [attribute existence](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr]` * [attribute value](http://dev.w3.org/csswg/selectors4/#attribute-selectors): `[attr="foo"]` or `[attr=123]` * attribute regex: `[attr=/foo.*/]` or (with flags) `[attr=/foo.*/is]` * attribute conditions: `[attr!="foo"]`, `[attr>2]`, `[attr<3]`, `[attr>=2]`, or `[attr<=3]` * nested attribute: `[attr.level2="foo"]` * field: `FunctionDeclaration > Identifier.id` * [First](http://dev.w3.org/csswg/selectors4/#the-first-child-pseudo) or [last](http://dev.w3.org/csswg/selectors4/#the-last-child-pseudo) child: `:first-child` or `:last-child` * [nth-child](http://dev.w3.org/csswg/selectors4/#the-nth-child-pseudo) (no ax+b support): `:nth-child(2)` * [nth-last-child](http://dev.w3.org/csswg/selectors4/#the-nth-last-child-pseudo) (no ax+b support): `:nth-last-child(1)` * [descendant](http://dev.w3.org/csswg/selectors4/#descendant-combinators): `ancestor descendant` * [child](http://dev.w3.org/csswg/selectors4/#child-combinators): `parent > child` * [following sibling](http://dev.w3.org/csswg/selectors4/#general-sibling-combinators): `node ~ sibling` * [adjacent sibling](http://dev.w3.org/csswg/selectors4/#adjacent-sibling-combinators): `node + adjacent` * [negation](http://dev.w3.org/csswg/selectors4/#negation-pseudo): `:not(ForStatement)` * [has](https://drafts.csswg.org/selectors-4/#has-pseudo): `:has(ForStatement)` * [matches-any](http://dev.w3.org/csswg/selectors4/#matches): `:matches([attr] > :first-child, :last-child)` * [subject indicator](http://dev.w3.org/csswg/selectors4/#subject): `!IfStatement > [name="foo"]` * class of AST node: `:statement`, `:expression`, `:declaration`, `:function`, or `:pattern` [![Build Status](https://travis-ci.org/estools/esquery.png?branch=master)](https://travis-ci.org/estools/esquery) [![build status](https://app.travis-ci.com/dankogai/js-base64.svg)](https://app.travis-ci.com/github/dankogai/js-base64) # base64.js Yet another [Base64] transcoder. [Base64]: http://en.wikipedia.org/wiki/Base64 ## Install ```shell $ npm install --save js-base64 ``` ## Usage ### In Browser Locally… ```html <script src="base64.js"></script> ``` … or Directly from CDN. In which case you don't even need to install. ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> ``` This good old way loads `Base64` in the global context (`window`). Though `Base64.noConflict()` is made available, you should consider using ES6 Module to avoid tainting `window`. ### As an ES6 Module locally… ```javascript import { Base64 } from 'js-base64'; ``` ```javascript // or if you prefer no Base64 namespace import { encode, decode } from 'js-base64'; ``` or even remotely. ```html <script type="module"> // note jsdelivr.net does not automatically minify .mjs import { Base64 } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ```html <script type="module"> // or if you prefer no Base64 namespace import { encode, decode } from 'https://cdn.jsdelivr.net/npm/[email protected]/base64.mjs'; </script> ``` ### node.js (commonjs) ```javascript const {Base64} = require('js-base64'); ``` Unlike the case above, the global context is no longer modified. You can also use [esm] to `import` instead of `require`. [esm]: https://github.com/standard-things/esm ```javascript require=require('esm')(module); import {Base64} from 'js-base64'; ``` ## SYNOPSIS ```javascript let latin = 'dankogai'; let utf8 = '小飼弾' let u8s = new Uint8Array([100,97,110,107,111,103,97,105]); Base64.encode(latin); // ZGFua29nYWk= Base64.encode(latin, true)); // ZGFua29nYWk skips padding Base64.encodeURI(latin)); // ZGFua29nYWk Base64.btoa(latin); // ZGFua29nYWk= Base64.btoa(utf8); // raises exception Base64.fromUint8Array(u8s); // ZGFua29nYWk= Base64.fromUint8Array(u8s, true); // ZGFua29nYW which is URI safe Base64.encode(utf8); // 5bCP6aO85by+ Base64.encode(utf8, true) // 5bCP6aO85by- Base64.encodeURI(utf8); // 5bCP6aO85by- ``` ```javascript Base64.decode( 'ZGFua29nYWk=');// dankogai Base64.decode( 'ZGFua29nYWk'); // dankogai Base64.atob( 'ZGFua29nYWk=');// dankogai Base64.atob( '5bCP6aO85by+');// '小飼弾' which is nonsense Base64.toUint8Array('ZGFua29nYWk=');// u8s above Base64.decode( '5bCP6aO85by+');// 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode( '5bCP6aO85by-');// 小飼弾 ``` ```javascript Base64.isValid(0); // false: 0 is not string Base64.isValid(''); // true: a valid Base64-encoded empty byte Base64.isValid('ZA=='); // true: a valid Base64-encoded 'd' Base64.isValid('Z A='); // true: whitespaces are okay Base64.isValid('ZA'); // true: padding ='s can be omitted Base64.isValid('++'); // true: can be non URL-safe Base64.isValid('--'); // true: or URL-safe Base64.isValid('+-'); // false: can't mix both ``` ### Built-in Extensions By default `Base64` leaves built-in prototypes untouched. But you can extend them as below. ```javascript // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- ab alias of .toBase64(true) '小飼弾'.toBase64URL(); // 5bCP6aO85by- an alias of .toBase64URI() 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.toUint8Array();// u8s above ``` ```javascript // you have to explicitly extend Uint8Array.prototype Base64.extendUint8Array(); // once extended, you can do the following u8s.toBase64(); // 'ZGFua29nYWk=' u8s.toBase64URI(); // 'ZGFua29nYWk' u8s.toBase64URL(); // 'ZGFua29nYWk' an alias of .toBase64URI() ``` ```javascript // extend all at once Base64.extendBuiltins() ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. Or even better, `Base64.toUint8Array(pngBase64)`. ### If you really, really need an ES5 version You can transpiles to an ES5 that runs on IEs before 11. Do the following in your shell. ```shell $ make base64.es5.js ``` ## Brief History * Since version 3.3 it is written in TypeScript. Now `base64.mjs` is compiled from `base64.ts` then `base64.js` is generated from `base64.mjs`. * Since version 3.7 `base64.js` is ES5-compatible again (hence IE11-compabile). * Since 3.0 `js-base64` switch to ES2015 module so it is no longer compatible with legacy browsers like IE (see above) [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). [![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) This package is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy to use and powerful. It was first released in 2010 and is tested against big data sets by a large community. ## Documentation * [Project homepage](http://csv.js.org/stringify/) * [API](http://csv.js.org/stringify/api/) * [Options](http://csv.js.org/stringify/options/) * [Examples](http://csv.js.org/stringify/examples/) ## Main features * Follow the Node.js streaming API * Simplicity with the optional callback API * Support for custom formatters, delimiters, quotes, escape characters and header * Support big datasets * Complete test coverage and samples for inspiration * Only 1 external dependency * to be used conjointly with `csv-generate`, `csv-parse` and `stream-transform` * MIT License ## Usage The module is built on the Node.js Stream API. For the sake of simplicity, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: ```javascript const stringify = require('csv-stringify') const assert = require('assert') // import stringify from 'csv-stringify' // import assert from 'assert/strict' const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] stringify(input, function(err, output) { const expected = '1,2,3,4\na,b,c,d\n' assert.strictEqual(output, expected, `output.should.eql ${expected}`) console.log("Passed.", output) }) ``` ## Development Tests are executed with mocha. To install it, run `npm install` followed by `npm test`. It will install mocha and its dependencies in your project "node_modules" directory and run the test suite. The tests run against the CoffeeScript source files. To generate the JavaScript files, run `npm run build`. The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node-csv-stringify). See the [Travis definition file](https://github.com/adaltas/node-csv-stringify/blob/master/.travis.yml) to view the tested Node.js version. ## Contributors * David Worms: <https://github.com/wdavidw> [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform [examples]: http://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Sponsors [![Scout APM](./sponsors/scout-apm.png)](https://scoutapm.com/) My Open Source work is supported by [Scout APM](https://scoutapm.com/) and [other sponsors](https://github.com/sponsors/indutny). ## Notation ### Prefixes There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the end of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this trick one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` ## Enterprise support fast-json-stable-stringify package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-json-stable-stringify?utm_source=npm-fast-json-stable-stringify&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) # Acorn-JSX [![Build Status](https://travis-ci.org/acornjs/acorn-jsx.svg?branch=master)](https://travis-ci.org/acornjs/acorn-jsx) [![NPM version](https://img.shields.io/npm/v/acorn-jsx.svg)](https://www.npmjs.org/package/acorn-jsx) This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. It was created as an experimental alternative, faster [React.js JSX](http://facebook.github.io/react/docs/jsx-in-depth.html) parser. Later, it replaced the [official parser](https://github.com/facebookarchive/esprima) and these days is used by many prominent development tools. ## Transpiler Please note that this tool only parses source code to JSX AST, which is useful for various language tools and services. If you want to transpile your code to regular ES5-compliant JavaScript with source map, check out [Babel](https://babeljs.io/) and [Buble](https://buble.surge.sh/) transpilers which use `acorn-jsx` under the hood. ## Usage Requiring this module provides you with an Acorn plugin that you can use like this: ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); acorn.Parser.extend(jsx()).parse("my(<jsx/>, 'code');"); ``` Note that official spec doesn't support mix of XML namespaces and object-style access in tag names (#27) like in `<namespace:Object.Property />`, so it was deprecated in `[email protected]`. If you still want to opt-in to support of such constructions, you can pass the following option: ```javascript acorn.Parser.extend(jsx({ allowNamespacedObjects: true })) ``` Also, since most apps use pure React transformer, a new option was introduced that allows to prohibit namespaces completely: ```javascript acorn.Parser.extend(jsx({ allowNamespaces: false })) ``` Note that by default `allowNamespaces` is enabled for spec compliancy. ## License This plugin is issued under the [MIT license](./LICENSE). # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # eslint-visitor-keys [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) [![Build Status](https://travis-ci.org/eslint/eslint-visitor-keys.svg?branch=master)](https://travis-ci.org/eslint/eslint-visitor-keys) [![Dependency Status](https://david-dm.org/eslint/eslint-visitor-keys.svg)](https://david-dm.org/eslint/eslint-visitor-keys) Constants and utilities about visitor keys to traverse AST. ## 💿 Installation Use [npm] to install. ```bash $ npm install eslint-visitor-keys ``` ### Requirements - [Node.js] 4.0.0 or later. ## 📖 Usage ```js const evk = require("eslint-visitor-keys") ``` ### evk.KEYS > type: `{ [type: string]: string[] | undefined }` Visitor keys. This keys are frozen. This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. For example: ``` console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] ``` ### evk.getKeys(node) > type: `(node: object) => string[]` Get the visitor keys of a given AST node. This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. This will be used to traverse unknown nodes. For example: ``` const node = { type: "AssignmentExpression", left: { type: "Identifier", name: "foo" }, right: { type: "Literal", value: 0 } } console.log(evk.getKeys(node)) // → ["type", "left", "right"] ``` ### evk.unionWith(additionalKeys) > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` Make the union set with `evk.KEYS` and the given keys. - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. - It removes duplicated keys as keeping the first one. For example: ``` console.log(evk.unionWith({ MethodDefinition: ["decorators"] })) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } ``` ## 📰 Change log See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases). ## 🍻 Contributing Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). ### Development commands - `npm test` runs tests and measures code coverage. - `npm run lint` checks source codes with ESLint. - `npm run coverage` opens the code coverage report of the previous test with your default browser. - `npm run release` publishes this package to [npm] registory. [npm]: https://www.npmjs.com/ [Node.js]: https://nodejs.org/en/ [ESTree]: https://github.com/estree/estree semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # word-wrap [![NPM version](https://img.shields.io/npm/v/word-wrap.svg?style=flat)](https://www.npmjs.com/package/word-wrap) [![NPM monthly downloads](https://img.shields.io/npm/dm/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![NPM total downloads](https://img.shields.io/npm/dt/word-wrap.svg?style=flat)](https://npmjs.org/package/word-wrap) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/word-wrap.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/word-wrap) > Wrap words to a specified length. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save word-wrap ``` ## Usage ```js var wrap = require('word-wrap'); wrap('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.'); ``` Results in: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ``` ## Options ![image](https://cloud.githubusercontent.com/assets/383994/6543728/7a381c08-c4f6-11e4-8b7d-b6ba197569c9.png) ### options.width Type: `Number` Default: `50` The width of the text before wrapping to a new line. **Example:** ```js wrap(str, {width: 60}); ``` ### options.indent Type: `String` Default: `` (two spaces) The string to use at the beginning of each line. **Example:** ```js wrap(str, {indent: ' '}); ``` ### options.newline Type: `String` Default: `\n` The string to use at the end of each line. **Example:** ```js wrap(str, {newline: '\n\n'}); ``` ### options.escape Type: `function` Default: `function(str){return str;}` An escape function to run on each line after splitting them. **Example:** ```js var xmlescape = require('xml-escape'); wrap(str, { escape: function(string){ return xmlescape(string); } }); ``` ### options.trim Type: `Boolean` Default: `false` Trim trailing whitespace from the returned string. This option is included since `.trim()` would also strip the leading indentation from the first line. **Example:** ```js wrap(str, {trim: true}); ``` ### options.cut Type: `Boolean` Default: `false` Break a word between any two letters when the word is longer than the specified width. **Example:** ```js wrap(str, {cut: true}); ``` ## About ### Related projects * [common-words](https://www.npmjs.com/package/common-words): Updated list (JSON) of the 100 most common words in the English language. Useful for… [more](https://github.com/jonschlinkert/common-words) | [homepage](https://github.com/jonschlinkert/common-words "Updated list (JSON) of the 100 most common words in the English language. Useful for excluding these words from arrays.") * [shuffle-words](https://www.npmjs.com/package/shuffle-words): Shuffle the words in a string and optionally the letters in each word using the… [more](https://github.com/jonschlinkert/shuffle-words) | [homepage](https://github.com/jonschlinkert/shuffle-words "Shuffle the words in a string and optionally the letters in each word using the Fisher-Yates algorithm. Useful for creating test fixtures, benchmarking samples, etc.") * [unique-words](https://www.npmjs.com/package/unique-words): Return the unique words in a string or array. | [homepage](https://github.com/jonschlinkert/unique-words "Return the unique words in a string or array.") * [wordcount](https://www.npmjs.com/package/wordcount): Count the words in a string. Support for english, CJK and Cyrillic. | [homepage](https://github.com/jonschlinkert/wordcount "Count the words in a string. Support for english, CJK and Cyrillic.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 43 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [lordvlad](https://github.com/lordvlad) | | 2 | [hildjj](https://github.com/hildjj) | | 1 | [danilosampaio](https://github.com/danilosampaio) | | 1 | [2fd](https://github.com/2fd) | | 1 | [toddself](https://github.com/toddself) | | 1 | [wolfgang42](https://github.com/wolfgang42) | | 1 | [zachhale](https://github.com/zachhale) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 02, 2017._ # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. # assemblyscript-json ![npm version](https://img.shields.io/npm/v/assemblyscript-json) ![npm downloads per month](https://img.shields.io/npm/dm/assemblyscript-json) JSON encoder / decoder for AssemblyScript. Special thanks to https://github.com/MaxGraey/bignum.wasm for basic unit testing infra for AssemblyScript. ## Installation `assemblyscript-json` is available as a [npm package](https://www.npmjs.com/package/assemblyscript-json). You can install `assemblyscript-json` in your AssemblyScript project by running: `npm install --save assemblyscript-json` ## Usage ### Parsing JSON ```typescript import { JSON } from "assemblyscript-json"; // Parse an object using the JSON object let jsonObj: JSON.Obj = <JSON.Obj>(JSON.parse('{"hello": "world", "value": 24}')); // We can then use the .getX functions to read from the object if you know it's type // This will return the appropriate JSON.X value if the key exists, or null if the key does not exist let worldOrNull: JSON.Str | null = jsonObj.getString("hello"); // This will return a JSON.Str or null if (worldOrNull != null) { // use .valueOf() to turn the high level JSON.Str type into a string let world: string = worldOrNull.valueOf(); } let numOrNull: JSON.Num | null = jsonObj.getNum("value"); if (numOrNull != null) { // use .valueOf() to turn the high level JSON.Num type into a f64 let value: f64 = numOrNull.valueOf(); } // If you don't know the value type, get the parent JSON.Value let valueOrNull: JSON.Value | null = jsonObj.getValue("hello"); if (valueOrNull != null) { let value = <JSON.Value>valueOrNull; // Next we could figure out what type we are if(value.isString) { // value.isString would be true, so we can cast to a string let innerString = (<JSON.Str>value).valueOf(); let jsonString = (<JSON.Str>value).stringify(); // Do something with string value } } ``` ### Encoding JSON ```typescript import { JSONEncoder } from "assemblyscript-json"; // Create encoder let encoder = new JSONEncoder(); // Construct necessary object encoder.pushObject("obj"); encoder.setInteger("int", 10); encoder.setString("str", ""); encoder.popObject(); // Get serialized data let json: Uint8Array = encoder.serialize(); // Or get serialized data as string let jsonString: string = encoder.stringify(); assert(jsonString, '"obj": {"int": 10, "str": ""}'); // True! ``` ### Custom JSON Deserializers ```typescript import { JSONDecoder, JSONHandler } from "assemblyscript-json"; // Events need to be received by custom object extending JSONHandler. // NOTE: All methods are optional to implement. class MyJSONEventsHandler extends JSONHandler { setString(name: string, value: string): void { // Handle field } setBoolean(name: string, value: bool): void { // Handle field } setNull(name: string): void { // Handle field } setInteger(name: string, value: i64): void { // Handle field } setFloat(name: string, value: f64): void { // Handle field } pushArray(name: string): bool { // Handle array start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popArray(): void { // Handle array end } pushObject(name: string): bool { // Handle object start // true means that nested object needs to be traversed, false otherwise // Note that returning false means JSONDecoder.startIndex need to be updated by handler return true; } popObject(): void { // Handle object end } } // Create decoder let decoder = new JSONDecoder<MyJSONEventsHandler>(new MyJSONEventsHandler()); // Create a byte buffer of our JSON. NOTE: Deserializers work on UTF8 string buffers. let jsonString = '{"hello": "world"}'; let jsonBuffer = Uint8Array.wrap(String.UTF8.encode(jsonString)); // Parse JSON decoder.deserialize(jsonBuffer); // This will send events to MyJSONEventsHandler ``` Feel free to look through the [tests](https://github.com/nearprotocol/assemblyscript-json/tree/master/assembly/__tests__) for more usage examples. ## Reference Documentation Reference API Documentation can be found in the [docs directory](./docs). ## License [MIT](./LICENSE) # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # AssemblyScript Loader A convenient loader for [AssemblyScript](https://assemblyscript.org) modules. Demangles module exports to a friendly object structure compatible with TypeScript definitions and provides useful utility to read/write data from/to memory. [Documentation](https://assemblyscript.org/loader.html) iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Aliases Create custom aliases for styles. ```js const colors = require('ansi-colors'); colors.alias('primary', colors.yellow); colors.alias('secondary', colors.bold); console.log(colors.primary.secondary('Foo')); ``` ## Themes A theme is an object of custom aliases. ```js const colors = require('ansi-colors'); colors.theme({ danger: colors.red, dark: colors.dim.gray, disabled: colors.gray, em: colors.italic, heading: colors.bold.underline, info: colors.cyan, muted: colors.dim, primary: colors.blue, strong: colors.bold, success: colors.green, underline: colors.underline, warning: colors.yellow }); // Now, we can use our custom styles alongside the built-in styles! console.log(colors.danger.strong.em('Error!')); console.log(colors.warning('Heads up!')); console.log(colors.info('Did you know...')); console.log(colors.success.bold('It worked!')); ``` ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 48 | [jonschlinkert](https://github.com/jonschlinkert) | | 42 | [doowb](https://github.com/doowb) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on July 01, 2019._ # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. <h1 align="center">Enquirer</h1> <p align="center"> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/v/enquirer.svg" alt="version"> </a> <a href="https://travis-ci.org/enquirer/enquirer"> <img src="https://img.shields.io/travis/enquirer/enquirer.svg" alt="travis"> </a> <a href="https://npmjs.org/package/enquirer"> <img src="https://img.shields.io/npm/dm/enquirer.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <b>Stylish CLI prompts that are user-friendly, intuitive and easy to create.</b><br> <sub>>_ Prompts should be more like conversations than inquisitions▌</sub> </p> <br> <p align="center"> <sub>(Example shows Enquirer's <a href="#survey-prompt">Survey Prompt</a>)</a></sub> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"><br> <sub>The terminal in all examples is <a href="https://hyper.is/">Hyper</a>, theme is <a href="https://github.com/jonschlinkert/hyper-monokai-extended">hyper-monokai-extended</a>.</sub><br><br> <a href="#built-in-prompts"><strong>See more prompt examples</strong></a> </p> <br> <br> Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb), Enquirer is fast, easy to use, and lightweight enough for small projects, while also being powerful and customizable enough for the most advanced use cases. * **Fast** - [Loads in ~4ms](#-performance) (that's about _3-4 times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps_) * **Lightweight** - Only one dependency, the excellent [ansi-colors](https://github.com/doowb/ansi-colors) by [Brian Woodward](https://github.com/doowb). * **Easy to implement** - Uses promises and async/await and sensible defaults to make prompts easy to create and implement. * **Easy to use** - Thrill your users with a better experience! Navigating around input and choices is a breeze. You can even create [quizzes](examples/fun/countdown.js), or [record](examples/fun/record.js) and [playback](examples/fun/play.js) key bindings to aid with tutorials and videos. * **Intuitive** - Keypress combos are available to simplify usage. * **Flexible** - All prompts can be used standalone or chained together. * **Stylish** - Easily override semantic styles and symbols for any part of the prompt. * **Extensible** - Easily create and use custom prompts by extending Enquirer's built-in [prompts](#-prompts). * **Pluggable** - Add advanced features to Enquirer using plugins. * **Validation** - Optionally validate user input with any prompt. * **Well tested** - All prompts are well-tested, and tests are easy to create without having to use brittle, hacky solutions to spy on prompts or "inject" values. * **Examples** - There are numerous [examples](examples) available to help you get started. If you like Enquirer, please consider starring or tweeting about this project to show your support. Thanks! <br> <p align="center"> <b>>_ Ready to start making prompts your users will love? ▌</b><br> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/heartbeat.gif" alt="Enquirer Select Prompt with heartbeat example" width="750"> </p> <br> <br> ## ❯ Getting started Get started with Enquirer, the most powerful and easy-to-use Node.js library for creating interactive CLI prompts. * [Install](#-install) * [Usage](#-usage) * [Enquirer](#-enquirer) * [Prompts](#-prompts) - [Built-in Prompts](#-prompts) - [Custom Prompts](#-custom-prompts) * [Key Bindings](#-key-bindings) * [Options](#-options) * [Release History](#-release-history) * [Performance](#-performance) * [About](#-about) <br> ## ❯ Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install enquirer --save ``` Install with [yarn](https://yarnpkg.com/en/): ```sh $ yarn add enquirer ``` <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/npm-install.gif" alt="Install Enquirer with NPM" width="750"> </p> _(Requires Node.js 8.6 or higher. Please let us know if you need support for an earlier version by creating an [issue](../../issues/new).)_ <br> ## ❯ Usage ### Single prompt The easiest way to get started with enquirer is to pass a [question object](#prompt-options) to the `prompt` method. ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); // { username: 'jonschlinkert' } ``` _(Examples with `await` need to be run inside an `async` function)_ ### Multiple prompts Pass an array of ["question" objects](#prompt-options) to run a series of prompts. ```js const response = await prompt([ { type: 'input', name: 'name', message: 'What is your name?' }, { type: 'input', name: 'username', message: 'What is your username?' } ]); console.log(response); // { name: 'Edward Chan', username: 'edwardmchan' } ``` ### Different ways to run enquirer #### 1. By importing the specific `built-in prompt` ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Did you like enquirer?' }); prompt.run() .then(answer => console.log('Answer:', answer)); ``` #### 2. By passing the options to `prompt` ```js const { prompt } = require('enquirer'); prompt({ type: 'confirm', name: 'question', message: 'Did you like enquirer?' }) .then(answer => console.log('Answer:', answer)); ``` **Jump to**: [Getting Started](#-getting-started) · [Prompts](#-prompts) · [Options](#-options) · [Key Bindings](#-key-bindings) <br> ## ❯ Enquirer **Enquirer is a prompt runner** Add Enquirer to your JavaScript project with following line of code. ```js const Enquirer = require('enquirer'); ``` The main export of this library is the `Enquirer` class, which has methods and features designed to simplify running prompts. ```js const { prompt } = require('enquirer'); const question = [ { type: 'input', name: 'username', message: 'What is your username?' }, { type: 'password', name: 'password', message: 'What is your password?' } ]; let answers = await prompt(question); console.log(answers); ``` **Prompts control how values are rendered and returned** Each individual prompt is a class with special features and functionality for rendering the types of values you want to show users in the terminal, and subsequently returning the types of values you need to use in your application. **How can I customize prompts?** Below in this guide you will find information about creating [custom prompts](#-custom-prompts). For now, we'll focus on how to customize an existing prompt. All of the individual [prompt classes](#built-in-prompts) in this library are exposed as static properties on Enquirer. This allows them to be used directly without using `enquirer.prompt()`. Use this approach if you need to modify a prompt instance, or listen for events on the prompt. **Example** ```js const { Input } = require('enquirer'); const prompt = new Input({ name: 'username', message: 'What is your username?' }); prompt.run() .then(answer => console.log('Username:', answer)) .catch(console.error); ``` ### [Enquirer](index.js#L20) Create an instance of `Enquirer`. **Params** * `options` **{Object}**: (optional) Options to use with all prompts. * `answers` **{Object}**: (optional) Answers object to initialize with. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` ### [register()](index.js#L42) Register a custom prompt type. **Params** * `type` **{String}** * `fn` **{Function|Prompt}**: `Prompt` class, or a function that returns a `Prompt` class. * `returns` **{Object}**: Returns the Enquirer instance **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); enquirer.register('customType', require('./custom-prompt')); ``` ### [prompt()](index.js#L78) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const response = await enquirer.prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` ### [use()](index.js#L160) Use an enquirer plugin. **Params** * `plugin` **{Function}**: Plugin function that takes an instance of Enquirer. * `returns` **{Object}**: Returns the Enquirer instance. **Example** ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); const plugin = enquirer => { // do stuff to enquire instance }; enquirer.use(plugin); ``` ### [Enquirer#prompt](index.js#L210) Prompt function that takes a "question" object or array of question objects, and returns an object with responses from the user. **Params** * `questions` **{Array|Object}**: Options objects for one or more prompts to run. * `returns` **{Promise}**: Promise that returns an "answers" object with the user's responses. **Example** ```js const { prompt } = require('enquirer'); const response = await prompt({ type: 'input', name: 'username', message: 'What is your username?' }); console.log(response); ``` <br> ## ❯ Prompts This section is about Enquirer's prompts: what they look like, how they work, how to run them, available options, and how to customize the prompts or create your own prompt concept. **Getting started with Enquirer's prompts** * [Prompt](#prompt) - The base `Prompt` class used by other prompts - [Prompt Options](#prompt-options) * [Built-in prompts](#built-in-prompts) * [Prompt Types](#prompt-types) - The base `Prompt` class used by other prompts * [Custom prompts](#%E2%9D%AF-custom-prompts) - Enquirer 2.0 introduced the concept of prompt "types", with the goal of making custom prompts easier than ever to create and use. ### Prompt The base `Prompt` class is used to create all other prompts. ```js const { Prompt } = require('enquirer'); class MyCustomPrompt extends Prompt {} ``` See the documentation for [creating custom prompts](#-custom-prompts) to learn more about how this works. #### Prompt Options Each prompt takes an options object (aka "question" object), that implements the following interface: ```js { // required type: string | function, name: string | function, message: string | function | async function, // optional skip: boolean | function | async function, initial: string | function | async function, format: function | async function, result: function | async function, validate: function | async function, } ``` Each property of the options object is described below: | **Property** | **Required?** | **Type** | **Description** | | ------------ | ------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `type` | yes | `string\|function` | Enquirer uses this value to determine the type of prompt to run, but it's optional when prompts are run directly. | | `name` | yes | `string\|function` | Used as the key for the answer on the returned values (answers) object. | | `message` | yes | `string\|function` | The message to display when the prompt is rendered in the terminal. | | `skip` | no | `boolean\|function` | If `true` it will not ask that prompt. | | `initial` | no | `string\|function` | The default value to return if the user does not supply a value. | | `format` | no | `function` | Function to format user input in the terminal. | | `result` | no | `function` | Function to format the final submitted value before it's returned. | | `validate` | no | `function` | Function to validate the submitted value before it's returned. This function may return a boolean or a string. If a string is returned it will be used as the validation error message. | **Example usage** ```js const { prompt } = require('enquirer'); const question = { type: 'input', name: 'username', message: 'What is your username?' }; prompt(question) .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` <br> ### Built-in prompts * [AutoComplete Prompt](#autocomplete-prompt) * [BasicAuth Prompt](#basicauth-prompt) * [Confirm Prompt](#confirm-prompt) * [Form Prompt](#form-prompt) * [Input Prompt](#input-prompt) * [Invisible Prompt](#invisible-prompt) * [List Prompt](#list-prompt) * [MultiSelect Prompt](#multiselect-prompt) * [Numeral Prompt](#numeral-prompt) * [Password Prompt](#password-prompt) * [Quiz Prompt](#quiz-prompt) * [Survey Prompt](#survey-prompt) * [Scale Prompt](#scale-prompt) * [Select Prompt](#select-prompt) * [Sort Prompt](#sort-prompt) * [Snippet Prompt](#snippet-prompt) * [Toggle Prompt](#toggle-prompt) ### AutoComplete Prompt Prompt that auto-completes as the user types, and returns the selected value as a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/autocomplete-prompt.gif" alt="Enquirer AutoComplete Prompt" width="750"> </p> **Example Usage** ```js const { AutoComplete } = require('enquirer'); const prompt = new AutoComplete({ name: 'flavor', message: 'Pick your favorite flavor', limit: 10, initial: 2, choices: [ 'Almond', 'Apple', 'Banana', 'Blackberry', 'Blueberry', 'Cherry', 'Chocolate', 'Cinnamon', 'Coconut', 'Cranberry', 'Grape', 'Nougat', 'Orange', 'Pear', 'Pineapple', 'Raspberry', 'Strawberry', 'Vanilla', 'Watermelon', 'Wintergreen' ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **AutoComplete Options** | Option | Type | Default | Description | | ----------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `highlight` | `function` | `dim` version of primary style | The color to use when "highlighting" characters in the list that match user input. | | `multiple` | `boolean` | `false` | Allow multiple choices to be selected. | | `suggest` | `function` | Greedy match, returns true if choice message contains input string. | Function that filters choices. Takes user input and a choices array, and returns a list of matching choices. | | `initial` | `number` | 0 | Preselected item in the list of choices. | | `footer` | `function` | None | Function that displays [footer text](https://github.com/enquirer/enquirer/blob/6c2819518a1e2ed284242a99a685655fbaabfa28/examples/autocomplete/option-footer.js#L10) | **Related prompts** * [Select](#select-prompt) * [MultiSelect](#multiselect-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### BasicAuth Prompt Prompt that asks for username and password to authenticate the user. The default implementation of `authenticate` function in `BasicAuth` prompt is to compare the username and password with the values supplied while running the prompt. The implementer is expected to override the `authenticate` function with a custom logic such as making an API request to a server to authenticate the username and password entered and expect a token back. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61570485-7ffd9c00-aaaa-11e9-857a-d47dc7008284.gif" alt="Enquirer BasicAuth Prompt" width="750"> </p> **Example Usage** ```js const { BasicAuth } = require('enquirer'); const prompt = new BasicAuth({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '123', showPassword: true }); prompt .run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Confirm Prompt Prompt that returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/confirm-prompt.gif" alt="Enquirer Confirm Prompt" width="750"> </p> **Example Usage** ```js const { Confirm } = require('enquirer'); const prompt = new Confirm({ name: 'question', message: 'Want to answer?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Form Prompt Prompt that allows the user to enter and submit multiple values on a single terminal screen. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/form-prompt.gif" alt="Enquirer Form Prompt" width="750"> </p> **Example Usage** ```js const { Form } = require('enquirer'); const prompt = new Form({ name: 'user', message: 'Please provide the following information:', choices: [ { name: 'firstname', message: 'First Name', initial: 'Jon' }, { name: 'lastname', message: 'Last Name', initial: 'Schlinkert' }, { name: 'username', message: 'GitHub username', initial: 'jonschlinkert' } ] }); prompt.run() .then(value => console.log('Answer:', value)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Input Prompt Prompt that takes user input and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/input-prompt.gif" alt="Enquirer Input Prompt" width="750"> </p> **Example Usage** ```js const { Input } = require('enquirer'); const prompt = new Input({ message: 'What is your username?', initial: 'jonschlinkert' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.log); ``` You can use [data-store](https://github.com/jonschlinkert/data-store) to store [input history](https://github.com/enquirer/enquirer/blob/master/examples/input/option-history.js) that the user can cycle through (see [source](https://github.com/enquirer/enquirer/blob/8407dc3579123df5e6e20215078e33bb605b0c37/lib/prompts/input.js)). **Related prompts** * [Confirm](#confirm-prompt) * [Numeral](#numeral-prompt) * [Password](#password-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Invisible Prompt Prompt that takes user input, hides it from the terminal, and returns a string. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/invisible-prompt.gif" alt="Enquirer Invisible Prompt" width="750"> </p> **Example Usage** ```js const { Invisible } = require('enquirer'); const prompt = new Invisible({ name: 'secret', message: 'What is your secret?' }); prompt.run() .then(answer => console.log('Answer:', { secret: answer })) .catch(console.error); ``` **Related prompts** * [Password](#password-prompt) * [Input](#input-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### List Prompt Prompt that returns a list of values, created by splitting the user input. The default split character is `,` with optional trailing whitespace. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/list-prompt.gif" alt="Enquirer List Prompt" width="750"> </p> **Example Usage** ```js const { List } = require('enquirer'); const prompt = new List({ name: 'keywords', message: 'Type comma-separated keywords' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Sort](#sort-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### MultiSelect Prompt Prompt that allows the user to select multiple items from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/multiselect-prompt.gif" alt="Enquirer MultiSelect Prompt" width="750"> </p> **Example Usage** ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: ['aqua', 'blue', 'fuchsia'] ``` **Example key-value pairs** Optionally, pass a `result` function and use the `.map` method to return an object of key-value pairs of the selected names and values: [example](./examples/multiselect/option-result.js) ```js const { MultiSelect } = require('enquirer'); const prompt = new MultiSelect({ name: 'value', message: 'Pick your favorite colors', limit: 7, choices: [ { name: 'aqua', value: '#00ffff' }, { name: 'black', value: '#000000' }, { name: 'blue', value: '#0000ff' }, { name: 'fuchsia', value: '#ff00ff' }, { name: 'gray', value: '#808080' }, { name: 'green', value: '#008000' }, { name: 'lime', value: '#00ff00' }, { name: 'maroon', value: '#800000' }, { name: 'navy', value: '#000080' }, { name: 'olive', value: '#808000' }, { name: 'purple', value: '#800080' }, { name: 'red', value: '#ff0000' }, { name: 'silver', value: '#c0c0c0' }, { name: 'teal', value: '#008080' }, { name: 'white', value: '#ffffff' }, { name: 'yellow', value: '#ffff00' } ], result(names) { return this.map(names); } }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); // Answer: { aqua: '#00ffff', blue: '#0000ff', fuchsia: '#ff00ff' } ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Numeral Prompt Prompt that takes a number as input. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/numeral-prompt.gif" alt="Enquirer Numeral Prompt" width="750"> </p> **Example Usage** ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ name: 'number', message: 'Please enter a number' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Confirm](#confirm-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Password Prompt Prompt that takes user input and masks it in the terminal. Also see the [invisible prompt](#invisible-prompt) <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/password-prompt.gif" alt="Enquirer Password Prompt" width="750"> </p> **Example Usage** ```js const { Password } = require('enquirer'); const prompt = new Password({ name: 'password', message: 'What is your password?' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Input](#input-prompt) * [Invisible](#invisible-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Quiz Prompt Prompt that allows the user to play multiple-choice quiz questions. <p align="center"> <img src="https://user-images.githubusercontent.com/13731210/61567561-891d4780-aa6f-11e9-9b09-3d504abd24ed.gif" alt="Enquirer Quiz Prompt" width="750"> </p> **Example Usage** ```js const { Quiz } = require('enquirer'); const prompt = new Quiz({ name: 'countries', message: 'How many countries are there in the world?', choices: ['165', '175', '185', '195', '205'], correctChoice: 3 }); prompt .run() .then(answer => { if (answer.correct) { console.log('Correct!'); } else { console.log(`Wrong! Correct answer is ${answer.correctAnswer}`); } }) .catch(console.error); ``` **Quiz Options** | Option | Type | Required | Description | | ----------- | ---------- | ---------- | ------------------------------------------------------------------------------------------------------------ | | `choices` | `array` | Yes | The list of possible answers to the quiz question. | | `correctChoice`| `number` | Yes | Index of the correct choice from the `choices` array. | **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Survey Prompt Prompt that allows the user to provide feedback for a list of questions. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/survey-prompt.gif" alt="Enquirer Survey Prompt" width="750"> </p> **Example Usage** ```js const { Survey } = require('enquirer'); const prompt = new Survey({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.' }, { name: 'navigation', message: 'The website is easy to navigate.' }, { name: 'images', message: 'The website usually has good images.' }, { name: 'upload', message: 'The website makes it easy to upload images.' }, { name: 'colors', message: 'The website has a pleasing color palette.' } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [Scale](#scale-prompt) * [Snippet](#snippet-prompt) * [Select](#select-prompt) *** ### Scale Prompt A more compact version of the [Survey prompt](#survey-prompt), the Scale prompt allows the user to quickly provide feedback using a [Likert Scale](https://en.wikipedia.org/wiki/Likert_scale). <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/scale-prompt.gif" alt="Enquirer Scale Prompt" width="750"> </p> **Example Usage** ```js const { Scale } = require('enquirer'); const prompt = new Scale({ name: 'experience', message: 'Please rate your experience', scale: [ { name: '1', message: 'Strongly Disagree' }, { name: '2', message: 'Disagree' }, { name: '3', message: 'Neutral' }, { name: '4', message: 'Agree' }, { name: '5', message: 'Strongly Agree' } ], margin: [0, 0, 2, 1], choices: [ { name: 'interface', message: 'The website has a friendly interface.', initial: 2 }, { name: 'navigation', message: 'The website is easy to navigate.', initial: 2 }, { name: 'images', message: 'The website usually has good images.', initial: 2 }, { name: 'upload', message: 'The website makes it easy to upload images.', initial: 2 }, { name: 'colors', message: 'The website has a pleasing color palette.', initial: 2 } ] }); prompt.run() .then(value => console.log('ANSWERS:', value)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Select Prompt Prompt that allows the user to select from a list of options. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/select-prompt.gif" alt="Enquirer Select Prompt" width="750"> </p> **Example Usage** ```js const { Select } = require('enquirer'); const prompt = new Select({ name: 'color', message: 'Pick a flavor', choices: ['apple', 'grape', 'watermelon', 'cherry', 'orange'] }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [AutoComplete](#autocomplete-prompt) * [MultiSelect](#multiselect-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Sort Prompt Prompt that allows the user to sort items in a list. **Example** In this [example](https://github.com/enquirer/enquirer/raw/master/examples/sort/prompt.js), custom styling is applied to the returned values to make it easier to see what's happening. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/sort-prompt.gif" alt="Enquirer Sort Prompt" width="750"> </p> **Example Usage** ```js const colors = require('ansi-colors'); const { Sort } = require('enquirer'); const prompt = new Sort({ name: 'colors', message: 'Sort the colors in order of preference', hint: 'Top is best, bottom is worst', numbered: true, choices: ['red', 'white', 'green', 'cyan', 'yellow'].map(n => ({ name: n, message: colors[n](n) })) }); prompt.run() .then(function(answer = []) { console.log(answer); console.log('Your preferred order of colors is:'); console.log(answer.map(key => colors[key](key)).join('\n')); }) .catch(console.error); ``` **Related prompts** * [List](#list-prompt) * [Select](#select-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Snippet Prompt Prompt that allows the user to replace placeholders in a snippet of code or text. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/snippet-prompt.gif" alt="Prompts" width="750"> </p> **Example Usage** ```js const semver = require('semver'); const { Snippet } = require('enquirer'); const prompt = new Snippet({ name: 'username', message: 'Fill out the fields in package.json', required: true, fields: [ { name: 'author_name', message: 'Author Name' }, { name: 'version', validate(value, state, item, index) { if (item && item.name === 'version' && !semver.valid(value)) { return prompt.styles.danger('version should be a valid semver value'); } return true; } } ], template: `{ "name": "\${name}", "description": "\${description}", "version": "\${version}", "homepage": "https://github.com/\${username}/\${name}", "author": "\${author_name} (https://github.com/\${username})", "repository": "\${username}/\${name}", "license": "\${license:ISC}" } ` }); prompt.run() .then(answer => console.log('Answer:', answer.result)) .catch(console.error); ``` **Related prompts** * [Survey](#survey-prompt) * [AutoComplete](#autocomplete-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Toggle Prompt Prompt that allows the user to toggle between two values then returns `true` or `false`. <p align="center"> <img src="https://raw.githubusercontent.com/enquirer/enquirer/master/media/toggle-prompt.gif" alt="Enquirer Toggle Prompt" width="750"> </p> **Example Usage** ```js const { Toggle } = require('enquirer'); const prompt = new Toggle({ message: 'Want to answer?', enabled: 'Yep', disabled: 'Nope' }); prompt.run() .then(answer => console.log('Answer:', answer)) .catch(console.error); ``` **Related prompts** * [Confirm](#confirm-prompt) * [Input](#input-prompt) * [Sort](#sort-prompt) **↑ back to:** [Getting Started](#-getting-started) · [Prompts](#-prompts) *** ### Prompt Types There are 5 (soon to be 6!) type classes: * [ArrayPrompt](#arrayprompt) - [Options](#options) - [Properties](#properties) - [Methods](#methods) - [Choices](#choices) - [Defining choices](#defining-choices) - [Choice properties](#choice-properties) - [Related prompts](#related-prompts) * [AuthPrompt](#authprompt) * [BooleanPrompt](#booleanprompt) * DatePrompt (Coming Soon!) * [NumberPrompt](#numberprompt) * [StringPrompt](#stringprompt) Each type is a low-level class that may be used as a starting point for creating higher level prompts. Continue reading to learn how. ### ArrayPrompt The `ArrayPrompt` class is used for creating prompts that display a list of choices in the terminal. For example, Enquirer uses this class as the basis for the [Select](#select) and [Survey](#survey) prompts. #### Options In addition to the [options](#options) available to all prompts, Array prompts also support the following options. | **Option** | **Required?** | **Type** | **Description** | | ----------- | ------------- | --------------- | ----------------------------------------------------------------------------------------------------------------------- | | `autofocus` | `no` | `string\|number` | The index or name of the choice that should have focus when the prompt loads. Only one choice may have focus at a time. | | | `stdin` | `no` | `stream` | The input stream to use for emitting keypress events. Defaults to `process.stdin`. | | `stdout` | `no` | `stream` | The output stream to use for writing the prompt to the terminal. Defaults to `process.stdout`. | | | #### Properties Array prompts have the following instance properties and getters. | **Property name** | **Type** | **Description** | | ----------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `choices` | `array` | Array of choices that have been normalized from choices passed on the prompt options. | | `cursor` | `number` | Position of the cursor relative to the _user input (string)_. | | `enabled` | `array` | Returns an array of enabled choices. | | `focused` | `array` | Returns the currently selected choice in the visible list of choices. This is similar to the concept of focus in HTML and CSS. Focused choices are always visible (on-screen). When a list of choices is longer than the list of visible choices, and an off-screen choice is _focused_, the list will scroll to the focused choice and re-render. | | `focused` | Gets the currently selected choice. Equivalent to `prompt.choices[prompt.index]`. | | `index` | `number` | Position of the pointer in the _visible list (array) of choices_. | | `limit` | `number` | The number of choices to display on-screen. | | `selected` | `array` | Either a list of enabled choices (when `options.multiple` is true) or the currently focused choice. | | `visible` | `string` | | #### Methods | **Method** | **Description** | | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pointer()` | Returns the visual symbol to use to identify the choice that currently has focus. The `❯` symbol is often used for this. The pointer is not always visible, as with the `autocomplete` prompt. | | `indicator()` | Returns the visual symbol that indicates whether or not a choice is checked/enabled. | | `focus()` | Sets focus on a choice, if it can be focused. | #### Choices Array prompts support the `choices` option, which is the array of choices users will be able to select from when rendered in the terminal. **Type**: `string|object` **Example** ```js const { prompt } = require('enquirer'); const questions = [{ type: 'select', name: 'color', message: 'Favorite color?', initial: 1, choices: [ { name: 'red', message: 'Red', value: '#ff0000' }, //<= choice object { name: 'green', message: 'Green', value: '#00ff00' }, //<= choice object { name: 'blue', message: 'Blue', value: '#0000ff' } //<= choice object ] }]; let answers = await prompt(questions); console.log('Answer:', answers.color); ``` #### Defining choices Whether defined as a string or object, choices are normalized to the following interface: ```js { name: string; message: string | undefined; value: string | undefined; hint: string | undefined; disabled: boolean | string | undefined; } ``` **Example** ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: ['Apple', 'Orange', 'Raspberry'] }; ``` Normalizes to the following when the prompt is run: ```js const question = { name: 'fruit', message: 'Favorite fruit?', choices: [ { name: 'Apple', message: 'Apple', value: 'Apple' }, { name: 'Orange', message: 'Orange', value: 'Orange' }, { name: 'Raspberry', message: 'Raspberry', value: 'Raspberry' } ] }; ``` #### Choice properties The following properties are supported on `choice` objects. | **Option** | **Type** | **Description** | | ----------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | `string` | The unique key to identify a choice | | `message` | `string` | The message to display in the terminal. `name` is used when this is undefined. | | `value` | `string` | Value to associate with the choice. Useful for creating key-value pairs from user choices. `name` is used when this is undefined. | | `choices` | `array` | Array of "child" choices. | | `hint` | `string` | Help message to display next to a choice. | | `role` | `string` | Determines how the choice will be displayed. Currently the only role supported is `separator`. Additional roles may be added in the future (like `heading`, etc). Please create a [feature request] | | `enabled` | `boolean` | Enabled a choice by default. This is only supported when `options.multiple` is true or on prompts that support multiple choices, like [MultiSelect](#-multiselect). | | `disabled` | `boolean\|string` | Disable a choice so that it cannot be selected. This value may either be `true`, `false`, or a message to display. | | `indicator` | `string\|function` | Custom indicator to render for a choice (like a check or radio button). | #### Related prompts * [AutoComplete](#autocomplete-prompt) * [Form](#form-prompt) * [MultiSelect](#multiselect-prompt) * [Select](#select-prompt) * [Survey](#survey-prompt) *** ### AuthPrompt The `AuthPrompt` is used to create prompts to log in user using any authentication method. For example, Enquirer uses this class as the basis for the [BasicAuth Prompt](#basicauth-prompt). You can also find prompt examples in `examples/auth/` folder that utilizes `AuthPrompt` to create OAuth based authentication prompt or a prompt that authenticates using time-based OTP, among others. `AuthPrompt` has a factory function that creates an instance of `AuthPrompt` class and it expects an `authenticate` function, as an argument, which overrides the `authenticate` function of the `AuthPrompt` class. #### Methods | **Method** | **Description** | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `authenticate()` | Contain all the authentication logic. This function should be overridden to implement custom authentication logic. The default `authenticate` function throws an error if no other function is provided. | #### Choices Auth prompt supports the `choices` option, which is the similar to the choices used in [Form Prompt](#form-prompt). **Example** ```js const { AuthPrompt } = require('enquirer'); function authenticate(value, state) { if (value.username === this.options.username && value.password === this.options.password) { return true; } return false; } const CustomAuthPrompt = AuthPrompt.create(authenticate); const prompt = new CustomAuthPrompt({ name: 'password', message: 'Please enter your password', username: 'rajat-sr', password: '1234567', choices: [ { name: 'username', message: 'username' }, { name: 'password', message: 'password' } ] }); prompt .run() .then(answer => console.log('Authenticated?', answer)) .catch(console.error); ``` #### Related prompts * [BasicAuth Prompt](#basicauth-prompt) *** ### BooleanPrompt The `BooleanPrompt` class is used for creating prompts that display and return a boolean value. ```js const { BooleanPrompt } = require('enquirer'); const prompt = new BooleanPrompt({ header: '========================', message: 'Do you love enquirer?', footer: '========================', }); prompt.run() .then(answer => console.log('Selected:', answer)) .catch(console.error); ``` **Returns**: `boolean` *** ### NumberPrompt The `NumberPrompt` class is used for creating prompts that display and return a numerical value. ```js const { NumberPrompt } = require('enquirer'); const prompt = new NumberPrompt({ header: '************************', message: 'Input the Numbers:', footer: '************************', }); prompt.run() .then(answer => console.log('Numbers are:', answer)) .catch(console.error); ``` **Returns**: `string|number` (number, or number formatted as a string) *** ### StringPrompt The `StringPrompt` class is used for creating prompts that display and return a string value. ```js const { StringPrompt } = require('enquirer'); const prompt = new StringPrompt({ header: '************************', message: 'Input the String:', footer: '************************' }); prompt.run() .then(answer => console.log('String is:', answer)) .catch(console.error); ``` **Returns**: `string` <br> ## ❯ Custom prompts With Enquirer 2.0, custom prompts are easier than ever to create and use. **How do I create a custom prompt?** Custom prompts are created by extending either: * Enquirer's `Prompt` class * one of the built-in [prompts](#-prompts), or * low-level [types](#-types). <!-- Example: HaiKarate Custom Prompt --> ```js const { Prompt } = require('enquirer'); class HaiKarate extends Prompt { constructor(options = {}) { super(options); this.value = options.initial || 0; this.cursorHide(); } up() { this.value++; this.render(); } down() { this.value--; this.render(); } render() { this.clear(); // clear previously rendered prompt from the terminal this.write(`${this.state.message}: ${this.value}`); } } // Use the prompt by creating an instance of your custom prompt class. const prompt = new HaiKarate({ message: 'How many sprays do you want?', initial: 10 }); prompt.run() .then(answer => console.log('Sprays:', answer)) .catch(console.error); ``` If you want to be able to specify your prompt by `type` so that it may be used alongside other prompts, you will need to first create an instance of `Enquirer`. ```js const Enquirer = require('enquirer'); const enquirer = new Enquirer(); ``` Then use the `.register()` method to add your custom prompt. ```js enquirer.register('haikarate', HaiKarate); ``` Now you can do the following when defining "questions". ```js let spritzer = require('cologne-drone'); let answers = await enquirer.prompt([ { type: 'haikarate', name: 'cologne', message: 'How many sprays do you need?', initial: 10, async onSubmit(name, value) { await spritzer.activate(value); //<= activate drone return value; } } ]); ``` <br> ## ❯ Key Bindings ### All prompts These key combinations may be used with all prompts. | **command** | **description** | | -------------------------------- | -------------------------------------- | | <kbd>ctrl</kbd> + <kbd>c</kbd> | Cancel the prompt. | | <kbd>ctrl</kbd> + <kbd>g</kbd> | Reset the prompt to its initial state. | <br> ### Move cursor These combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>left</kbd> | Move the cursor back one character. | | <kbd>right</kbd> | Move the cursor forward one character. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> ### Edit Input These key combinations may be used on prompts that support user input (eg. [input prompt](#input-prompt), [password prompt](#password-prompt), and [invisible prompt](#invisible-prompt)). | **command** | **description** | | ------------------------------ | ---------------------------------------- | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move cursor to the start of the line | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move cursor to the end of the line | | <kbd>ctrl</kbd> + <kbd>b</kbd> | Move cursor back one character | | <kbd>ctrl</kbd> + <kbd>f</kbd> | Move cursor forward one character | | <kbd>ctrl</kbd> + <kbd>x</kbd> | Toggle between first and cursor position | <br> | **command (Mac)** | **command (Windows)** | **description** | | ----------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | <kbd>delete</kbd> | <kbd>backspace</kbd> | Delete one character to the left. | | <kbd>fn</kbd> + <kbd>delete</kbd> | <kbd>delete</kbd> | Delete one character to the right. | | <kbd>option</kbd> + <kbd>up</kbd> | <kbd>alt</kbd> + <kbd>up</kbd> | Scroll to the previous item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | | <kbd>option</kbd> + <kbd>down</kbd> | <kbd>alt</kbd> + <kbd>down</kbd> | Scroll to the next item in history ([Input prompt](#input-prompt) only, when [history is enabled](examples/input/option-history.js)). | ### Select choices These key combinations may be used on prompts that support _multiple_ choices, such as the [multiselect prompt](#multiselect-prompt), or the [select prompt](#select-prompt) when the `multiple` options is true. | **command** | **description** | | ----------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>space</kbd> | Toggle the currently selected choice when `options.multiple` is true. | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>a</kbd> | Toggle all choices to be enabled or disabled. | | <kbd>i</kbd> | Invert the current selection of choices. | | <kbd>g</kbd> | Toggle the current choice group. | <br> ### Hide/show choices | **command** | **description** | | ------------------------------- | ---------------------------------------------- | | <kbd>fn</kbd> + <kbd>up</kbd> | Decrease the number of visible choices by one. | | <kbd>fn</kbd> + <kbd>down</kbd> | Increase the number of visible choices by one. | <br> ### Move/lock Pointer | **command** | **description** | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | <kbd>number</kbd> | Move the pointer to the choice at the given index. Also toggles the selected choice when `options.multiple` is true. | | <kbd>up</kbd> | Move the pointer up. | | <kbd>down</kbd> | Move the pointer down. | | <kbd>ctrl</kbd> + <kbd>a</kbd> | Move the pointer to the first _visible_ choice. | | <kbd>ctrl</kbd> + <kbd>e</kbd> | Move the pointer to the last _visible_ choice. | | <kbd>shift</kbd> + <kbd>up</kbd> | Scroll up one choice without changing pointer position (locks the pointer while scrolling). | | <kbd>shift</kbd> + <kbd>down</kbd> | Scroll down one choice without changing pointer position (locks the pointer while scrolling). | <br> | **command (Mac)** | **command (Windows)** | **description** | | -------------------------------- | --------------------- | ---------------------------------------------------------- | | <kbd>fn</kbd> + <kbd>left</kbd> | <kbd>home</kbd> | Move the pointer to the first choice in the choices array. | | <kbd>fn</kbd> + <kbd>right</kbd> | <kbd>end</kbd> | Move the pointer to the last choice in the choices array. | <br> ## ❯ Release History Please see [CHANGELOG.md](CHANGELOG.md). ## ❯ Performance ### System specs MacBook Pro, Intel Core i7, 2.5 GHz, 16 GB. ### Load time Time it takes for the module to load the first time (average of 3 runs): ``` enquirer: 4.013ms inquirer: 286.717ms ``` <br> ## ❯ About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Todo We're currently working on documentation for the following items. Please star and watch the repository for updates! * [ ] Customizing symbols * [ ] Customizing styles (palette) * [ ] Customizing rendered input * [ ] Customizing returned values * [ ] Customizing key bindings * [ ] Question validation * [ ] Choice validation * [ ] Skipping questions * [ ] Async choices * [ ] Async timers: loaders, spinners and other animations * [ ] Links to examples </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ```sh $ yarn && yarn test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> #### Contributors | **Commits** | **Contributor** | | --- | --- | | 283 | [jonschlinkert](https://github.com/jonschlinkert) | | 82 | [doowb](https://github.com/doowb) | | 32 | [rajat-sr](https://github.com/rajat-sr) | | 20 | [318097](https://github.com/318097) | | 15 | [g-plane](https://github.com/g-plane) | | 12 | [pixelass](https://github.com/pixelass) | | 5 | [adityavyas611](https://github.com/adityavyas611) | | 5 | [satotake](https://github.com/satotake) | | 3 | [tunnckoCore](https://github.com/tunnckoCore) | | 3 | [Ovyerus](https://github.com/Ovyerus) | | 3 | [sw-yx](https://github.com/sw-yx) | | 2 | [DanielRuf](https://github.com/DanielRuf) | | 2 | [GabeL7r](https://github.com/GabeL7r) | | 1 | [AlCalzone](https://github.com/AlCalzone) | | 1 | [hipstersmoothie](https://github.com/hipstersmoothie) | | 1 | [danieldelcore](https://github.com/danieldelcore) | | 1 | [ImgBotApp](https://github.com/ImgBotApp) | | 1 | [jsonkao](https://github.com/jsonkao) | | 1 | [knpwrs](https://github.com/knpwrs) | | 1 | [yeskunall](https://github.com/yeskunall) | | 1 | [mischah](https://github.com/mischah) | | 1 | [renarsvilnis](https://github.com/renarsvilnis) | | 1 | [sbugert](https://github.com/sbugert) | | 1 | [stephencweiss](https://github.com/stephencweiss) | | 1 | [skellock](https://github.com/skellock) | | 1 | [whxaxes](https://github.com/whxaxes) | #### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) #### Credit Thanks to [derhuerst](https://github.com/derhuerst), creator of prompt libraries such as [prompt-skeleton](https://github.com/derhuerst/prompt-skeleton), which influenced some of the concepts we used in our prompts. #### License Copyright © 2018-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # Web IDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [Web IDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js "use strict"; const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a Web IDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different Web IDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the Web IDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the Web IDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). Each method also accepts a second, optional, parameter for miscellaneous options. For conversion methods that throw errors, a string option `{ context }` may be provided to provide more information in the error message. (For example, `conversions["float"](NaN, { context: "Argument 1 of Interface's operation" })` will throw an error with message `"Argument 1 of Interface's operation is not a finite floating-point value."`) Specific conversions may also accept other options, the details of which can be found below. ## Conversions implemented Conversions for all of the basic types from the Web IDL specification are implemented: - [`any`](https://heycam.github.io/webidl/#es-any) - [`void`](https://heycam.github.io/webidl/#es-void) - [`boolean`](https://heycam.github.io/webidl/#es-boolean) - [Integer types](https://heycam.github.io/webidl/#es-integer-types), which can additionally be provided the boolean options `{ clamp, enforceRange }` as a second parameter - [`float`](https://heycam.github.io/webidl/#es-float), [`unrestricted float`](https://heycam.github.io/webidl/#es-unrestricted-float) - [`double`](https://heycam.github.io/webidl/#es-double), [`unrestricted double`](https://heycam.github.io/webidl/#es-unrestricted-double) - [`DOMString`](https://heycam.github.io/webidl/#es-DOMString), which can additionally be provided the boolean option `{ treatNullAsEmptyString }` as a second parameter - [`ByteString`](https://heycam.github.io/webidl/#es-ByteString), [`USVString`](https://heycam.github.io/webidl/#es-USVString) - [`object`](https://heycam.github.io/webidl/#es-object) - [`Error`](https://heycam.github.io/webidl/#es-Error) - [Buffer source types](https://heycam.github.io/webidl/#es-buffer-source-types) Additionally, for convenience, the following derived type definitions are implemented: - [`ArrayBufferView`](https://heycam.github.io/webidl/#ArrayBufferView) - [`BufferSource`](https://heycam.github.io/webidl/#BufferSource) - [`DOMTimeStamp`](https://heycam.github.io/webidl/#DOMTimeStamp) - [`Function`](https://heycam.github.io/webidl/#Function) - [`VoidFunction`](https://heycam.github.io/webidl/#VoidFunction) (although it will not censor the return type) Derived types, such as nullable types, promise types, sequences, records, etc. are not handled by this library. You may wish to investigate the [webidl2js](https://github.com/jsdom/webidl2js) project. ### A note on the `long long` types The `long long` and `unsigned long long` Web IDL types can hold values that cannot be stored in JavaScript numbers, so the conversion is imperfect. For example, converting the JavaScript number `18446744073709552000` to a Web IDL `long long` is supposed to produce the Web IDL value `-18446744073709551232`. Since we are representing our Web IDL values in JavaScript, we can't represent `-18446744073709551232`, so we instead the best we could do is `-18446744073709552000` as the output. This library actually doesn't even get that far. Producing those results would require doing accurate modular arithmetic on 64-bit intermediate values, but JavaScript does not make this easy. We could pull in a big-integer library as a dependency, but in lieu of that, we for now have decided to just produce inaccurate results if you pass in numbers that are not strictly between `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER`. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. Web IDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on Web IDL values, i.e. instances of Web IDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a Web IDL value of [Web IDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, Web IDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given Web IDL operation, how does that get converted into a Web IDL value? For example, a JavaScript `true` passed in the position of a Web IDL `boolean` argument becomes a Web IDL `true`. But, a JavaScript `true` passed in the position of a [Web IDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a Web IDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the Web IDL algorithms, they don't actually use Web IDL values, since those aren't "real" outside of specs. Instead, implementations apply the Web IDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting Web IDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of Web IDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given Web IDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ Web IDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ Web IDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a Web IDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't use this Seriously, why would you ever use this? You really shouldn't. Web IDL is … strange, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from Web IDL. In general, your JavaScript should not be trying to become more like Web IDL; if anything, we should fix Web IDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in Web IDL. Its main consumer is the [jsdom](https://github.com/tmpvar/jsdom) project. # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. <img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png"> ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # file-entry-cache > Super simple cache for file metadata, useful for process that work o a given series of files > and that only need to repeat the job on the changed ones since the previous run of the process — Edit [![NPM Version](http://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache) [![Build Status](http://img.shields.io/travis/royriojas/file-entry-cache.svg?style=flat)](https://travis-ci.org/royriojas/file-entry-cache) ## install ```bash npm i --save file-entry-cache ``` ## Usage The module exposes two functions `create` and `createFromFile`. ## `create(cacheName, [directory, useCheckSum])` - **cacheName**: the name of the cache to be created - **directory**: Optional the directory to load the cache from - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ## `createFromFile(pathToCache, [useCheckSum])` - **pathToCache**: the path to the cache file (this combines the cache name and directory) - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file. ```js // loads the cache, if one does not exists for the given // Id a new one will be prepared to be created var fileEntryCache = require('file-entry-cache'); var cache = fileEntryCache.create('testCache'); var files = expand('../fixtures/*.txt'); // the first time this method is called, will return all the files var oFiles = cache.getUpdatedFiles(files); // this will persist this to disk checking each file stats and // updating the meta attributes `size` and `mtime`. // custom fields could also be added to the meta object and will be persisted // in order to retrieve them later cache.reconcile(); // use this if you want the non visited file entries to be kept in the cache // for more than one execution // // cache.reconcile( true /* noPrune */) // on a second run var cache2 = fileEntryCache.create('testCache'); // will return now only the files that were modified or none // if no files were modified previous to the execution of this function var oFiles = cache.getUpdatedFiles(files); // if you want to prevent a file from being considered non modified // something useful if a file failed some sort of validation // you can then remove the entry from the cache doing cache.removeEntry('path/to/file'); // path to file should be the same path of the file received on `getUpdatedFiles` // that will effectively make the file to appear again as modified until the validation is passed. In that // case you should not remove it from the cache // if you need all the files, so you can determine what to do with the changed ones // you can call var oFiles = cache.normalizeEntries(files); // oFiles will be an array of objects like the following entry = { key: 'some/name/file', the path to the file changed: true, // if the file was changed since previous run meta: { size: 3242, // the size of the file mtime: 231231231, // the modification time of the file data: {} // some extra field stored for this file (useful to save the result of a transformation on the file } } ``` ## Motivation for this module I needed a super simple and dumb **in-memory cache** with optional disk persistence (write-back cache) in order to make a script that will beautify files with `esformatter` to execute only on the files that were changed since the last run. In doing so the process of beautifying files was reduced from several seconds to a small fraction of a second. This module uses [flat-cache](https://www.npmjs.com/package/flat-cache) a super simple `key/value` cache storage with optional file persistance. The main idea is to read the files when the task begins, apply the transforms required, and if the process succeed, then store the new state of the files. The next time this module request for `getChangedFiles` will return only the files that were modified. Making the process to end faster. This module could also be used by processes that modify the files applying a transform, in that case the result of the transform could be stored in the `meta` field, of the entries. Anything added to the meta field will be persisted. Those processes won't need to call `getChangedFiles` they will instead call `normalizeEntries` that will return the entries with a `changed` field that can be used to determine if the file was changed or not. If it was not changed the transformed stored data could be used instead of actually applying the transformation, saving time in case of only a few files changed. In the worst case scenario all the files will be processed. In the best case scenario only a few of them will be processed. ## Important notes - The values set on the meta attribute of the entries should be `stringify-able` ones if possible, flat-cache uses `circular-json` to try to persist circular structures, but this should be considered experimental. The best results are always obtained with non circular values - All the changes to the cache state are done to memory first and only persisted after reconcile. ## License MIT <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the .gitignore [spec](http://git-scm.com/docs/gitignore). Pay attention that [`minimatch`](https://www.npmjs.org/package/minimatch) does not work in the gitignore way. To filter filenames according to .gitignore file, I recommend this module. ##### Tested on - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - [Guide for 2.x -> 3.x](#upgrade-2x---3x) - [Guide for 3.x -> 4.x](#upgrade-3x---4x) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array<Pathname>): Array<Pathname> ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory. ```js // WRONG ig.ignores('./abc') // WRONG, for it will never happen. // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js ig.add('config/') // `ig` does NOT know if 'config' is a normal file, directory or something ig.ignores('config') // And it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` **** # Upgrade Guide ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* ## Timezone support In order to provide support for timezones, without relying on the JavaScript host or any other time-zone aware environment, this library makes use of teh IANA Timezone Database directly: https://www.iana.org/time-zones The database files are parsed by the scripts in this folder, which emit AssemblyScript code which is used to process the various rules at runtime. # Near Bindings Generator Transforms the Assembyscript AST to serialize exported functions and add `encode` and `decode` functions for generating and parsing JSON strings. ## Using via CLI After installling, `npm install nearprotocol/near-bindgen-as`, it can be added to the cli arguments of the assemblyscript compiler you must add the following: ```bash asc <file> --transform near-bindgen-as ... ``` This module also adds a binary `near-asc` which adds the default arguments required to build near contracts as well as the transformer. ```bash near-asc <input file> <output file> ``` ## Using a script to compile Another way is to add a file such as `asconfig.js` such as: ```js const compile = require("near-bindgen-as/compiler").compile; compile("assembly/index.ts", // input file "out/index.wasm", // output file [ // "-O1", // Optional arguments "--debug", "--measure" ], // Prints out the final cli arguments passed to compiler. {verbose: true} ); ``` It can then be built with `node asconfig.js`. There is an example of this in the test directory. # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # binary-install Install .tar.gz binary applications via npm ## Usage This library provides a single class `Binary` that takes a download url and some optional arguments. You **must** provide either `name` or `installDirectory` when creating your `Binary`. | option | decription | | ---------------- | --------------------------------------------- | | name | The name of your binary | | installDirectory | A path to the directory to install the binary | If an `installDirectory` is not provided, the binary will be installed at your OS specific config directory. On MacOS it defaults to `~/Library/Preferences/${name}-nodejs` After your `Binary` has been created, you can run `.install()` to install the binary, and `.run()` to run it. ### Example This is meant to be used as a library - create your `Binary` with your desired options, then call `.install()` in the `postinstall` of your `package.json`, `.run()` in the `bin` section of your `package.json`, and `.uninstall()` in the `preuninstall` section of your `package.json`. See [this example project](/example) to see how to create an npm package that installs and runs a binary using the Github releases API. # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC ## assemblyscript-temporal An implementation of temporal within AssemblyScript, with an initial focus on non-timezone-aware classes and functionality. ### Why? AssemblyScript has minimal `Date` support, however, the JS Date API itself is terrible and people tend not to use it that often. As a result libraries like moment / luxon have become staple replacements. However, there is now a [relatively mature TC39 proposal](https://github.com/tc39/proposal-temporal) that adds greatly improved date support to JS. The goal of this project is to implement Temporal for AssemblyScript. ### Usage This library currently supports the following types: #### `PlainDateTime` A `PlainDateTime` represents a calendar date and wall-clock time that does not carry time zone information, e.g. December 7th, 1995 at 3:00 PM (in the Gregorian calendar). For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindatetime.html), this implementation follows the specification as closely as possible. You can create a `PlainDateTime` from individual components, a string or an object literal: ```javascript datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.year; // 2019; datetime.month; // 11; // ... datetime.nanosecond; // 789; datetime = PlainDateTime.from("1976-11-18T12:34:56"); datetime.toString(); // "1976-11-18T12:34:56" datetime = PlainDateTime.from({ year: 1966, month: 3, day: 3 }); datetime.toString(); // "1966-03-03T00:00:00" ``` There are various ways you can manipulate a date: ```javascript // use 'with' to copy a date but with various property values overriden datetime = new PlainDateTime(1976, 11, 18, 15, 23, 30, 123, 456, 789); datetime.with({ year: 2019 }).toString(); // "2019-11-18T15:23:30.123456789" // use 'add' or 'substract' to add / subtract a duration datetime = PlainDateTime.from("2020-01-12T15:00"); datetime.add({ months: 1 }).toString(); // "2020-02-12T15:00:00"); // add / subtract support Duration objects or object literals datetime.add(new Duration(1)).toString(); // "2021-01-12T15:00:00"); ``` You can compare dates and check for equality ```javascript dt1 = PlainDateTime.from("1976-11-18"); dt2 = PlainDateTime.from("2019-10-29"); PlainDateTime.compare(dt1, dt1); // 0 PlainDateTime.compare(dt1, dt2); // -1 dt1.equals(dt1); // true ``` Currently `PlainDateTime` only supports the ISO 8601 (Gregorian) calendar. #### `PlainDate` A `PlainDate` object represents a calendar date that is not associated with a particular time or time zone, e.g. August 24th, 2006. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaindate.html), this implementation follows the specification as closely as possible. The `PlainDate` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainTime` A `PlainTime` object represents a wall-clock time that is not associated with a particular date or time zone, e.g. 7:39 PM. For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plaintime.html), this implementation follows the specification as closely as possible. The `PlainTime` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `PlainMonthDay` A date without a year component. This is useful to express things like "Bastille Day is on the 14th of July". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainmonthday.html) , this implementation follows the specification as closely as possible. ```javascript const monthDay = PlainMonthDay.from({ month: 7, day: 14 }); // => 07-14 const date = monthDay.toPlainDate({ year: 2030 }); // => 2030-07-14 date.dayOfWeek; // => 7 ``` The `PlainMonthDay` API is almost identical to `PlainDateTime`, so see above for more API usage examples. #### `PlainYearMonth` A date without a day component. This is useful to express things like "the October 2020 meeting". For detailed documentation see the [TC39 Temporal proposal website](https://tc39.es/proposal-temporal/docs/plainyearmonth.html) , this implementation follows the specification as closely as possible. The `PlainYearMonth` API is almost identical to `PlainDateTime`, so see above for API usage examples. #### `now` The `now` object has several methods which give information about the current time and date. ```javascript dateTime = now.plainDateTimeISO(); dateTime.toString(); // 2021-04-01T12:05:47.357 ``` ## Contributing This project is open source, MIT licensed and your contributions are very much welcomed. There is a [brief document that outlines implementation progress and priorities](./development.md). # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```sh node example --arr 1 2 { _[], arr: [1, 2] } ``` _if disabled:_ ```sh node example --arr 1 2 { _[2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```sh node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```sh node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```sh node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC
nearnautnft_astro-marketplace-contract
Cargo.toml src external.rs lib.rs nft_callbacks.rs target .rustc_info.json
Harshanaxs_nearblockchain-
README.md package-lock.json todos-crud-contract as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts index.spec.ts as_types.d.ts index.ts model.ts tsconfig.json index.js neardev dev-account.env package-lock.json package.json tests index.js todos-crud-web README.md package-lock.json package.json public index.html manifest.json robots.txt src App.css App.js App.test.js components Board.js CreateTodo.js Game.js Square.js Todo.js TodoList.js config.js helper.js index.css index.js logo.svg reportWebVitals.js setupTests.js
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) # CRUD App Tutorial This contains the finished code for the tutorial on [building a CRUD dApp](https://docs.near.org/docs/tutorials/apps/todos-crud-app) # Notes The application will consist of two distinct layers: - Smart contract (in web2 we may refer to this as server-side or back-end) - Web app (in web2 we may refer to this as client-side or front-end) ## Working **Contracts: `/todos-crud-contract/`** 1. install dependencies `cd todos-crud-contract && yarn` 2. run tests - `yarn test` 3. compile the contract - `yarn build` 4. deploy the contract - `yarn deploy` **App Tests: `/todos-crud-web/`** 1. install dependencies `cd todos-crud-web && yarn` 2. start the server - `yarn start` ## Notes - If you deploy the contract, make sure to edit the `CONTRACT_NAME` found in `todos-crud-web/src/config.js` to match your deployed contract. - You must be logged in to interact with the app. If you don't have a NEAR wallet, click [here](https://wallet.testnet.near.org/) to make one.
Icarocom_web-dapp-near
.env .eslintrc.js .github workflows chromatic.yml lint.yml .storybook main.js preview.js .vscode settings.json CONTRIBUTING.md README.md components Auth authSlice.ts Projects index.ts projectSlice.ts icons index.ts items elements index.ts index.ts projects index.ts ui Button index.ts Card index.ts Icon_Button index.ts Spinner index.ts index.ts config config.ts near.ts docs adr 0001_record-architecture-decisions.md 0002_component-and-storybook-structure.md contributing style-guides react.md design-system Colors includes index.ts Typography includes index.ts lib context.ts firebase.ts hooks.ts near-api.ts store.ts next-env.d.ts next.config.js package.json pages api hello.ts postcss.config.js public vercel.svg styles Home.module.css index.css swiper.css tailwind.config.js test tsconfig.json theme defaultTheme.js index.js theme.js tsconfig.json
# Catch App using - [typescript](https://github.com/microsoft/TypeScript) - [next.js](https://github.com/vercel/next.js) - [tailwindcss](https://github.com/tailwindlabs/tailwindcss) - [redux](https://github.com/reduxjs/redux) - [firebase](https://github.com/firebase/firebase-js-sdk) - [storybook](https://github.com/storybookjs/storybook/) - [eslint](https://github.com/eslint/eslint) - [prettier](https://github.com/prettier/prettier) ## Install ```bash yarn install # or shortcut yarn ``` ## Getting Started ### Setting up Environment Make a copy of `.env` file and name it `.env.local`. Fill in the values for all `NEXT_PUBLIC_*` variables. You may contact Andrius or Eric to get the correct values. Do not commit either of those files. ### Development Run the development server: ```bash yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. ## Storybook ```bash yarn storybook # build yarn build-storybook ``` ## Contributing See the [the contributing guide](CONTRIBUTING.md) for detailed instructions on how to get started with our project. ## Documenting Components All Components should follow the same structure for a consistent documentation experience: - `Overview`: MDX based documentation to give a complete overview about the component. This is the main documentation and includes some of the other stories. - `Playground`: Is a Story that provides a control for almost any prop of the component, to make it easy to try the component. - `Visual Guide`: Is a Story that provides a overview about the all the states of a component. This makes regression testing easier. And provides a quick overview. Visual Guide should include hover, focus, active, visited, disabled, etc. To statically use them in stories, we generate css classes for the pseudo classes using the PostCSS Pseudo Classes plugin. - `Features`: A directory wich contains a dedicated story for each feature that the component implement. This gives a clear list of supported features with a demo. - `Examples`: A directory with real life examples of how the component might be used. The Overview documentation should be formatted to guide our users. We use a set of doc-components to format our overview documentation: https://intuit.github.io/doc-blocks/?path=/story/gallery--page Any doc-block component need to installed on its own. Package names can be found in their repository: https://github.com/intuit/doc-blocks ```mdx # <component-name> <ShieldRow> ... </ShieldRow> short description of the component ## Usage short example, how to use the component Show Import source code. Use Preview Tag to include playground story. <RelatedComponents components={[]} /> When to use this component? Do's and Don't ## Accessibility Approach document the list of aspects: https://testen.bitv-test.de/index.php?a=dl See heading component as an example. ## SEO ## Features ## API Docs / Args Table ```
near-everything_canvas
.env .github ISSUE_TEMPLATE bug_report.md feature-request.md workflows release.yml README.md apps canvas bos.config.json config paths.js presets loadPreset.js webpack.analyze.js webpack.development.js webpack.production.js functions [[accountId]] widget [[index]].js common.js magic img account [index].js nft [[index]].js sitemap index.js posts [index].js profiles index.js sources [index].js widgets index.js package.json public index.html manifest.json robots.txt runtime.11b6858f93d8625836ab.bundle.js src App.js components ActionButton.js BosLoaderBanner.js Core.js custom tldraw Canvas.js ResponseShape.js SharePanel.js Templates.js TldrawLogo.js TopZone.js ZoomUI.js icons LogOut.js Pretend.js StopPretending.js User.js navigation MobileQRModal.js NotificationWidget.js PretendModal.js SignInButton.js data near.js openai.js web3.js widgets.js hooks useBosLoaderInitializer.js useFlags.js useHashRouterLegacy.js useQuery.js useScrollBlock.js useUrlState.js images build_dao.combo.svg build_dao_icon.svg index.css index.js pages FeedPage.js Flags.js ViewPage.js stores bos-loader.js webpack.config.js
# every canvas Connect your canvas to the open web. ![draw everything](./docs/draw.everything.dev.gif) [everyone](https://near.social/mob.near/widget/Everyone) [builds](https://www.nearbuilders.org/) [everything](https://www.merriam-webster.com/dictionary/everything) [together](https://near.social). # Context [Sawyer Hood](https://github.com/SawyerHood) built [an app](https://github.com/SawyerHood/draw-a-ui) that uses tldraw and the [gpt-4-vision](https://openai.com/blog/new-models-and-developer-products-announced-at-devday) api to generate html based on a wireframe you draw. [tldraw forked that app](https://github.com/tldraw/draw-a-ui), then [I forked tldraw](https://github.com/tldraw/draw-a-ui). I had originally adapted the prompt and preview shape to create [near.social](https://near.social) widgets and embed them via [near-bos-webcomponent](https://github.com/petersalomonsen/near-bos-webcomponent). I was able to create valid, stateful widget code: ![A demo of the app](https://github.com/elliotBraem/draw-a-ui/blob/121194dfbfbfbc1df650e894d2667a7bddbf030f/demo.gif) It worked by taking the current canvas SVG, converting it to a PNG, and then sending that png to gpt-4-vision with instructions to return a single jsx file with styled components. The JSX code was then passed to a [near-bos-webcomponent](https://github.com/petersalomonsen/near-bos-webcomponent) so it could be rendered via the Near Social VM](https://github.com/NearSocial/VM), but now I'm thinking there should be a widget with an iframe inside it -- then this iframe holds the html that gets generated from the canvas. Possibly sharing some resemblance with [bos-web-engine](https://github.com/near/bos-web-engine/blob/main/architecture.md#trust). # Overview This repository is built using the [NEAR open web stack](https://near.org/learn). Right now, it is a [Near Social gateway](https://github.com/NearSocial/viewer) and [bos-workspace](https://github.com/nearbuilders/bos-workspace) combined in one. This gateway provides [tldraw](https://tldraw.dev/) as a custom element to the [Near Social VM](https://github.com/NearSocial/VM). This enables us to use ```<Tldraw />``` and it's [editor](./src/components/custom/tldraw/Canvas.js) via: ```javascript <Canvas initialSnapshot={data || {}} persistance={path} autoFocus={true} /> ``` in a widget you can find in [apps/canvas/widget/index](./apps/canvas/widget/index.jsx). [Widgets](https://thewiki.near.page/near.social_widgets) are reusable composable components for Near Social. You can view and create widgets at [near.social](https://near.social). This means the [draw.everything.dev](https://draw.everything.dev) gateway provides you with the ability to hack your own components using the ```<Canvas>``` element. This structure will evolve for a better development experience. ## Setup & Development Initialize repo: ``` yarn ``` Start development version: ``` yarn dev ``` This will start both the gateway at localhost:3000 and serve the widgets from http://127.0.0.1:4040. Once these are running, copy this server address (http://127.0.0.1:4040), go to [localhost:3000/flags](http://localhost:3000/flags) (Chrome recommended), and paste it as the BOS Loader Url. Save and you should see the following banner: ![bos-loader](./docs/bos-loader.png) ### Next Steps - [x] Merge [PR to near-bos-webcomponent](https://github.com/petersalomonsen/near-bos-webcomponent/pull/1) and replace bundles from CDN - [x] Ability to publish JSX widget to the [social-db](https://github.com/NearSocial/social-db) - [ ] Load in existing widgets and make modifications to them - [x] Option to provide your own API key ([near-openai](https://github.com/petersalomonsen/near-openai)) - [ ] Feature to provide custom prompts and option to swap chat gpt model - IN DEV - [ ] Store JSON on IPFS and create [hyperfiles](https://github.com/hyperfiles-org/hyperfiles) for saving canvas and communicating with [Obsidian](https://docs.obsidian.md/Plugins/Getting+started/Build+a+plugin). - [ ] Deploy to [web4](https://github.com/vgrichina/web4) ## Contributing Pull requests are welcome! Happy hacking! If you'd like to help improve the developer experience, help out [here](https://github.com/orgs/NEARBuilders/projects/5).
Hazarre_SharedDoc
.eslintrc.json README.md marine shared_doc Cargo.toml Config.toml build.sh cfg.json deploy.sh src main.rs test.sh package.json sample.txt src _aqua getting-started.ts components EssayForm.js NameForm.js index.css index.html tsconfig.json webpack.dev.config.ts
# SharedDoc with Fluence and Self.ID Create a shared document app with [Fluence services](https://doc.fluence.dev/docs/), [Self.ID](https://developers.ceramic.network/reference/self-id/classes/web.SelfID/#authenticate) and React. Users can create, share and share files as well as adjust editing permission. A GUI in the browser can be used for ease of access. ### Youtube Demo https://youtu.be/IpWqufnPs58 ![alt text](https://github.com/Hazarre/SharedDoc/blob/main/demo.png) ### Client The clients of this app have two roles: the owner and editors. The owner (deployer identified by self.ID) of a SharedDoc service instance can create documents, add editors to them and share them with others. The owner shares a file to editors using their self.ID. Once a file is shared with a self.ID. It becomes a editor with power to read/write the document as well as share it with other self.IDs. First the verify their identity with self.ID in their browser. Then they use their self.ID to authenticate their permission to read/write/share files. ### Running the App Download this directory. Inside this directory, [connect to a ceramic node](https://developers.ceramic.network/run/nodes/community-nodes/) and run ```npm install``` then```npm start```. You also need a metamask account for easy of use. To deploy your own version of the app, see sections below. ### Fluence services Deployed at: ``` peer id 12D3KooWEFFCZnar1cUJQ3rMWjvPQg6yMV2aXWs2DkJNSRbduBWn service id 829128d8-3641-49eb-8f77-e3df5d04f808 ``` ```rust service SharedDoc: add_editor(doc: string, editor: string, self_id: string) -> bool am_i_owner() -> bool authenticate(filename: string, self_id: string) -> bool create_doc(filename: string, self_id: string) -> bool del_editor(doc: string, editor: string, self_id: string) -> bool read_file(filename: string, editor: string) -> string write_file(filename: string, editor: string, content: string) -> string ``` Aqua services can be found at ```aqua/shared_doc.aqua```. Marine implementations can be found at ```marine/shared_doc```. Run ```./deploy.sh``` to deplot to a Fluence node. React app have config files in the main directory and files in ```src/``` #### Future functoinalities: - Sharing with fine grained permission. - Better UI and UX. - Neater marine/rust code.
GoldenEagle1035_marketplace-smart-contracts_NEAR
.dependabot config.yml README.md contracts market Cargo.toml README.md build-mainnet.sh build-testnet.sh build.sh neardev dev-account.env src external.rs internal.rs lib.rs nft_callbacks.rs sale.rs nft Cargo.toml README.md build-mainnet.sh build-testnet.sh build.sh neardev dev-account.env src enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs token.rs docs document.txt folder_structure.md nep-171.md stateDoc.txt token_ipfs.md upgrade.md package.json scripts app.js app.test.js app1.js app2.js app4.js app5.js config.js execute.js near-utils.js secondary.js snippet.js test-utils.js utils config.js create_initial_accounts.js deploy-market-upgrade.js deploy-market.js deploy-nft-upgrade.js deploy-nft.js near-utils.js patch-config.js patch-deploy-config.js tutils.js
# TBD Amplify Art Music NFT & Marketplace Contract ========================== Modules: 1) Market 2) NFTs ## Work Item: Show List of nfts in User's wallet function nft_tokens_for_owner implementation is in progress. These are old docs, but useful for understanding how it proceeded. ## Doc v0.5 ( Resolved Gas Errors + Fixed Design to suit Album Songs) This is for the current implementation A) Album & song uploads & to list all album bundle copies on market 1) add_token_types B) To Buy a album Bundle on teh marketplace 1) offer_album C) To list song on the marketplace 1) nft_approve D) To Buy the song on the marketplace 1) offer 2) nft_token(to check if the owner has it now ) ## Doc v0.4 Was about series minting ## Doc v0.3 Error Handling Error can be found in Logs of the transaction failed / succeeded otherwise ## Doc v0.2 (Mint + Price Setting + Purchase) 1) Deploy NFT Contract `near dev-deploy --accountId=dev-1623229186642-77647971299977 --wasmFile=./out/music_nft.wasm` 2) Create a Market Account `near create_account market.dev-1623229186642-77647971299977 --masterAccount=dev-1623227573802-45982734932448 --initial-balance 50` 3) Deploy the Music contracts `near deploy --accountId=market.dev-1623229186642-77647971299977 --wasmFile=./out/music_market.wasm` 4) New Function `near call market.dev-1623229186642-77647971299977 new '{"owner_id": "dev-1623229186642-77647971299977", "nft_contract_id": "dev-1623229186642-77647971299977"}' --accountId=dev-1623229186642-77647971299977` `near call dev-1623229186642-77647971299977 new '{"owner_id":"dev-1623229186642-77647971299977","metadata":{"spec":"music-nft-0.2.0","name":"AmplifyArt","symbol":"AMPLIFY"},"supply_cap_by_type":{"test": "1000000"}}' --accountId=dev-1623229186642-77647971299977` 7) Storage Cost Call for the Minter `near call --accountId=rahulsoshte.testnet market.dev-1623229186642-77647971299977 storage_deposit --gas 200000000000000 --amount 20` 8) For further steps follow scripts/app2.js ## Doc v0.1 (Simple Mint function) 1) Copy the WASM File into your machine <br> 2) Install Near CLI (https://docs.near.org/docs/tools/near-cli#windows ) <br> 3) Deploy the WASM file on Testnet <br> `near deploy --wasmFile target/wasm32-unknown-unknown/release/rust_counter_tutorial.wasm --accountId YOUR_ACCOUNT_HERE` <br> 4) For Quick Testing - CLI Arguments ( Will work on WSL ) <br> `near login` `near call YOUR_ACCOUNT_HERE increment --accountId YOUR_ACCOUNT_HERE` `near call --accountId CALLER-ID RECEIVER-ID new '{"owner_id": "OWNER-ID"}'` ( Have to only call once ) `near call --accountId dev-1622112382753-68159924582656 dev-1622112382753-68159924582656 mint_token '{"token_id":"IPFS_METADATA_LINk", "owner_id": "dev-1622112382753-68159924582656"}'` <br> 5) For testing with the NEAR API You need to take reference of near-api-js documentation https://docs.near.org/docs/api/naj-quick-reference#contract So the TokenID can be a IPFS CID of the Metadata (Content ID, a unique hash) & the Metadata's structure can be, For example let's say <b>"21 Guns"</b> song ``` Metadata { "name": "21 Guns", "album": "21st Century Breakdown", "description": "The song is about fighting a good fight, but not the fights unworthy of fighting for. You only got one life, and just one 21 gun salute, avail of it. Live your life an honorable life and give up the petty things.", "audio_file_ipfs_link": "https://ipfs.io/ipfs/QmQvx9dxYNA4kp1ZDzC1jd2LyYgwhffwK3TfBRv7QNqGd8?filename=21guns.mp3", "singer":"Green Day", "genre":"Alternative Rock", "song_writers":"Billie, Mike, Tre", "released_date":"2009" } ``` This whole metadata can be represented by a unique hash ( IPFS Content ID / IPFS URL ) which will be used as the tokenID / unique identifier of the NFT on the blockchain. What happends with using HTTPS URL with AWS S3 as the unique identifier for the NFT is that the links can possibly break, and the TokenID on the blockchain for the NFT becomes a little useless. # TBD
mhassanist_letseducate
.env .eslintrc.yml .gitpod.yml .travis.yml README.md as-pect.config.js asconfig.json babel.config.js neardev shared-test-staging test.near.json shared-test test.near.json package.json src environments environment.prod.ts environment.ts index.html interfaces.ts polyfills.ts tsconfig.json
# lLets Educate! ## Lets educate the world! Connecting learners with believers all over the world! Learners who can't afford education or buying courses use let's educate to seek fund, Beleivers worldwide can donate to help them learn. Login to explore .. Frontend of lets educate smart contract : https://github.com/mhassanist/letseducate-smartcontract # letseducate-smartcontract ## Sample Usage ``` yarn asb --target release ``` ``` near deploy --accountId=letseducate.msaudi.testnet --wasmFile="./build/release/app-one.wasm" ``` ``` near call letseducate.msaudi.testnet createLearningRequest '{"title":"test","description":"test","requestedAmount":"1","courseURL":"http://googogl.com"}' --accountId msaudi.testnet ``` ``` near view letseducate.msaudi.testnet getAvailableLearningRequests ``` ``` near call letseducate.msaudi.testnet supportLearningRequest '{"title":"test"}' --amount 1 --accountId msaudi.testnet ```
itsdivgithub_BOSai-NEAR
.eslintrc.json README.md devcontainer.json jsLibraryMappings.xml modules.xml next.config.js package.json prettier.xml public llm-functions-data generate-bos-widget code prompt.md prompt.md generate-transaction args prompt.md methodName prompt.md prompt.md search-backup prompt.md submit-query network prompt.md prompt.md query prompt.md template prompt.md var1 prompt.md next.svg robots.txt vercel.svg sentry.client.config.ts sentry.edge.config.ts sentry.server.config.ts src app api chat-with-functions route.ts create-account route.ts get-public-file [pluginId] [property] route.ts route.ts relay route.ts test route.ts assets images near_social_combo.svg near_social_icon.svg nearcon_banner_2023.svg vs_code_icon.svg components banners lib Spinner index.ts Toast README.md api.ts index.ts store.ts styles.ts navigation icons close.svg logo-black.svg near-logotype.svg return.svg search.svg org-links.ts sandbox Banners BannerOboarding.js VsCodeBanner.js Buttons ForkButton.js OnboardingPublishButton.js OpenCreateButton.js OpenInNewTabButton.js PublishButton.js PublishDraftAsMainButton.js RenameButton.js RenderPreviewButton.js SaveDraftButton.js Mobile MobileBlocker.js Modals AddModal.js CreateModal.js OpenModal.js OpenModuleModal.js RenameModal.js SaveDraft.js index.js Navigation FileTab.js NavigationLeft.js NavigationRight.js index.js NavigationSub index.js OnBoarding OnboardingWelcome.js Step1.js Step10.js Step2.js Step3.js Step4.js Step5.js Step6.js Step7.js Step8.js Step9.js icons arrow-small.svg arrow.svg copy.svg onboarding-1.svg onboarding-2.svg onboarding-3.svg point-1.svg point-2.svg index.js Preview index.js PreviewMetadata index.js Sandbox.js Search index.js TabEditor index.js TabMetadata index.js TabProps index.js Tabs index.js Welcome MainLoader.js index.js css MainWrapper.js index.ts utils const.js editor.js onboarding.js data bos-components.ts links.ts web3.ts hooks useBanner.ts useBosComponents.ts useBosLoaderInitializer.ts useClearCurrentComponent.ts useClickTracking.ts useFlags.ts useHashUrlBackwardsCompatibility.ts usePageAnalytics.ts useScrollBlock.ts useSignInRedirect.ts index.d.ts lib selector setup.js wallet.js mb-ai-bos selector setup.js wallet.js utils near hooks use-create-implicit-account.ts use-sign-delegate.ts use-submit-meta-transaction.ts meta-transactions.ts sign-delegated.ts types schema.ts stores auth.ts bos-loader.ts current-component.ts vm.ts styles globals.css theme.css utils analytics.ts auth.js config.ts firebase.ts form-validation.ts keypom-options.ts rudder-analytics.ts segment-analytics.ts types.ts zendesk.ts tsconfig.json types rudderstack-analytics.ts vcs.xml workflows promote-develop-to-main.yml
# NEAR (BOS)- BOSai ENCODE X NEAR HORIZON 2023 BOSai functions as a user's personal gateway into the blockchain ecosystem. It provides an interactive Chat Widget that guides users in navigating the BOS, answering their queries, and assisting in the initiation of blockchain interactions. The platform comes with a built-in feature called Tinyauth, which enables the creation of Zero Balance accounts. With Tinyauth, users can securely store keys on their device and sign blockchain transactions without the need for an initial token balance. This feature simplifies the onboarding process, eliminating the barriers associated with account funding and key management. To further enhance the user experience, Bonsai includes a relay system for meta transactions. This feature allows users to submit transactions on the blockchain without dealing with the underlying complexities, thus making their initial experiences with blockchain smooth and intuitive. Incorporating the power of AI through the Vercel AI SDK and GPT Functions, Bonsai enables users to interact with the platform, create transactions, query data, and develop widgets simply by engaging in a conversation with the system. In essence, BOSai nurtures the growth of users in the blockchain ecosystem, making the process of planting their roots and starting their journey as simple and intuitive as possible. ## BUILT Blockchain Gateway: We've forked the near-discovery and created a Chat Widget on the Blockchain Operating System (BOS). This widget serves as a user-friendly interface, guiding users through the blockchain ecosystem. Secure Authentication: We introduced BOSai Tinyauth, a minimalist implementation of FastAuth that securely stores keys on the user's device using WebAuthn. This enables users to create Zero Balance accounts and sign transactions without requiring an initial token balance. Meta Transaction Relayer: To make the transaction submission process simpler, we built a relayer as a NextJS serverless function. This relayer allows users to submit meta transactions, abstracting the complex transaction details from the users. Artificial Intelligence Integration: We've integrated the Vercel AI SDK along with GPT Functions into our platform. This integration enables BOSai to leverage AI technology, facilitating the development of user-friendly GPT plugins. GPT Plugin Development: With the help of GPT plugins, users can perform various blockchain operations, such as creating transactions, querying data, and developing BOS widgets, through simple conversations with the system. ## Setup & Development Initialize repo: ``` pnpm i ``` Start development version: ``` pnpm dev ``` ## Local Component Development 1. Run an instance of a component server like [near/bos-loader](https://github.com/near/bos-loader) which serves component code in the following format ```json { "components": { "<component path 1>": { "code": "<component 1 code>" }, "<component path 2>": { "code": "<component 2 code>" } } } ``` this will be used as a `redirectMap` in `ViewPage` 2. Open the `/flags` route of your viewer and set the BOS Loader URL e.g. `http://127.0.0.1:3030` Note: there is no hot reload, you must refresh the page to see component changes ## Local VM Development > This section needs testing since switch to pnpm If you need to make changes to the VM and test locally, you can easily link your local copy of the VM: 1. Clone the VM repo as a sibling of `near-discovery`: ``` git clone [email protected]:NearSocial/VM.git ``` Folder Structure: ``` /near-discovery /VM ``` 2. Run `pnpm link ../VM` 3. Any time you make changes to the `VM`, run `pnpm build` inside the `VM` project in order for the viewer project to pick up the changes # Toast Implemented via Radix primitives: https://www.radix-ui.com/docs/primitives/components/toast _If the current props and Stitches style overrides aren't enough to cover your use case, feel free to implement your own component using the Radix primitives directly._ ## Example Using the `openToast` API allows you to easily open a toast from any context: ```tsx import { openToast } from '@/components/lib/Toast'; ... <Button onClick={() => openToast({ type: 'ERROR', title: 'Toast Title', description: 'This is a great toast description.', }) } > Open a Toast </Button> ``` You can pass other options too: ```tsx <Button onClick={() => openToast({ type: 'SUCCESS', // SUCCESS | INFO | ERROR title: 'Toast Title', description: 'This is a great toast description.', icon: 'ph-bold ph-pizza', // https://phosphoricons.com/ duration: 20000, // milliseconds (pass Infinity to disable auto close) }) } > Open a Toast </Button> ``` ## Deduplicate If you need to ensure only a single instance of a toast is ever displayed at once, you can deduplicate by passing a unique `id` key. If a toast with the passed `id` is currently open, a new toast will not be opened: ```tsx <Button onClick={() => openToast({ id: 'my-unique-toast', title: 'Toast Title', description: 'This is a great toast description.', }) } > Deduplicated Toast </Button> ``` ## Custom Toast If you need something more custom, you can render a custom toast using `lib/Toast/Toaster.tsx` as an example like so: ```tsx import * as Toast from '@/components/lib/Toast'; ... <Toast.Provider duration={5000}> <Toast.Root open={isOpen} onOpenChange={setIsOpen}> <Toast.Title>My Title</Toast.Title> <Toast.Description>My Description</Toast.Description> <Toast.CloseButton /> </Toast.Root> <Toast.Viewport /> </Toast.Provider> ```
Near-Grants-Projects_reits-africa-frontend
README.md components Dashboard Dashboard.js ExchangeOverview ExchangeOverview.js ExchangeTokenAmount ExchangeToken.js Feed Feed.js Layout.js PeerToPeerExchange PeerToPeerExchange.js PeerToPeerOverview PeerToPeerOverview.js Pin Pin.js Portfolio Portfolio.js PortfolioInfo PortfolioInfo.js PortfolioTwo PortfolioTwo.js Table.js SendWalletAddress SendWalletAddress.js Sidebar Sidebar.js SidebarLink SidebarLink.js Success SuccessPage.js TransferAssetOverview TransferAsset.js WalletDepositInfo AssetsTable.js WalletDepositInfo.js WalletDepositStepTwo SelectAssetDropDown.js WalletDepositStepTwo.js WalletSelectAsset WalletSelectAsset.js WalletWithdrawal WalletWithdrawal.js WalletWithdrawalBankDetails WalletWithdrawalBankDetails.js WalletWithdrawalInfo WalletWithdrawalInfo.js WalletWithdrawalOverview index.js data.js jsconfig.json next-env.d.ts next.config.js package-lock.json package.json pages _app.js _document.js api hello.js dashboard index.js dashboardTwo index.js exchange index.js index.js p2p index.js portfolio index.js send index.js transactions index.js wallet index.js withdrawal index.js pin.js stepone.js postcss.config.js styles globals.css tailwind.config.js
# Reits Africa Frontend (Dashboard) This is the dashboard for reits africa ### Run the Server ```bash npm run dev # or yarn dev ``` Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
noemk2_enviar_recivir_as
README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts index.spec.ts index.ts package.json
Enviar/Recivir near con AssemblyScript ================== Introducción a enviar_recivir en near (assemblyScript) ================== un enviar_recivir en near protocol, este contrato te perminte: 1. paga en near 2. recive en near 👨‍💻 Instalación en local =========== Para correr este proyecto en local debes seguir los siguientes pasos: Paso 1: Pre - Requisitos ------------------------------ 1. Asegúrese de haber instalado [Node.js] ≥ 12 ((recomendamos usar [nvm]) 2. Asegúrese de haber instalado yarn: `npm install -g yarn` 3. Instalar dependencias: `yarn install` 4. Crear un test near account [NEAR test account] 5. Instalar el NEAR CLI globally: [near-cli] es una interfaz de linea de comando (CLI) para interacturar con NEAR blockchain yarn install --global near-cli Step 2: Configura tu NEAR CLI ------------------------------- Configura tu near-cli para autorizar su cuenta de prueba creada recientemente: near login Step 3: Clonar Repositorio ------------------------------- Este comando nos permite clonar el repositorio de nuestro proyecto ```bash git clone https://github.com/noemk2/enviar_recivir.git ``` Una vez que hayas descargado el repositorio, asegurate de ejecutar los comandos dentro del repositorio descargado. Puedes hacerlo con ```bash cd enviar_recivir/ ``` Step 4: Realiza el BUILD para implementación de desarrollo de contrato inteligente ------------------------------------------------------------------------------------ Instale el gestor de dependencia de Node.js dentro del repositorio ```bash npm install ``` Cree el código de contrato inteligente e implemente el servidor de desarrollo local: ```bash yarn deploy:dev ``` Cree la variable local $CONTRACT_NAME (permite guardar tu contrato temporal en una variable facil de recordar) ```bash source ./neardev/dev-account.env ``` Consulte` package.json` para obtener una lista completa de `scripts` que puede ejecutar con` yarn`). Este script le devuelve un contrato inteligente provisional implementado (guárdelo para usarlo más tarde) ¡Felicitaciones, ahora tendrá un entorno de desarrollo local ejecutándose en NEAR TestNet! ✏️ Comando v ----------------------------------------------- Para Linux: ```bash coming soon ``` 🤖 Test ================== Las pruebas son parte del desarrollo, luego, para ejecutar las pruebas en el contrato inteligente , debe ejecutar el siguiente comando: coming soon ============================================== [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [NEAR test account]: https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account [nvm]: https://github.com/nvm-sh/nvm [UX/UI]: https://www.figma.com/proto/GqP5EF5zRZRvAv3HoaSsuN/uniwap?node-id=39%3A2300&scaling=min-zoom&page-id=0%3A1&starting-point-node-id=39%3A2300&hide-ui=1 [UX/UI]: https://www.figma.com/proto/0dZLC0WI1eVsfjeKu3T8J8/Garant%C3%ADzame?node-id=2%3A8&scaling=scale-down-width&page-id=0%3A1&starting-point-node-id=2%3A8
esaminu_console-boilerplate-temsdfsdgasdapasdlate-rs-ss25dfghaafdghdfhg
.github scripts runfe.sh workflows deploy-to-console.yml readme.yml tests.yml .gitpod.yml README.md contract README.md build.sh deploy.sh package-lock.json package.json src contract.ts model.ts utils.ts tsconfig.json integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
# Donation Contract The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. ```ts @call donate() { // Get who is calling the method and how much $NEAR they attached let donor = near.predecessorAccountId(); let donationAmount: bigint = near.attachedDeposit() as bigint; let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) let toTransfer = donationAmount; // This is the user's first donation, lets register it, which increases storage if(donatedSoFar == BigInt(0)) { assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); // Subtract the storage cost to the amount to transfer toTransfer -= STORAGE_COST } // Persist in storage the amount donated so far donatedSoFar += donationAmount this.donations.set(donor, donatedSoFar.toString()) // Send the money to the beneficiary const promise = near.promiseBatchCreate(this.beneficiary) near.promiseBatchActionTransfer(promise, toTransfer) // Return the total amount donated so far return donatedSoFar.toString() } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` The contract will be automatically initialized with a default `beneficiary`. To initialize the contract yourself do: ```bash # Use near-cli to initialize contract (optional) near call <dev-account> init '{"beneficiary":"<account>"}' --accountId <dev-account> ``` <br /> ## 2. Get Beneficiary `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> beneficiary ``` <br /> ## 3. Get Number of Donations `donate` forwards any attached money to the `beneficiary` while keeping track of it. `donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> donate --amount 1 --accountId <account> ``` **Tip:** If you would like to `donate` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Donation 💸 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/donation-js) [![](https://img.shields.io/badge/Contract-js-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fdonation-js%2Fbadge&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/donation-js/goto) Our Donation example enables to forward money to an account while keeping track of it. It is one of the simplest examples on making a contract receive and send money. ![](https://docs.near.org/assets/images/donation-7cf65e5e131274fd1ae9aa34bc465bb8.png) # What This Example Shows 1. How to receive and transfer $NEAR on a contract. 2. How to divide a project into multiple modules. 3. How to handle the storage costs. 4. How to handle transaction results. 5. How to use a `Map`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-js). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome).
jacobnaumann_near-charity-project
README.md as-pect.config.js asconfig.json package.json scripts 1.dev-deploy.sh 2.use-contract.sh 3.cleanup.sh README.md src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts singleton __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
## Setting up your terminal The scripts in this folder are designed to help you demonstrate the behavior of the contract(s) in this project. It uses the following setup: ```sh # set your terminal up to have 2 windows, A and B like this: ┌─────────────────────────────────┬─────────────────────────────────┐ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ └─────────────────────────────────┴─────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands _helper scripts_ ```sh 1.dev-deploy.sh # helper: build and deploy contracts 2.use-contract.sh # helper: call methods on ContractPromise 3.cleanup.sh # helper: delete build and deploy artifacts ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linuo-watch-command#191068) # `near-sdk-as` Starter Kit This is a good project to use as a starting point for your AssemblyScript project. ## Samples This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage There are 2 AssemblyScript contracts in this project, each in their own folder: - **simple** in the `src/simple` folder - **singleton** in the `src/singleton` folder ### Simple We say that an AssemblyScript contract is written in the "simple style" when the `index.ts` file (the contract entry point) includes a series of exported functions. In this case, all exported functions become public contract methods. ```ts // return the string 'hello world' export function helloWorld(): string {} // read the given key from account (contract) storage export function read(key: string): string {} // write the given value at the given key to account (contract) storage export function write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} ``` ### Singleton We say that an AssemblyScript contract is written in the "singleton style" when the `index.ts` file (the contract entry point) has a single exported class (the name of the class doesn't matter) that is decorated with `@nearBindgen`. In this case, all methods on the class become public contract methods unless marked `private`. Also, all instance variables are stored as a serialized instance of the class under a special storage key named `STATE`. AssemblyScript uses JSON for storage serialization (as opposed to Rust contracts which use a custom binary serialization format called borsh). ```ts @nearBindgen export class Contract { // return the string 'hello world' helloWorld(): string {} // read the given key from account (contract) storage read(key: string): string {} // write the given value at the given key to account (contract) storage @mutateState() write(key: string, value: string): string {} // private helper method used by read() and write() above private storageReport(): string {} } ``` ## Usage ### Getting started (see below for video recordings of each of the following steps) INSTALL `NEAR CLI` first like this: `npm i -g near-cli` 1. clone this repo to a local folder 2. run `yarn` 3. run `./scripts/1.dev-deploy.sh` 3. run `./scripts/2.use-contract.sh` 4. run `./scripts/2.use-contract.sh` (yes, run it to see changes) 5. run `./scripts/3.cleanup.sh` ### Videos **`1.dev-deploy.sh`** This video shows the build and deployment of the contract. [![asciicast](https://asciinema.org/a/409575.svg)](https://asciinema.org/a/409575) **`2.use-contract.sh`** This video shows contract methods being called. You should run the script twice to see the effect it has on contract state. [![asciicast](https://asciinema.org/a/409577.svg)](https://asciinema.org/a/409577) **`3.cleanup.sh`** This video shows the cleanup script running. Make sure you add the `BENEFICIARY` environment variable. The script will remind you if you forget. ```sh export BENEFICIARY=<your-account-here> # this account receives contract account balance ``` [![asciicast](https://asciinema.org/a/409580.svg)](https://asciinema.org/a/409580) ### Other documentation - See `./scripts/README.md` for documentation about the scripts - Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` ## The file system ```sh ├── README.md # this file ├── as-pect.config.js # configuration for as-pect (AssemblyScript unit testing) ├── asconfig.json # configuration for AssemblyScript compiler (supports multiple contracts) ├── package.json # NodeJS project manifest ├── scripts │   ├── 1.dev-deploy.sh # helper: build and deploy contracts │   ├── 2.use-contract.sh # helper: call methods on ContractPromise │   ├── 3.cleanup.sh # helper: delete build and deploy artifacts │   └── README.md # documentation for helper scripts ├── src │   ├── as_types.d.ts # AssemblyScript headers for type hints │   ├── simple # Contract 1: "Simple example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 1 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 1 │   ├── singleton # Contract 2: "Singleton-style example" │   │   ├── __tests__ │   │   │   ├── as-pect.d.ts # as-pect unit testing headers for type hints │   │   │   └── index.unit.spec.ts # unit tests for contract 2 │   │   ├── asconfig.json # configuration for AssemblyScript compiler (one per contract) │   │   └── assembly │   │   └── index.ts # contract code for contract 2 │   ├── tsconfig.json # Typescript configuration │   └── utils.ts # common contract utility functions └── yarn.lock # project manifest version lock ``` You may clone this repo to get started OR create everything from scratch. Please note that, in order to create the AssemblyScript and tests folder structure, you may use the command `asp --init` which will create the following folders and files: ``` ./assembly/ ./assembly/tests/ ./assembly/tests/example.spec.ts ./assembly/tests/as-pect.d.ts ```
iamvon_Pristorage
.gitpod.yml GUIDE.md README.md babel.config.js contract Cargo.toml README.md compile.js src lib.rs dist avatar.svg doc.svg logo.svg package.json src App.js __mocks__ fileMock.js assets avatar.svg doc.svg logo-black.svg logo-white.svg logo.svg components DeleteButton index.js FilePreview index.css index.js GuardedRoute index.js ShareFileButton index.js ShareFolderButton index.js config.js global.css hook useDownloadFile.js useFetchFolder.js useFetchSharedDoc.js useFetchUser.js useFileCreate.js useFilePreview.js index.html index.js jest.init.js layout MainLayout.js layout.css main.test.js pages HomeV2.js Login.js SharedWithMe.js style General.page.css LoginPage.module.css router index.js store slice folderV2.slice.js root.slice.js sharedWithMeV2.js user.slice.js store.js utils.js utils file.utils.js keypair.utils.js near.utils.js url.utils.js web3.storage.js wallet login index.html worker.js
Vi storage 2.0 Smart Contract ================== A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard Rust tests using [cargo] with a `--nocapture` flag so that you can see any debug info you print to the console. [smart contract]: https://docs.near.org/docs/develop/contracts/overview [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://github.com/near/near-sdk-rs#pre-requisites [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html PriStorage ================== This [React] app was initialized with [create-near-app] Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy & Run PriStorage DApp ====== 1. **Prerequisites**: Make sure you've installed [Node.js] ≥ 12 2. **Install dependencies**: `yarn install` Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you're ready to deploy your smart contract permanent on the NEAR TestNet, here's how. Step 0: Install near-cli ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn global add near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `YOUR-ACCOUNT-NAME.testnet`, you can deploy your contract to `vi-storage.YOUR-ACCOUNT-NAME.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `vi-storage.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: ```bash near login ``` 2. Create a subaccount (replace `YOUR-ACCOUNT-NAME` below with your actual account name): ```bash near create-account vi-storage.YOUR-ACCOUNT-NAME.testnet --masterAccount YOUR-ACCOUNT-NAME.testnet ``` Step 2: Set contract name in code --------------------------------- Add CONTRACT_NAME to the .env file at the root folder. ```bash CONTRACT_NAME=vi-storage.YOUR-ACCOUNT-NAME.testnet ``` Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'vi-storage.YOUR-ACCOUNT-NAME.testnet' Step 3: Deploy smart contract & run DApp! --------------- One command: yarn dev As you can see in `package.json`, this does two things: 1. ```prestart script```: builds & deploys smart contract to NEAR TestNet. 2. Using CONTRACT_NAME variable in .env to run DApp authorization on the localhost. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
Multiplier-Effect_Chainstock
README.md package.json public index.html manifest.json robots.txt static icon.svg src App.js App.test.js Routes.js components Logo.js index.js layouts DashboardLayout.js DashboardNavbar.js DashboardSidebar.js MainLayout.js MainNavbar.js NavItem.js redux action index.js constants.js reducers app.js index.js store index.js reportWebVitals.js setupTests.js theme GlobalStyles.js theme.js utils RouteWithLayout.js view AccountView StockList.js index.js CreateTokenView Backdrop.js CreateNft.js index.js DashboardView Album.js index.js MainView index.js MarketPubView Album.js index.js new.js popular.js TokenView InfoNft.js MediaNft.js index.js
# Chainstock ## ChainStock를 소개합니다! ChainStock은 비상장주식 중 비통일주식의 복잡한 거래방식과 주식 소유자 위변조 문제를 해결하는 블록체인 기반 비상장주식 거래 플랫폼입니다. 현재 투자자들의 많은 관심을 받고 있는 비상장주식은 거래 규모와 그 가치가 점점 더 커지고 있으나 비상장주식을 거래하는 데에는 많은 서류와 절차가 필요한 상황입니다. 또한 비상장주식의 소유자를 확인할 수 있는 방법이 시스템화 되어 있지 않아 양도자의 소유권 확인 역시 복잡하고 위변조 가능성이 있습니다. ChainStock은 블록체인을 통해 거래내역을 기록하고 소유권을 증명하여 이러한 불편함과 위험성을 없앴습니다. ## ChainStock의 기술 소개 ChainStock은 NEAR Protocol을 기반으로 운영되며 NFT 기술을 사용하고 Smart Contract를 통해 이를 구현합니다. **Near Protocol** NEAR Protocol은 레거시 블록체인의 문제점인 비싼 비용과 느린 처리 속도를 해결하기 위해 등장했으며, 최종 확인 처리 속도 1초와 저렴한 수수료가 특징인 블록체인이며 Sharding 기술을 도입하고 구현하는 최초의 블록체인입니다. Mass adoption을 위해 개발자 친화성, 사용성에 포커스를 맞춘 NEAR Protocol을 사용해 빠르고 저렴한 비용에 유저들이 비상장 주식 거래를 할 수 있도록 DApp을 빌딩하고 있습니다. 더 많은 NEAR Protocol에 대한 설명은 NEAR Protocol 홈페이지를 참고해주세요. [NEAR Protocol | Reimagine your World](https://near.org) **NFT 기술** NFT는 ‘대체 불가능한 토큰’으로 희소성을 가진 디지털 자산 즉, 디지털 세계에서 등기부등본과 같은 개념입니다. 최초의 창작자가 누구인지, 어떤 사람들이 소유해왔는지를 고유한 암호로 저장하기 때문에 소유권의 위변조가 불가능한 것이 특징입니다. ‘원본’을 증명할 수 있는 기술로 주식의 소유자 증명과 거래시 위변조를 막을 수 있기 때문에 주요 기술로 사용하였습니다. 비통일주식 1주를 NFT 토큰으로 발행하는 데 사용됩니다. **ERC721 기반 Smart Contract** 한 주 단위로 구성되어있는 주식의 특성과 맞게 비통일주식을 스마트 컨트랙트를 통해 ERC721 표준을 따른 NFT 토큰으로 발행하고 거래하는 형태로 구현합니다. 스마트 컨트랙트 주요 기능은 1. 비통일 주식을 NFT로 만들기 위해 발행하고 `approve` 과정을 거치기 2. 비통일 주식을 토큰으로 구매하고 사용자 간 `transfer`를 구현하기 입니다. ## ChainStock의 기대효과 **간편한 비통일주식 발행으로 스타트업, 벤처 생태계 활성화 가능** 그동안 복잡한 비통일주식 거래 방식으로 인해 스타트업도 비통일주식을 발행하기 어려웠고 투자자 역시 구입하기 어려웠습니다. 하지만 NFT 기술을 이용한다면 발행과 구매, 거래가 모두 간편해지기 때문에 투자가 활성화될 수 있습니다. **비통일주식 거래의 단순화, 간편화** 기존에 많은 서류들이 필요했던 것에 비해 플랫폼에 가입하고 계좌나 지갑을 연결하고 플랫폼 위에서 바로 거래하기만 하면 되므로 매우 간편합니다. **주주명부 관리 간편화** 기업에서 직접 관리해야했던 주주명부 역시 토큰 소유권 확인을 통해 자동으로 관리되고 간편하고 빠르게 확인할 수 있습니다. **비통일주식 관련 서류 위변조검사 기능** 기존에 많은 서류들이 위변조 되었는지 구매자와 기업 측에서 검사를 했어야 하는데 반면 NFT 기술을 사용한다면 트랜잭션만 확인하면 되므로 위변조검사 기능이 매우 간편해집니다. **비통일주식 거래 장부화 및 투명화** 블록체인 기술의 장점을 이용해 21세기에 맞지 않는 거래 과정이 수기로 이루어지는 복잡하고 불투명했던 방식을 간편하고 투명하게 디지털화시켜 변화시킬 수 있습니다. ## 개인 사용자를 위한 사용설명서 ### 1. 회원가입 / 로그인 1-1. 아이디와 비밀번호를 설정하여 계정을 생성합니다. ![회원가입 - STEP 1](https://user-images.githubusercontent.com/56113089/144750185-c16dd779-f390-4a49-9f86-62bd6f0d8931.png) 1-2. 특정금융정보이용법에 따라 신원 확인을 진행해주세요. ![회원가입 - STEP 2](https://user-images.githubusercontent.com/56113089/144750189-640f52ed-314f-47a5-84fc-f010031d27c5.png) 1-3. 회원가입이 완료되었다면 로그인해주세요. ![로그인](https://user-images.githubusercontent.com/56113089/144750196-8fdac98e-e499-4e69-9ef7-3bfd9bec2939.png) ### 2. 메인화면 - 회원가입 후 로그인을 완료하면 다음과 같은 메인화면을 만날 수 있습니다. - 새로운 종목과 거래가 많은 인기 종목을 확인할 수 있습니다. - 왼쪽의 메뉴바를 통해 'Market'과 'Mypage'로 이동할 수 있습니다. ![MainPage](https://user-images.githubusercontent.com/56113089/144750222-5c570f55-622c-4574-8ece-4f6ec71c3d77.png) ### 3. 종목 확인 - 왼쪽 메뉴바에서 'Market'을 누르면 다음과 같이 전체 기업 종목 확인을 할 수 있습니다. - 기업명이나 키워드를 통해 기업을 검색할 수 있습니다. - 기업의 이름, 기업 가치, 기업의 짧은 설명, 최근 거래 시점, 최저 가격을 확인할 수 있습니다. - '보유중인 기업 확인하기' 버튼을 누르면 마이페이지로 이동하게 됩니다. - 각 기업 박스를 누르면 각 기업의 상세 페이지로 이동하게 됩니다. ![Market](https://user-images.githubusercontent.com/56113089/144750229-ab55bdf0-0648-4ff2-b668-49955009c051.png) ### 4. 기업 상세 페이지 / 종목 구매 - 3에서 기업 박스를 누르면 다음과 같은 화면을 볼 수 있습니다. - 해당 기업 매물을 아래에서 확인할 수 있고, 종목명, 가격, 등록일, 등록 번호로 이루어져 있습니다. - 낮은 가격순, 높은 가격순, 등록일 순으로 정렬이 가능합니다. - 매물의 아무 부분이나 클릭하면 해당 매물을 구매할 수 있는 팝업이 생성됩니다. ![Detail](https://user-images.githubusercontent.com/56113089/144750236-f756e25f-b508-41aa-a1b3-314916003f7c.png) ### 5. 마이페이지 / 종목 판매 - 왼쪽 메뉴바의 'MyPage'를 누르거나 종목 확인 페이지에서 '보유중인 기업 확인하기' 버튼을 누르면 본 화면으로 이동할 수 있습니다. - 보유 중인 주식 목록을 확인할 수 있으며 거래 일자와 구매 가격, 구매 영수증을 확인할 수 있습니다. - 보유 중인 주식 목록에서 판매 버튼을 누르면 판매할 수 있는 팝업이 생성됩니다. - 판매 중인 주식 목록에서 현재 내가 판매하고 있는 주식의 펀매 등록 일자와, 구매 가격, 판매 가격을 확인할 수 있습니다. ![마이페이지](https://user-images.githubusercontent.com/56113089/144750249-f2d1495f-38bc-443d-ada7-f9458660f1d3.png) - '구매 영수증' 칸을 누르면 다음과 같이 NEAR transaction을 확인할 수 있는 페이지로 이동하게 된다. ![Untitled](https://user-images.githubusercontent.com/56113089/144750259-6d5967a6-fdcf-40c2-b944-a15a196bb793.png) ## 기업 사용자를 위한 설명서 ### 1. 회원가입 / 로그인 1-1. 회원가입 페이지에서 아래의 기업용 계정 만들기 버튼을 눌러 아이디와 비밀번호를 설정하여 계정을 생성해주세요. ![회원가입 - STEP 1](https://user-images.githubusercontent.com/56113089/144750268-7cdd88e8-d41f-49ad-a82f-0c6689e252e6.png) 1-2. 특정금융정보이용법에 따라 신원 확인을 진행해주세요. ![회원가입 - STEP 2](https://user-images.githubusercontent.com/56113089/144750279-67840a14-515a-456a-8ef6-468fcf9fb1f9.png) 1-3. 회원가입이 완료되었다면 로그인해주세요. ![로그인](https://user-images.githubusercontent.com/56113089/144750287-8f94e329-4471-42ef-b77b-6a8a58b3f35e.png) ### 2. Home 화면 - 회원가입 후 로그인을 완료하면 다음과 같은 메인화면을 만날 수 있습니다. - 새로운 종목과 거래가 많은 인기 종목을 확인할 수 있습니다. - 왼쪽의 메뉴바를 통해 'Market'과 'Mypage'로 이동할 수 있습니다. ![MainPage_기업](https://user-images.githubusercontent.com/56113089/144750293-131c8741-65dc-4b51-abe9-0b76e8535838.png) ### 3. MyPage - 주주명부 확인 - 왼쪽 메뉴바의 'MyPage'를 누르면 기업 정보를 관리할 수 있는 본 페이지로 이동할 수 있습니다. - 본 페이지에서 기업의 주식을 보유하고 있는 주주명부를 확인할 수 있습니다. - 지분율 순, 구매일자 순, 주주명 순으로 정렬할 수 있습니다. - '주주명부 출력하기' 버튼을 통해 아래의 주주명부를 출력하여 저장할 수 있습니다. - '내 기업 상세페이지 바로가기' 버튼을 통해 기업의 마켓 상세 페이지로 이동할 수 있습니다. ![주주명부 관리 페이지](https://user-images.githubusercontent.com/56113089/144750299-1b70e4a4-b0d5-46d9-8401-a5d679c8b0b9.png) - '거래 영수증' 칸을 누르면 다음과 같이 NEAR transaction을 확인할 수 있는 페이지로 이동하게 된다. ![Untitled](https://user-images.githubusercontent.com/56113089/144750307-8255f2f2-d1b6-4062-bbc1-b82fcbef5f68.png) ### 4. 기업 매물 확인 - 개인 사용자와 마찬가지로 Market에서 나의 기업을 클릭하면 다음과 같이 기업의 매물을 확인할 수 있고, MyPage에서의 '내 기업 상세페이지 바로가기' 버튼을 통해서도 이동할 수 있습니다. ![Detail_기업](https://user-images.githubusercontent.com/56113089/144750317-54e73056-f436-4bd7-9616-ef963ac10fd8.png) <!-- @format --> # Chainstock ## Quick Start ### 배포된 데모 웹 사이트 접속 후 실행 - Chrome 최적화 [https://chainstock.vercel.app](https://chainstock.vercel.app) ### 직접 다운로드 후 실행 #### 레포지토리 복사 ``` git clone https://github.com/Multiplier-Effect/Chainstock ``` #### 필요 환경 설치 ``` yarn ``` #### 프론트엔드 실행 ``` yarn start ``` #### 프론트엔드 접속 ``` https://localhost:3000/ ``` ## ChainStock를 소개합니다! ChainStock은 비상장주식 중 비통일주식의 복잡한 거래방식과 주식 소유자 위변조 문제를 해결하는 블록체인 기반 비상장주식 거래 플랫폼입니다. 현재 투자자들의 많은 관심을 받고 있는 비상장주식은 거래 규모(2022년 기준 시초 약 34조)와 그 가치가 점점 더 커지고 있으나 비상장주식을 거래하는 데에는 많은 서류와 절차가 필요한 상황입니다. 또한 비상장주식의 소유자를 확인할 수 있는 방법이 시스템화 되어 있지 않아 양도자의 소유권 확인 역시 복잡하고 위변조 가능성이 있습니다. ChainStock은 블록체인을 통해 거래내역을 기록하고 소유권을 증명하여 이러한 불편함과 위험성을 없앴습니다. ## ChainStock의 기술 소개 ChainStock은 NEAR Protocol을 기반으로 운영되며 NFT 기술을 사용하고 Smart Contract를 통해 이를 구현합니다. **Near Protocol** NEAR Protocol은 레거시 블록체인의 문제점인 비싼 비용과 느린 처리 속도를 해결하기 위해 등장했으며, 최종 확인 처리 속도 1초와 저렴한 수수료가 특징인 블록체인이며 Sharding 기술을 도입하고 구현하는 최초의 블록체인입니다. Mass adoption을 위해 개발자 친화성, 사용성에 포커스를 맞춘 NEAR Protocol을 사용해 빠르고 저렴한 비용에 유저들이 비상장 주식 거래를 할 수 있도록 DApp을 빌딩하고 있습니다. 더 많은 NEAR Protocol에 대한 설명은 NEAR Protocol 홈페이지를 참고해주세요. [NEAR Protocol | Reimagine your World](https://near.org) **NFT 기술** NFT는 ‘대체 불가능한 토큰’으로 희소성을 가진 디지털 자산 즉, 디지털 세계에서 등기부등본과 같은 개념입니다. 최초의 창작자가 누구인지, 어떤 사람들이 소유해왔는지를 고유한 암호로 저장하기 때문에 소유권의 위변조가 불가능한 것이 특징입니다. ‘원본’을 증명할 수 있는 기술로 주식의 소유자 증명과 거래시 위변조를 막을 수 있기 때문에 주요 기술로 사용하였습니다. 비통일주식 1주를 NFT 토큰으로 발행하는 데 사용됩니다. **ERC721 기반 Smart Contract** 한 주 단위로 구성되어있는 주식의 특성과 맞게 비통일주식을 스마트 컨트랙트를 통해 ERC721 표준을 따른 NFT 토큰으로 발행하고 거래하는 형태로 구현합니다. 스마트 컨트랙트 주요 기능은 1. 비통일 주식을 NFT로 만들기 위해 발행하고 `approve` 과정을 거치기 2. 비통일 주식을 토큰으로 구매하고 사용자 간 `transfer`를 구현하기 입니다. ## ChainStock의 기대효과 **간편한 비통일주식 발행으로 스타트업, 벤처 생태계 활성화 가능** 그동안 복잡한 비통일주식 거래 방식으로 인해 스타트업도 비통일주식을 발행하기 어려웠고 투자자 역시 구입하기 어려웠습니다. 하지만 NFT 기술을 이용한다면 발행과 구매, 거래가 모두 간편해지기 때문에 투자가 활성화될 수 있습니다. **비통일주식 거래의 단순화, 간편화** 기존에 많은 서류들이 필요했던 것에 비해 플랫폼에 가입하고 계좌나 지갑을 연결하고 플랫폼 위에서 바로 거래하기만 하면 되므로 매우 간편합니다. **주주명부 관리 간편화** 기업에서 직접 관리해야했던 주주명부 역시 토큰 소유권 확인을 통해 자동으로 관리되고 간편하고 빠르게 확인할 수 있습니다. **비통일주식 관련 서류 위변조검사 기능** 기존에 많은 서류들이 위변조 되었는지 구매자와 기업 측에서 검사를 했어야 하는데 반면 NFT 기술을 사용한다면 트랜잭션만 확인하면 되므로 위변조검사 기능이 매우 간편해집니다. **비통일주식 거래 장부화 및 투명화** 블록체인 기술의 장점을 이용해 21세기에 맞지 않는 거래 과정이 수기로 이루어지는 복잡하고 불투명했던 방식을 간편하고 투명하게 디지털화시켜 변화시킬 수 있습니다. ## 개인 사용자를 위한 사용설명서 ### 1. 회원가입 / 로그인 ChainStock은 NEAR Protocol 공식 wallet을 사용하여 로그인합니다. 1-1. [https://wallet.near.org](https://wallet.near.org/) NEAR Protocol 공식 월렛 홈페이지에서 자신의 지갑을 생성합니다. <img width="1280" alt="1111" src="https://user-images.githubusercontent.com/56113089/170502187-74d31815-1569-4140-968f-871adab6c6fd.png"> 1-2. 지갑 생성이 완료되었다면 메인화면 오른쪽 상단의 버튼을 눌러 NEAR wallet에 로그인해주세요. <img width="1280" alt="2" src="https://user-images.githubusercontent.com/56113089/170502300-0ef01436-71db-4a40-9fce-3b50c41419d1.png"> ### 2. 종목 확인 - 로그인시 바로 만날 수 있는 페이지 입니다. - 왼쪽 메뉴바에서 'Market'을 눌러서도 다음과 같이 전체 기업 종목 확인을 할 수 있습니다. - 구매가능한 주식의 이름과 가격, 소유주를 확인할 수 있습니다. - 각 주식의 ‘view’를 누르면 각 매물의 상세페이지로 이동하게 됩니다. ![3](https://user-images.githubusercontent.com/56113089/170502484-f3f81e3a-b907-4bb1-a07b-1ad6cd3e982f.png) ### 3. 주식 구매 - 2에서 view를 누르면 볼 수 있는 매물의 상세 페이지입니다. - 구매하고자 하는 주식의 기업정보와 소유자, 가격을 볼 수 있습니다. - 구매하기 버튼을 클릭하면 해당 매물을 구매할 수 있는 페이지로 이동합니다. - 구매 페이지에서 Approve를 누르면 구매가 완료됩니다. ![4](https://user-images.githubusercontent.com/56113089/170502535-db08cf28-cdc1-4d4c-bf0c-bbdb268880bb.png) ![5](https://user-images.githubusercontent.com/56113089/170502638-08a89087-1be2-47b8-8c63-9084d1744d02.png) ### 4. 마이페이지 / 종목 판매 - 왼쪽 메뉴바의 'MyPage'를 누르면 본 화면으로 이동할 수 있습니다. - 보유 중인 주식 목록과 현재 판매중인 주식 목록을 확인할 수 있습니다. - 보유 중인 주식 목록에서 판매 버튼을 누르면 판매할 수 있는 팝업이 생성됩니다. - ![6](https://user-images.githubusercontent.com/56113089/170502679-1fe2471e-5a2c-4de0-87df-e2b71755b933.png) ![7](https://user-images.githubusercontent.com/56113089/170502692-6c9ec50f-8ed4-4893-815b-404c62930bca.png) ### 5. 주주 명부 확인 - 주식을 소유 중인 사람들과 그 거래를 증명하는 거래 증명서를 확인할 수 있습니다. ![8](https://user-images.githubusercontent.com/56113089/170502736-c5e76343-5a0f-416b-ac6d-ca959f86a3d9.png) - '거래 증명서' 칸을 누르면 다음과 같이 실제 NEAR transaction을 확인할 수 있는 페이지로 이동하게 됩니다. ![9](https://user-images.githubusercontent.com/56113089/170502762-e51c4ddc-86e5-44d2-bddd-082ca7f307e8.png) # TBD # TBD Minimal NEP141 + Metadata Token Launcher TBD Fork of: https://github.com/mikedotexe/nep-141-examples (basic)
Learn-NEAR_NCD--wagers
.gitpod.yml README.md contract README.md as-pect.config.js asconfig.json assembly __tests__ as-pect.d.ts main.spec.ts as_types.d.ts index.ts model.ts tsconfig.json compile.js package-lock.json package.json package-lock.json package.json src assets logo-black.svg logo-white.svg config.js global.css index.html index.js main.test.js utils.js wallet login index.html
learn-near ================== This app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `npm install` 3. Run the local development server: `npm run dev` (see `package.json` for a full list of `scripts` you can run with `npm`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/src` folder. `/src/index.html` is a great place to start exploring. Note that it loads in `/src/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `npm run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `learn-near.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `learn-near.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account learn-near.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'learn-near.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: npm run deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages learn-near Smart Contract ================== A [smart contract] written in [AssemblyScript] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install [Node.js] ≥ 12 Exploring The Code ================== 1. The main smart contract code lives in `assembly/index.ts`. You can compile it with the `./compile` script. 2. Tests: You can run smart contract tests with the `./test` script. This runs standard AssemblyScript tests using [as-pect]. [smart contract]: https://docs.near.org/docs/roles/developer/contracts/intro [AssemblyScript]: https://www.assemblyscript.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [as-pect]: https://www.npmjs.com/package/@as-pect/cli
jerrymusaga_Crossword-Smart-Contaract
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
NearDeFi_burrow-live-feed
package.json public index.html manifest.json robots.txt src App.js App.test.js components SocialAccount SocialAccount.js common MutedDecimals.js token TokenBadge.js TokenBalance.js TokenSymbol.js data account.js near.js refFinance.js socialAccount.js token.js utils.js index.css index.js setupTests.js
laponte243_near-bookshop
Cargo.toml README.md src lib.rs
# near-bookshop
open-web-academy_owh-retos
2023-03-guadalajara README.md aurora.md comunidad-primero.md mejor-pitch.md meta-pool.md near.md 2023-05-monterrey README.md bos-is-multichain.md comunidad-primero.md evm-is-bos.md mejor-pitch.md meta-pool.md near-is-bos.md pide-tu-merch.md README.md
# Open Web House - Los Retos Construir = Colaborar ¿Eres capaz de sumarte a construir la web 3? Aquí te dejamos los retos para construir la Web 3. Conoce más [aquí](https://ow.academy/house) ![image|500x500](img/owh-monterrey.jpeg) # Retos Open Web House Guadalajara ![image|500x500](img/openwebhouse-gdl.jpeg) * Evento: Open Web House Guadalajara 2023 * Fecha de publicación: 1 de marzo del 2023. * Fecha de actualización: NA ## Retos | # | Reto | Descripción | Bolsa de premios | |---|-------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|------------------| | 1 | Construyendo valor en NEAR Protocol | Construye una aplicación decentralizada utilizando la tecnología de NEAR. Valida su utilidad con tus usuarios objetivos. | 1000 USDC | | 2 | Construyendo valor en Aurora | Construye una aplicación decentralizada utilizando la tecnología de Aurora. Valida su utilidad con tus usuarios objetivos. | 1000 USDC | | 3 | Mejor Pitch del evento | Presenta el mejor pitch en el Open Web House. | 250 USDC | | 4 | Construyendo valor con Meta Pool | Colabora con Meta Pool en crear la siguiente generación de plataformas de staking liquido. | 1000 USDC | | 5 | Comunidad primero | Haz crecer hasta la luna la comunidad de tu proyecto. | 250 USDC | | - | - | Total | 3500 USDC | # Retos Open Web House Monterrey 2023 ![image|500x500](im/../img/owh-monterrey.jpeg) * Evento: Open Web House Monterrey 2023 * Fecha de publicación: 15 de mayo del 2023. * Fecha de actualización: NA ## Retos | # | Reto | Descripción | Bolsa de premios | |---|-------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|------------------| | 1 | BOS is multichain | Construye un gateway que te permita tener un blockchain descentralizado para cualquier cadena | 600 USDC | | 2 | Comunidad primero | Haz crecer hasta la luna la comunidad de tu proyecto. | 200 USDC | | 3 | EVM is BOS | Construye un widget para una aplicación corriendo dentro de un EVM en BOS | 750 USDC | | 4 | Mejor Pitch del evento | Presenta el mejor pitch en el Open Web House. | 200 USDC | | 5 | Construyendo valor con Meta Pool | Colabora con Meta Pool en crear la siguiente generación de plataformas de staking liquido. | 1000 USDC | | 6 | NEAR is BOS | Construye un widget para una aplicación corriendo dentro de NEAR Protocol | 750 USDC | | 7 | Pide tu merch | Unete a las comunidades de NEAR y Open Web Academy y recibe Merch del evento | N/A | | - | - | Total | 3500 USDC |
open-web-academy_OWH-vending-machine-js
README.md owa open-web-house vending-machine .gitpod.yml README.md contract README.md babel.config.json build.sh deploy.sh node_modules .bin sha.js .package-lock.json @ampproject remapping README.md dist remapping.umd.js types build-source-map-tree.d.ts remapping.d.ts source-map-tree.d.ts source-map.d.ts types.d.ts package.json @babel code-frame README.md lib index.js package.json compat-data README.md corejs2-built-ins.js corejs3-shipped-proposals.js data corejs2-built-ins.json corejs3-shipped-proposals.json native-modules.json overlapping-plugins.json plugin-bugfixes.json plugins.json native-modules.js overlapping-plugins.js package.json plugin-bugfixes.js plugins.js core README.md lib config cache-contexts.js caching.js config-chain.js config-descriptors.js files configuration.js import-meta-resolve.js index-browser.js index.js module-types.js package.js plugins.js types.js utils.js full.js helpers config-api.js deep-array.js environment.js index.js item.js partial.js pattern-to-regex.js plugin.js printer.js resolve-targets-browser.js resolve-targets.js util.js validation option-assertions.js options.js plugins.js removed.js errors config-error.js rewrite-stack-trace.js gensync-utils async.js fs.js functional.js index.js parse.js parser index.js util missing-plugin-helper.js tools build-external-helpers.js transform-ast.js transform-file-browser.js transform-file.js transform.js transformation block-hoist-plugin.js file file.js generate.js merge-map.js index.js normalize-file.js normalize-opts.js plugin-pass.js util clone-deep.js vendor import-meta-resolve.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json src config files index-browser.ts index.ts resolve-targets-browser.ts resolve-targets.ts transform-file-browser.ts transform-file.ts generator README.md lib buffer.js generators base.js classes.js expressions.js flow.js index.js jsx.js methods.js modules.js statements.js template-literals.js types.js typescript.js index.js node index.js parentheses.js whitespace.js printer.js source-map.js node_modules @jridgewell gen-mapping README.md dist gen-mapping.umd.js types gen-mapping.d.ts sourcemap-segment.d.ts types.d.ts package.json src gen-mapping.ts sourcemap-segment.ts types.ts package.json helper-annotate-as-pure README.md lib index.js package.json helper-compilation-targets README.md lib debug.js filter-items.js index.js options.js pretty.js targets.js utils.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json helper-create-class-features-plugin README.md lib decorators.js features.js fields.js index.js misc.js typescript.js package.json helper-environment-visitor README.md lib index.js package.json helper-function-name README.md lib index.js package.json helper-hoist-variables README.md lib index.js package.json helper-member-expression-to-functions README.md lib index.js package.json helper-module-imports README.md lib import-builder.js import-injector.js index.js is-module.js package.json helper-module-transforms README.md lib dynamic-import.js get-module-name.js index.js normalize-and-load-metadata.js rewrite-live-references.js rewrite-this.js package.json helper-optimise-call-expression README.md lib index.js package.json helper-plugin-utils README.md lib index.js package.json helper-replace-supers README.md lib index.js package.json helper-simple-access README.md lib index.js package.json helper-split-export-declaration README.md lib index.js package.json helper-string-parser README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js helper-validator-option README.md lib find-suggestion.js index.js validator.js package.json helpers README.md lib helpers-generated.js helpers.js helpers AsyncGenerator.js OverloadYield.js applyDecs.js applyDecs2203.js asyncGeneratorDelegate.js asyncIterator.js awaitAsyncGenerator.js jsx.js objectSpread2.js regeneratorRuntime.js typeof.js wrapRegExp.js index.js package.json scripts generate-helpers.js generate-regenerator-runtime.js package.json highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json parser CHANGELOG.md README.md bin babel-parser.js lib index.js package.json typings babel-parser.d.ts babel-parser.source.d.ts plugin-proposal-decorators README.md lib index.js transformer-2022-03.js transformer-legacy.js package.json plugin-syntax-decorators README.md lib index.js package.json plugin-syntax-typescript README.md lib index.js package.json plugin-transform-typescript README.md lib const-enum.js enum.js index.js namespace.js package.json preset-typescript README.md lib index.js package.json template README.md lib builder.js formatters.js index.js literal.js options.js parse.js populate.js string.js package.json traverse README.md lib cache.js context.js hub.js index.js path ancestry.js comments.js context.js conversion.js evaluation.js family.js index.js inference index.js inferer-reference.js inferers.js util.js introspection.js lib hoister.js removal-hooks.js virtual-types-validator.js virtual-types.js modification.js removal.js replacement.js scope binding.js index.js lib renamer.js traverse-node.js types.js visitors.js package.json types README.md lib asserts assertNode.js generated index.js ast-types generated index.js builders flow createFlowUnionType.js createTypeAnnotationBasedOnTypeof.js generated index.js uppercase.js react buildChildren.js typescript createTSUnionType.js validateNode.js clone clone.js cloneDeep.js cloneDeepWithoutLoc.js cloneNode.js cloneWithoutLoc.js comments addComment.js addComments.js inheritInnerComments.js inheritLeadingComments.js inheritTrailingComments.js inheritsComments.js removeComments.js constants generated index.js index.js converters ensureBlock.js gatherSequenceExpressions.js toBindingIdentifierName.js toBlock.js toComputedKey.js toExpression.js toIdentifier.js toKeyAlias.js toSequenceExpression.js toStatement.js valueToNode.js definitions core.js experimental.js flow.js index.js jsx.js misc.js placeholders.js typescript.js utils.js index-legacy.d.ts index.d.ts index.js modifications appendToMemberExpression.js flow removeTypeDuplicates.js inherits.js prependToMemberExpression.js removeProperties.js removePropertiesDeep.js typescript removeTypeDuplicates.js retrievers getBindingIdentifiers.js getOuterBindingIdentifiers.js traverse traverse.js traverseFast.js utils inherit.js react cleanJSXElementLiteralChild.js shallowEqual.js validators buildMatchMemberExpression.js generated index.js is.js isBinding.js isBlockScoped.js isImmutable.js isLet.js isNode.js isNodesEquivalent.js isPlaceholderType.js isReferenced.js isScope.js isSpecifierDefault.js isType.js isValidES3Identifier.js isValidIdentifier.js isVar.js matchesPattern.js react isCompatTag.js isReactComponent.js validate.js package.json @jest environment build index.d.ts index.js package.json fake-timers build index.d.ts index.js legacyFakeTimers.d.ts legacyFakeTimers.js modernFakeTimers.d.ts modernFakeTimers.js package.json types build Circus.d.ts Circus.js Config.d.ts Config.js Global.d.ts Global.js TestResult.d.ts TestResult.js Transform.d.ts Transform.js index.d.ts index.js package.json @jridgewell gen-mapping README.md dist gen-mapping.umd.js types gen-mapping.d.ts sourcemap-segment.d.ts types.d.ts package.json resolve-uri README.md dist resolve-uri.umd.js types resolve-uri.d.ts package.json set-array README.md dist set-array.umd.js types set-array.d.ts package.json src set-array.ts sourcemap-codec README.md dist sourcemap-codec.umd.js types sourcemap-codec.d.ts package.json src sourcemap-codec.ts trace-mapping README.md dist trace-mapping.umd.js types any-map.d.ts binary-search.d.ts by-source.d.ts resolve.d.ts sort.d.ts sourcemap-segment.d.ts strip-filename.d.ts trace-mapping.d.ts types.d.ts package.json @ledgerhq devices CHANGELOG.md README.md jest.config.ts lib-es ble receiveAPDU.d.ts receiveAPDU.js sendAPDU.d.ts sendAPDU.js hid-framing.d.ts hid-framing.js index.d.ts index.js scrambling.d.ts scrambling.js lib ble receiveAPDU.d.ts receiveAPDU.js sendAPDU.d.ts sendAPDU.js hid-framing.d.ts hid-framing.js index.d.ts index.js scrambling.d.ts scrambling.js package.json src ble receiveAPDU.ts sendAPDU.ts hid-framing.ts index.ts scrambling.ts tests identifyTargetId.test.ts tsconfig.json errors CHANGELOG.md README.md jest.config.ts lib-es deserializeError.test.d.ts deserializeError.test.js helpers.d.ts helpers.js index.d.ts index.js index.test.d.ts index.test.js lib deserializeError.test.d.ts deserializeError.test.js helpers.d.ts helpers.js index.d.ts index.js index.test.d.ts index.test.js package.json src deserializeError.test.ts helpers.ts index.test.ts index.ts tsconfig.json hw-transport-node-hid-noevents CHANGELOG.md README.md jest.config.ts lib-es TransportNodeHid.d.ts TransportNodeHid.js lib TransportNodeHid.d.ts TransportNodeHid.js node_modules decompress-response index.d.ts index.js package.json readme.md detect-libc README.md bin detect-libc.js lib detect-libc.js package.json mimic-response index.d.ts index.js package.json readme.md node-abi .github workflows update-abi.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js package.json scripts update-abi-registry.js test index.js node-hid Publishing.md README.md hidapi .appveyor.yml .builds alpine.yml archlinux.yml fedora-mingw.yml freebsd.yml .cirrus.yml AUTHORS.txt HACKING.txt LICENSE-bsd.txt LICENSE-gpl3.txt LICENSE-orig.txt LICENSE.txt README.md hidapi hidapi.h hidtest test.c libusb hid.c linux hid.c mac hid.c testgui copy_to_bundle.sh mac_support.h test.cpp testgui.sln windows hid.c hidapi.sln nodehid.js package.json src buzzers.js powermate.js show-devices.js test-bigredbutton.js test-blink1.js test-buzzers.js test-ci.js test-macbookprotrackpad.js test-powermate.js test-ps3-rumbleled.js test-ps3.js test-teensyrawhid.js test-tinyusbrawhid.js testReadSync.js prebuild-install CHANGELOG.md CONTRIBUTING.md README.md asset.js bin.js download.js error.js help.txt index.js log.js package.json proxy.js rc.js util.js semver CHANGELOG.md README.md package.json semver.js simple-get README.md index.js package.json package.json src TransportNodeHid.ts tsconfig.json hw-transport-node-hid CHANGELOG.md README.md jest.config.ts lib-es TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js lib TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js package.json src TransportNodeHid.ts listenDevices.ts tsconfig.json hw-transport-u2f README.md lib-es TransportU2F.js lib TransportU2F.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportU2F.js hw-transport-webhid README.md flow webhid.js lib-es TransportWebHID.js lib TransportWebHID.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportWebHID.js hw-transport-webusb README.md flow webusb.js lib-es TransportWebUSB.js webusb.js lib TransportWebUSB.js webusb.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportWebUSB.js webusb.js hw-transport CHANGELOG.md README.md jest.config.ts lib-es Transport.d.ts Transport.js lib Transport.d.ts Transport.js package.json src Transport.ts tsconfig.json logs CHANGELOG.md README.md jest.config.ts lib-es index.d.ts index.js lib index.d.ts index.js package.json src index.ts tsconfig.json @nodelib fs.scandir README.md out adapters fs.d.ts fs.js constants.d.ts constants.js index.d.ts index.js providers async.d.ts async.js common.d.ts common.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js utils fs.d.ts fs.js index.d.ts index.js package.json fs.stat README.md out adapters fs.d.ts fs.js index.d.ts index.js providers async.d.ts async.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js package.json fs.walk README.md out index.d.ts index.js providers async.d.ts async.js index.d.ts index.js stream.d.ts stream.js sync.d.ts sync.js readers async.d.ts async.js common.d.ts common.js reader.d.ts reader.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js package.json @rollup plugin-babel CHANGELOG.md README.md dist index.es.js index.js package.json types index.d.ts plugin-commonjs CHANGELOG.md README.md dist index.es.js index.js package.json types index.d.ts plugin-node-resolve CHANGELOG.md README.md dist cjs index.js es index.js package.json package.json types index.d.ts pluginutils CHANGELOG.md README.md dist cjs index.js es index.js package.json node_modules estree-walker CHANGELOG.md README.md dist estree-walker.umd.js package.json src estree-walker.js index.ts types index.d.ts package.json types index.d.ts @scure base README.md lib esm index.js package.json index.d.ts index.js package.json @segment loosely-validate-event HISTORY.md README.md circle.yml index.js package.json test.js @sindresorhus is dist index.d.ts index.js package.json readme.md @sinonjs commons README.md lib called-in-order.js called-in-order.test.js class-name.js class-name.test.js deprecated.js deprecated.test.js every.js every.test.js function-name.js function-name.test.js global.js global.test.js index.js index.test.js order-by-first-call.js order-by-first-call.test.js prototypes README.md array.js copy-prototype-methods.js copy-prototype-methods.test.js function.js index.js index.test.js map.js object.js set.js string.js throws-on-proto.js type-of.js type-of.test.js value-to-string.js value-to-string.test.js package.json types called-in-order.d.ts class-name.d.ts deprecated.d.ts every.d.ts function-name.d.ts global.d.ts index.d.ts order-by-first-call.d.ts prototypes array.d.ts copy-prototype-methods.d.ts function.d.ts index.d.ts map.d.ts object.d.ts set.d.ts string.d.ts throws-on-proto.d.ts type-of.d.ts value-to-string.d.ts fake-timers CHANGELOG.md README.md package.json src fake-timers-src.js @szmarczak http-timer README.md package.json source index.js @ts-morph common dist ts-morph-common.js lib ts-morph-common.d.ts typescript.d.ts node_modules brace-expansion .github FUNDING.yml README.md index.js package.json minimatch README.md lib path.js minimatch.js package.json package.json readme.md @types estree README.md index.d.ts package.json istanbul-lib-coverage README.md index.d.ts package.json istanbul-lib-report README.md index.d.ts package.json istanbul-reports README.md index.d.ts package.json node README.md assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts package.json path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts ts4.8 assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts resolve README.md index.d.ts package.json stack-utils README.md index.d.ts package.json yargs-parser README.md index.d.ts package.json yargs README.md helpers.d.ts index.d.ts package.json yargs.d.ts analytics-node History.md index.js package.json readme.md ansi-align CHANGELOG.md README.md index.js package.json ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md aproba README.md index.js package.json are-we-there-yet CHANGES.md README.md index.js node_modules readable-stream .travis.yml CONTRIBUTING.md GOVERNANCE.md README.md doc wg-meetings 2015-01-30.md duplex-browser.js duplex.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams BufferList.js destroy.js stream-browser.js stream.js package.json passthrough.js readable-browser.js readable.js transform.js writable-browser.js writable.js safe-buffer README.md index.d.ts index.js package.json string_decoder .travis.yml README.md lib string_decoder.js package.json package.json tracker-base.js tracker-group.js tracker-stream.js tracker.js ascii-table .travis.yml ascii-table.js ascii-table.min.js bower.json example simple.js simple.txt index.js package.json readme.md test.js asynckit README.md bench.js index.js lib abort.js async.js defer.js iterate.js readable_asynckit.js readable_parallel.js readable_serial.js readable_serial_ordered.js state.js streamify.js terminator.js package.json parallel.js serial.js serialOrdered.js stream.js atob README.md bin atob.js bower.json browser-atob.js node-atob.js package.json test.js axios-retry CHANGELOG.md README.md es index.js index.d.ts index.js lib index.js package.json axios CHANGELOG.md README.md SECURITY.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel CancelToken.js CanceledError.js isCancel.js core Axios.js AxiosError.js InterceptorManager.js README.md buildFullPath.js dispatchRequest.js mergeConfig.js settle.js transformData.js defaults env FormData.js index.js transitional.js env README.md data.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isAxiosError.js isURLSameOrigin.js normalizeHeaderName.js null.js parseHeaders.js parseProtocol.js spread.js toFormData.js validator.js utils.js package.json tsconfig.json tslint.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js base64-js README.md base64js.min.js index.d.ts index.js package.json bindings LICENSE.md README.md bindings.js package.json bip39-light .travis.yml README.md index.js package.json test index.js readme.js vectors.json wordlist.json wordlists english.json bip39 CHANGELOG.md README.md node_modules @types node README.md assert.d.ts async_hooks.d.ts base.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts dns.d.ts domain.d.ts events.d.ts fs.d.ts globals.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts package.json path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts repl.d.ts stream.d.ts string_decoder.d.ts timers.d.ts tls.d.ts trace_events.d.ts ts3.2 globals.d.ts index.d.ts util.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts worker_threads.d.ts zlib.d.ts package.json src _wordlists.js index.js wordlists chinese_simplified.json chinese_traditional.json english.json french.json italian.json japanese.json korean.json spanish.json types _wordlists.d.ts index.d.ts wordlists.d.ts bl .travis.yml BufferList.js LICENSE.md README.md bl.js package.json test convert.js indexOf.js isBufferList.js test.js bn.js README.md lib bn.js package.json borsh .eslintrc.yml .travis.yml LICENSE-MIT.txt README.md borsh-ts .eslintrc.yml index.ts test .eslintrc.yml fuzz borsh-roundtrip.js transaction-example enums.d.ts enums.js key_pair.d.ts key_pair.js serialize.d.ts serialize.js signer.d.ts signer.js transaction.d.ts transaction.js serialize.test.js lib index.d.ts index.js package.json tsconfig.json boxen index.d.ts index.js package.json readme.md brace-expansion README.md index.js package.json braces CHANGELOG.md README.md index.js lib compile.js constants.js expand.js parse.js stringify.js utils.js package.json browserslist README.md browser.js cli.js error.d.ts error.js index.d.ts index.js node.js package.json parse.js bs58 CHANGELOG.md README.md index.js package.json buffer AUTHORS.md README.md index.d.ts index.js package.json builtin-modules builtin-modules.json index.d.ts index.js package.json readme.md static.d.ts static.js cacheable-request README.md node_modules get-stream buffer-stream.js index.d.ts index.js package.json readme.md lowercase-keys index.d.ts index.js package.json readme.md package.json src index.js camelcase index.d.ts index.js package.json readme.md caniuse-lite README.md data agents.js browserVersions.js browsers.js features.js features aac.js abortcontroller.js ac3-ec3.js accelerometer.js addeventlistener.js alternate-stylesheet.js ambient-light.js apng.js array-find-index.js array-find.js array-flat.js array-includes.js arrow-functions.js asmjs.js async-clipboard.js async-functions.js atob-btoa.js audio-api.js audio.js audiotracks.js autofocus.js auxclick.js av1.js avif.js background-attachment.js background-clip-text.js background-img-opts.js background-position-x-y.js background-repeat-round-space.js background-sync.js battery-status.js beacon.js beforeafterprint.js bigint.js blobbuilder.js bloburls.js border-image.js border-radius.js broadcastchannel.js brotli.js calc.js canvas-blending.js canvas-text.js canvas.js ch-unit.js chacha20-poly1305.js channel-messaging.js childnode-remove.js classlist.js client-hints-dpr-width-viewport.js clipboard.js colr-v1.js colr.js comparedocumentposition.js console-basic.js console-time.js const.js constraint-validation.js contenteditable.js contentsecuritypolicy.js contentsecuritypolicy2.js cookie-store-api.js cors.js createimagebitmap.js credential-management.js cryptography.js css-all.js css-animation.js css-any-link.js css-appearance.js css-at-counter-style.js css-autofill.js css-backdrop-filter.js css-background-offsets.js css-backgroundblendmode.js css-boxdecorationbreak.js css-boxshadow.js css-canvas.js css-caret-color.js css-cascade-layers.js css-case-insensitive.js css-clip-path.js css-color-adjust.js css-color-function.js css-conic-gradients.js css-container-queries.js css-container-query-units.js css-containment.js css-content-visibility.js css-counters.js css-crisp-edges.js css-cross-fade.js css-default-pseudo.js css-descendant-gtgt.js css-deviceadaptation.js css-dir-pseudo.js css-display-contents.js css-element-function.js css-env-function.js css-exclusions.js css-featurequeries.js css-file-selector-button.js css-filter-function.js css-filters.js css-first-letter.js css-first-line.js css-fixed.js css-focus-visible.js css-focus-within.js css-font-palette.js css-font-rendering-controls.js css-font-stretch.js css-gencontent.js css-gradients.js css-grid-animation.js css-grid.js css-hanging-punctuation.js css-has.js css-hyphens.js css-image-orientation.js css-image-set.js css-in-out-of-range.js css-indeterminate-pseudo.js css-initial-letter.js css-initial-value.js css-lch-lab.js css-letter-spacing.js css-line-clamp.js css-logical-props.js css-marker-pseudo.js css-masks.js css-matches-pseudo.js css-math-functions.js css-media-interaction.js css-media-range-syntax.js css-media-resolution.js css-media-scripting.js css-mediaqueries.js css-mixblendmode.js css-motion-paths.js css-namespaces.js css-nesting.js css-not-sel-list.js css-nth-child-of.js css-opacity.js css-optional-pseudo.js css-overflow-anchor.js css-overflow-overlay.js css-overflow.js css-overscroll-behavior.js css-page-break.js css-paged-media.js css-paint-api.js css-placeholder-shown.js css-placeholder.js css-print-color-adjust.js css-read-only-write.js css-rebeccapurple.js css-reflections.js css-regions.js css-repeating-gradients.js css-resize.js css-revert-value.js css-rrggbbaa.js css-scroll-behavior.js css-scroll-timeline.js css-scrollbar.js css-sel2.js css-sel3.js css-selection.js css-shapes.js css-snappoints.js css-sticky.js css-subgrid.js css-supports-api.js css-table.js css-text-align-last.js css-text-indent.js css-text-justify.js css-text-orientation.js css-text-spacing.js css-textshadow.js css-touch-action.js css-transitions.js css-unicode-bidi.js css-unset-value.js css-variables.js css-when-else.js css-widows-orphans.js css-width-stretch.js css-writing-mode.js css-zoom.js css3-attr.js css3-boxsizing.js css3-colors.js css3-cursors-grab.js css3-cursors-newer.js css3-cursors.js css3-tabsize.js currentcolor.js custom-elements.js custom-elementsv1.js customevent.js datalist.js dataset.js datauri.js date-tolocaledatestring.js declarative-shadow-dom.js decorators.js details.js deviceorientation.js devicepixelratio.js dialog.js dispatchevent.js dnssec.js do-not-track.js document-currentscript.js document-evaluate-xpath.js document-execcommand.js document-policy.js document-scrollingelement.js documenthead.js dom-manip-convenience.js dom-range.js domcontentloaded.js dommatrix.js download.js dragndrop.js element-closest.js element-from-point.js element-scroll-methods.js eme.js eot.js es5.js es6-class.js es6-generators.js es6-module-dynamic-import.js es6-module.js es6-number.js es6-string-includes.js es6.js eventsource.js extended-system-fonts.js feature-policy.js fetch.js fieldset-disabled.js fileapi.js filereader.js filereadersync.js filesystem.js flac.js flexbox-gap.js flexbox.js flow-root.js focusin-focusout-events.js font-family-system-ui.js font-feature.js font-kerning.js font-loading.js font-size-adjust.js font-smooth.js font-unicode-range.js font-variant-alternates.js font-variant-numeric.js fontface.js form-attribute.js form-submit-attributes.js form-validation.js forms.js fullscreen.js gamepad.js geolocation.js getboundingclientrect.js getcomputedstyle.js getelementsbyclassname.js getrandomvalues.js gyroscope.js hardwareconcurrency.js hashchange.js heif.js hevc.js hidden.js high-resolution-time.js history.js html-media-capture.js html5semantic.js http-live-streaming.js http2.js http3.js iframe-sandbox.js iframe-seamless.js iframe-srcdoc.js imagecapture.js ime.js img-naturalwidth-naturalheight.js import-maps.js imports.js indeterminate-checkbox.js indexeddb.js indexeddb2.js inline-block.js innertext.js input-autocomplete-onoff.js input-color.js input-datetime.js input-email-tel-url.js input-event.js input-file-accept.js input-file-directory.js input-file-multiple.js input-inputmode.js input-minlength.js input-number.js input-pattern.js input-placeholder.js input-range.js input-search.js input-selection.js insert-adjacent.js insertadjacenthtml.js internationalization.js intersectionobserver-v2.js intersectionobserver.js intl-pluralrules.js intrinsic-width.js jpeg2000.js jpegxl.js jpegxr.js js-regexp-lookbehind.js json.js justify-content-space-evenly.js kerning-pairs-ligatures.js keyboardevent-charcode.js keyboardevent-code.js keyboardevent-getmodifierstate.js keyboardevent-key.js keyboardevent-location.js keyboardevent-which.js lazyload.js let.js link-icon-png.js link-icon-svg.js link-rel-dns-prefetch.js link-rel-modulepreload.js link-rel-preconnect.js link-rel-prefetch.js link-rel-preload.js link-rel-prerender.js loading-lazy-attr.js localecompare.js magnetometer.js matchesselector.js matchmedia.js mathml.js maxlength.js mdn-css-unicode-bidi-isolate-override.js mdn-css-unicode-bidi-isolate.js mdn-css-unicode-bidi-plaintext.js mdn-text-decoration-color.js mdn-text-decoration-line.js mdn-text-decoration-shorthand.js mdn-text-decoration-style.js media-fragments.js mediacapture-fromelement.js mediarecorder.js mediasource.js menu.js meta-theme-color.js meter.js midi.js minmaxwh.js mp3.js mpeg-dash.js mpeg4.js multibackgrounds.js multicolumn.js mutation-events.js mutationobserver.js namevalue-storage.js native-filesystem-api.js nav-timing.js netinfo.js notifications.js object-entries.js object-fit.js object-observe.js object-values.js objectrtc.js offline-apps.js offscreencanvas.js ogg-vorbis.js ogv.js ol-reversed.js once-event-listener.js online-status.js opus.js orientation-sensor.js outline.js pad-start-end.js page-transition-events.js pagevisibility.js passive-event-listener.js passwordrules.js path2d.js payment-request.js pdf-viewer.js permissions-api.js permissions-policy.js picture-in-picture.js picture.js ping.js png-alpha.js pointer-events.js pointer.js pointerlock.js portals.js prefers-color-scheme.js prefers-reduced-motion.js progress.js promise-finally.js promises.js proximity.js proxy.js publickeypinning.js push-api.js queryselector.js readonly-attr.js referrer-policy.js registerprotocolhandler.js rel-noopener.js rel-noreferrer.js rellist.js rem.js requestanimationframe.js requestidlecallback.js resizeobserver.js resource-timing.js rest-parameters.js rtcpeerconnection.js ruby.js run-in.js same-site-cookie-attribute.js screen-orientation.js script-async.js script-defer.js scrollintoview.js scrollintoviewifneeded.js sdch.js selection-api.js server-timing.js serviceworkers.js setimmediate.js shadowdom.js shadowdomv1.js sharedarraybuffer.js sharedworkers.js sni.js spdy.js speech-recognition.js speech-synthesis.js spellcheck-attribute.js sql-storage.js srcset.js stream.js streams.js stricttransportsecurity.js style-scoped.js subresource-bundling.js subresource-integrity.js svg-css.js svg-filters.js svg-fonts.js svg-fragment.js svg-html.js svg-html5.js svg-img.js svg-smil.js svg.js sxg.js tabindex-attr.js template-literals.js template.js temporal.js testfeat.js text-decoration.js text-emphasis.js text-overflow.js text-size-adjust.js text-stroke.js textcontent.js textencoder.js tls1-1.js tls1-2.js tls1-3.js touch.js transforms2d.js transforms3d.js trusted-types.js ttf.js typedarrays.js u2f.js unhandledrejection.js upgradeinsecurerequests.js url-scroll-to-text-fragment.js url.js urlsearchparams.js use-strict.js user-select-none.js user-timing.js variable-fonts.js vector-effect.js vibration.js video.js videotracks.js viewport-unit-variants.js viewport-units.js wai-aria.js wake-lock.js wasm.js wav.js wbr-element.js web-animation.js web-app-manifest.js web-bluetooth.js web-serial.js web-share.js webauthn.js webcodecs.js webgl.js webgl2.js webgpu.js webhid.js webkit-user-drag.js webm.js webnfc.js webp.js websockets.js webtransport.js webusb.js webvr.js webvtt.js webworkers.js webxr.js will-change.js woff.js woff2.js word-break.js wordwrap.js x-doc-messaging.js x-frame-options.js xhr2.js xhtml.js xhtmlsmil.js xml-serializer.js regions AD.js AE.js AF.js AG.js AI.js AL.js AM.js AO.js AR.js AS.js AT.js AU.js AW.js AX.js AZ.js BA.js BB.js BD.js BE.js BF.js BG.js BH.js BI.js BJ.js BM.js BN.js BO.js BR.js BS.js BT.js BW.js BY.js BZ.js CA.js CD.js CF.js CG.js CH.js CI.js CK.js CL.js CM.js CN.js CO.js CR.js CU.js CV.js CX.js CY.js CZ.js DE.js DJ.js DK.js DM.js DO.js DZ.js EC.js EE.js EG.js ER.js ES.js ET.js FI.js FJ.js FK.js FM.js FO.js FR.js GA.js GB.js GD.js GE.js GF.js GG.js GH.js GI.js GL.js GM.js GN.js GP.js GQ.js GR.js GT.js GU.js GW.js GY.js HK.js HN.js HR.js HT.js HU.js ID.js IE.js IL.js IM.js IN.js IQ.js IR.js IS.js IT.js JE.js JM.js JO.js JP.js KE.js KG.js KH.js KI.js KM.js KN.js KP.js KR.js KW.js KY.js KZ.js LA.js LB.js LC.js LI.js LK.js LR.js LS.js LT.js LU.js LV.js LY.js MA.js MC.js MD.js ME.js MG.js MH.js MK.js ML.js MM.js MN.js MO.js MP.js MQ.js MR.js MS.js MT.js MU.js MV.js MW.js MX.js MY.js MZ.js NA.js NC.js NE.js NF.js NG.js NI.js NL.js NO.js NP.js NR.js NU.js NZ.js OM.js PA.js PE.js PF.js PG.js PH.js PK.js PL.js PM.js PN.js PR.js PS.js PT.js PW.js PY.js QA.js RE.js RO.js RS.js RU.js RW.js SA.js SB.js SC.js SD.js SE.js SG.js SH.js SI.js SK.js SL.js SM.js SN.js SO.js SR.js ST.js SV.js SY.js SZ.js TC.js TD.js TG.js TH.js TJ.js TK.js TL.js TM.js TN.js TO.js TR.js TT.js TV.js TW.js TZ.js UA.js UG.js US.js UY.js UZ.js VA.js VC.js VE.js VG.js VI.js VN.js VU.js WF.js WS.js YE.js YT.js ZA.js ZM.js ZW.js alt-af.js alt-an.js alt-as.js alt-eu.js alt-na.js alt-oc.js alt-sa.js alt-ww.js dist lib statuses.js supported.js unpacker agents.js browserVersions.js browsers.js feature.js features.js index.js region.js package.json capability Array.prototype.forEach.js Array.prototype.map.js Error.captureStackTrace.js Error.prototype.stack.js Function.prototype.bind.js Object.create.js Object.defineProperties.js Object.defineProperty.js Object.prototype.hasOwnProperty.js README.md arguments.callee.caller.js es5.js index.js lib CapabilityDetector.js definitions.js index.js package.json strict mode.js chalk index.d.ts package.json readme.md source index.js templates.js util.js charenc README.js charenc.js package.json chownr README.md chownr.js package.json ci-info CHANGELOG.md README.md index.js package.json vendors.json cipher-base .travis.yml README.md index.js package.json test.js cli-boxes boxes.json index.d.ts index.js package.json readme.md cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json clone-response README.md node_modules mimic-response index.js package.json readme.md package.json src index.js code-block-writer README.md package.json script mod.js package.json utils string_utils.js types mod.d.ts utils string_utils.d.ts code-point-at index.js package.json readme.md color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json combined-stream Readme.md lib combined_stream.js package.json commander Readme.md index.js lib argument.js command.js error.js help.js option.js suggestSimilar.js package-support.json package.json typings index.d.ts commondir example dir.js index.js package.json test dirs.js component-type Readme.md component.json index.js package.json test index.html mocha.css mocha.js tests.js concat-map .travis.yml example map.js index.js package.json test map.js configstore index.js package.json readme.md console-control-strings README.md index.js package.json convert-source-map README.md index.js package.json core-util-is README.md lib util.js package.json create-hash .travis.yml README.md browser.js index.js md5.js package.json test.js create-hmac README.md browser.js index.js legacy.js package.json crypt crypt.js package.json crypto-random-string index.d.ts index.js package.json readme.md debug README.md node_modules ms index.js license.md package.json readme.md package.json src browser.js common.js index.js node.js decode-uri-component index.js package.json readme.md decompress-response index.d.ts index.js package.json readme.md deep-extend CHANGELOG.md README.md index.js lib deep-extend.js package.json deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js deepmerge changelog.md dist cjs.js umd.js index.d.ts index.js license.txt package.json readme.md rollup.config.js defer-to-connect README.md dist index.d.ts index.js package.json define-lazy-prop index.d.ts index.js package.json readme.md delayed-stream Readme.md lib delayed_stream.js package.json delegates History.md Readme.md index.js package.json test index.js depd History.md Readme.md index.js lib browser index.js package.json detect-libc README.md index.d.ts lib detect-libc.js process.js package.json dot-prop index.d.ts index.js package.json readme.md duplexer3 index.js package.json readme.md electron-to-chromium CHANGELOG.md README.md chromium-versions.js chromium-versions.json full-chromium-versions.js full-chromium-versions.json full-versions.js full-versions.json index.js package.json versions.js versions.json emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js end-of-stream README.md index.js package.json error-ex README.md index.js package.json error-polyfill README.md index.js lib index.js non-v8 Frame.js FrameStringParser.js FrameStringSource.js index.js prepareStackTrace.js unsupported.js v8.js package.json escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-goat index.d.ts index.js package.json readme.md escape-string-regexp index.js package.json readme.md estree-walker CHANGELOG.md README.md dist esm estree-walker.js package.json umd estree-walker.js package.json src async.js index.js package.json sync.js walker.js types async.d.ts index.d.ts sync.d.ts walker.d.ts events .airtap.yml .github FUNDING.yml .travis.yml History.md Readme.md events.js package.json security.md tests add-listeners.js check-listener-leaks.js common.js errors.js events-list.js events-once.js index.js legacy-compat.js listener-count.js listeners-side-effects.js listeners.js max-listeners.js method-names.js modify-in-emit.js num-args.js once.js prepend.js remove-all-listeners.js remove-listeners.js set-max-listeners-side-effects.js special-event-names.js subclass.js symbols.js expand-template .travis.yml README.md index.js package.json test.js fast-glob README.md out index.d.ts index.js managers patterns.d.ts patterns.js tasks.d.ts tasks.js providers async.d.ts async.js filters deep.d.ts deep.js entry.d.ts entry.js error.d.ts error.js matchers matcher.d.ts matcher.js partial.d.ts partial.js provider.d.ts provider.js stream.d.ts stream.js sync.d.ts sync.js transformers entry.d.ts entry.js readers async.d.ts async.js reader.d.ts reader.js stream.d.ts stream.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js utils array.d.ts array.js errno.d.ts errno.js fs.d.ts fs.js index.d.ts index.js path.d.ts path.js pattern.d.ts pattern.js stream.d.ts stream.js string.d.ts string.js package.json fastq .github dependabot.yml workflows ci.yml README.md bench.js example.js index.d.ts package.json queue.js test example.ts promise.js test.js tsconfig.json figures index.js package.json readme.md file-uri-to-path .travis.yml History.md README.md index.d.ts index.js package.json test test.js tests.json fill-range README.md index.js package.json find-up index.js package.json readme.md flagged-respawn README.md index.js lib is-v8flags.js remover.js reorder.js respawn.js package.json follow-redirects README.md debug.js http.js https.js index.js package.json form-data Readme.md index.d.ts lib browser.js form_data.js populate.js package.json fs-constants README.md browser.js index.js package.json fs.realpath README.md index.js old.js package.json fsevents README.md fsevents.d.ts fsevents.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js gauge CHANGELOG.md README.md base-theme.js error.js has-color.js index.js node_modules ansi-regex index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.js package.json readme.md package.json plumbing.js process.js progress-bar.js render-template.js set-immediate.js set-interval.js spin.js template-item.js theme-set.js themes.js wide-truncate.js gensync README.md index.js package.json test index.test.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json get-stream buffer-stream.js index.js package.json readme.md github-from-package .travis.yml example package.json url.js index.js package.json test a.json b.json c.json d.json e.json url.js glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js global-dirs index.d.ts index.js node_modules ini README.md ini.js package.json package.json readme.md globals globals.json index.js package.json readme.md got node_modules decompress-response index.js package.json readme.md mimic-response index.js package.json readme.md package.json readme.md source as-promise.js as-stream.js create.js errors.js get-response.js index.js known-hook-events.js merge.js normalize-arguments.js progress.js request-as-event-emitter.js utils deep-freeze.js get-body-size.js is-form-data.js timed-out.js url-to-options.js graceful-fs README.md clone.js graceful-fs.js legacy-streams.js package.json polyfills.js has-flag index.d.ts index.js package.json readme.md has-unicode README.md index.js package.json has-yarn index.d.ts index.js package.json readme.md has README.md package.json src index.js test index.js hash-base README.md index.js package.json homedir-polyfill README.md index.js package.json polyfill.js http-cache-semantics README.md index.js package.json http-errors HISTORY.md README.md index.js node_modules depd History.md Readme.md index.js lib browser index.js compat callsite-tostring.js event-listener-count.js index.js package.json package.json ieee754 README.md index.d.ts index.js package.json import-lazy index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json ini README.md ini.js package.json ip-regex index.d.ts index.js package.json readme.md is-arrayish .istanbul.yml .travis.yml README.md index.js package.json is-buffer README.md index.js package.json test basic.js is-builtin-module index.d.ts index.js package.json readme.md is-ci CHANGELOG.md README.md bin.js index.js package.json is-core-module CHANGELOG.md README.md core.json index.js package.json test index.js is-docker cli.js index.d.ts index.js package.json readme.md is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json is-installed-globally index.d.ts index.js package.json readme.md is-module README.md component.json index.js package.json is-npm index.d.ts index.js package.json readme.md is-number README.md index.js package.json is-obj index.d.ts index.js package.json readme.md is-path-inside index.d.ts index.js package.json readme.md is-reference CHANGELOG.md README.md dist is-reference.es.js is-reference.js types index.d.ts package.json is-retry-allowed index.js package.json readme.md is-typedarray LICENSE.md README.md index.js package.json test.js is-url .travis.yml History.md Readme.md index.js package.json test index.js is-wsl index.d.ts index.js package.json readme.md is-yarn-global .travis.yml README.md index.js package.json is2 README.md index.d.ts index.js package.json tests.js isarray .travis.yml README.md component.json index.js package.json test.js jest-environment-node build index.d.ts index.js package.json jest-message-util build index.d.ts index.js types.d.ts types.js package.json jest-mock README.md build index.d.ts index.js package.json jest-util build ErrorWithStack.d.ts ErrorWithStack.js clearLine.d.ts clearLine.js convertDescriptorToString.d.ts convertDescriptorToString.js createDirectory.d.ts createDirectory.js createProcessObject.d.ts createProcessObject.js deepCyclicCopy.d.ts deepCyclicCopy.js formatTime.d.ts formatTime.js globsToMatcher.d.ts globsToMatcher.js index.d.ts index.js installCommonGlobals.d.ts installCommonGlobals.js interopRequireDefault.d.ts interopRequireDefault.js isInteractive.d.ts isInteractive.js isPromise.d.ts isPromise.js pluralize.d.ts pluralize.js preRunMessage.d.ts preRunMessage.js replacePathSepForGlob.d.ts replacePathSepForGlob.js requireOrImportModule.d.ts requireOrImportModule.js setGlobal.d.ts setGlobal.js specialChars.d.ts specialChars.js testPathPatternToRegExp.d.ts testPathPatternToRegExp.js tryRealpath.d.ts tryRealpath.js node_modules ci-info CHANGELOG.md README.md index.d.ts index.js package.json vendors.json package.json join-component History.md Readme.md component.json index.js package.json test index.js js-sha256 CHANGELOG.md LICENSE.txt README.md build sha256.min.js index.d.ts package.json src sha256.js js-tokens CHANGELOG.md README.md index.js package.json jsesc LICENSE-MIT.txt README.md jsesc.js package.json json-buffer .travis.yml README.md index.js package.json test index.js json-parse-better-errors CHANGELOG.md LICENSE.md README.md index.js package.json json5 LICENSE.md README.md dist index.js index.min.js lib cli.js index.d.ts index.js parse.d.ts parse.js register.js require.js stringify.d.ts stringify.js unicode.d.ts unicode.js util.d.ts util.js package.json keyv README.md package.json src index.js latest-version index.d.ts index.js package.json readme.md load-json-file index.js package.json readme.md locate-path index.js package.json readme.md lodash.isstring README.md index.js package.json lodash README.md _DataView.js _Hash.js _LazyWrapper.js _ListCache.js _LodashWrapper.js _Map.js _MapCache.js _Promise.js _Set.js _SetCache.js _Stack.js _Symbol.js _Uint8Array.js _WeakMap.js _apply.js _arrayAggregator.js _arrayEach.js _arrayEachRight.js _arrayEvery.js _arrayFilter.js _arrayIncludes.js _arrayIncludesWith.js _arrayLikeKeys.js _arrayMap.js _arrayPush.js _arrayReduce.js _arrayReduceRight.js _arraySample.js _arraySampleSize.js _arrayShuffle.js _arraySome.js _asciiSize.js _asciiToArray.js _asciiWords.js _assignMergeValue.js _assignValue.js _assocIndexOf.js _baseAggregator.js _baseAssign.js _baseAssignIn.js _baseAssignValue.js _baseAt.js _baseClamp.js _baseClone.js _baseConforms.js _baseConformsTo.js _baseCreate.js _baseDelay.js _baseDifference.js _baseEach.js _baseEachRight.js _baseEvery.js _baseExtremum.js _baseFill.js _baseFilter.js _baseFindIndex.js _baseFindKey.js _baseFlatten.js _baseFor.js _baseForOwn.js _baseForOwnRight.js _baseForRight.js _baseFunctions.js _baseGet.js _baseGetAllKeys.js _baseGetTag.js _baseGt.js _baseHas.js _baseHasIn.js _baseInRange.js _baseIndexOf.js _baseIndexOfWith.js _baseIntersection.js _baseInverter.js _baseInvoke.js _baseIsArguments.js _baseIsArrayBuffer.js _baseIsDate.js _baseIsEqual.js _baseIsEqualDeep.js _baseIsMap.js _baseIsMatch.js _baseIsNaN.js _baseIsNative.js _baseIsRegExp.js _baseIsSet.js _baseIsTypedArray.js _baseIteratee.js _baseKeys.js _baseKeysIn.js _baseLodash.js _baseLt.js _baseMap.js _baseMatches.js _baseMatchesProperty.js _baseMean.js _baseMerge.js _baseMergeDeep.js _baseNth.js _baseOrderBy.js _basePick.js _basePickBy.js _baseProperty.js _basePropertyDeep.js _basePropertyOf.js _basePullAll.js _basePullAt.js _baseRandom.js _baseRange.js _baseReduce.js _baseRepeat.js _baseRest.js _baseSample.js _baseSampleSize.js _baseSet.js _baseSetData.js _baseSetToString.js _baseShuffle.js _baseSlice.js _baseSome.js _baseSortBy.js _baseSortedIndex.js _baseSortedIndexBy.js _baseSortedUniq.js _baseSum.js _baseTimes.js _baseToNumber.js _baseToPairs.js _baseToString.js _baseTrim.js _baseUnary.js _baseUniq.js _baseUnset.js _baseUpdate.js _baseValues.js _baseWhile.js _baseWrapperValue.js _baseXor.js _baseZipObject.js _cacheHas.js _castArrayLikeObject.js _castFunction.js _castPath.js _castRest.js _castSlice.js _charsEndIndex.js _charsStartIndex.js _cloneArrayBuffer.js _cloneBuffer.js _cloneDataView.js _cloneRegExp.js _cloneSymbol.js _cloneTypedArray.js _compareAscending.js _compareMultiple.js _composeArgs.js _composeArgsRight.js _copyArray.js _copyObject.js _copySymbols.js _copySymbolsIn.js _coreJsData.js _countHolders.js _createAggregator.js _createAssigner.js _createBaseEach.js _createBaseFor.js _createBind.js _createCaseFirst.js _createCompounder.js _createCtor.js _createCurry.js _createFind.js _createFlow.js _createHybrid.js _createInverter.js _createMathOperation.js _createOver.js _createPadding.js _createPartial.js _createRange.js _createRecurry.js _createRelationalOperation.js _createRound.js _createSet.js _createToPairs.js _createWrap.js _customDefaultsAssignIn.js _customDefaultsMerge.js _customOmitClone.js _deburrLetter.js _defineProperty.js _equalArrays.js _equalByTag.js _equalObjects.js _escapeHtmlChar.js _escapeStringChar.js _flatRest.js _freeGlobal.js _getAllKeys.js _getAllKeysIn.js _getData.js _getFuncName.js _getHolder.js _getMapData.js _getMatchData.js _getNative.js _getPrototype.js _getRawTag.js _getSymbols.js _getSymbolsIn.js _getTag.js _getValue.js _getView.js _getWrapDetails.js _hasPath.js _hasUnicode.js _hasUnicodeWord.js _hashClear.js _hashDelete.js _hashGet.js _hashHas.js _hashSet.js _initCloneArray.js _initCloneByTag.js _initCloneObject.js _insertWrapDetails.js _isFlattenable.js _isIndex.js _isIterateeCall.js _isKey.js _isKeyable.js _isLaziable.js _isMaskable.js _isMasked.js _isPrototype.js _isStrictComparable.js _iteratorToArray.js _lazyClone.js _lazyReverse.js _lazyValue.js _listCacheClear.js _listCacheDelete.js _listCacheGet.js _listCacheHas.js _listCacheSet.js _mapCacheClear.js _mapCacheDelete.js _mapCacheGet.js _mapCacheHas.js _mapCacheSet.js _mapToArray.js _matchesStrictComparable.js _memoizeCapped.js _mergeData.js _metaMap.js _nativeCreate.js _nativeKeys.js _nativeKeysIn.js _nodeUtil.js _objectToString.js _overArg.js _overRest.js _parent.js _reEscape.js _reEvaluate.js _reInterpolate.js _realNames.js _reorder.js _replaceHolders.js _root.js _safeGet.js _setCacheAdd.js _setCacheHas.js _setData.js _setToArray.js _setToPairs.js _setToString.js _setWrapToString.js _shortOut.js _shuffleSelf.js _stackClear.js _stackDelete.js _stackGet.js _stackHas.js _stackSet.js _strictIndexOf.js _strictLastIndexOf.js _stringSize.js _stringToArray.js _stringToPath.js _toKey.js _toSource.js _trimmedEndIndex.js _unescapeHtmlChar.js _unicodeSize.js _unicodeToArray.js _unicodeWords.js _updateWrapDetails.js _wrapperClone.js add.js after.js array.js ary.js assign.js assignIn.js assignInWith.js assignWith.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js concat.js cond.js conforms.js conformsTo.js constant.js core.js core.min.js countBy.js create.js curry.js curryRight.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsDeep.js defer.js delay.js difference.js differenceBy.js differenceWith.js divide.js drop.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js escape.js escapeRegExp.js every.js extend.js extendWith.js fill.js filter.js find.js findIndex.js findKey.js findLast.js findLastIndex.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fp.js fp F.js T.js __.js _baseConvert.js _convertBrowser.js _falseOptions.js _mapping.js _util.js add.js after.js all.js allPass.js always.js any.js anyPass.js apply.js array.js ary.js assign.js assignAll.js assignAllWith.js assignIn.js assignInAll.js assignInAllWith.js assignInWith.js assignWith.js assoc.js assocPath.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js complement.js compose.js concat.js cond.js conforms.js conformsTo.js constant.js contains.js convert.js countBy.js create.js curry.js curryN.js curryRight.js curryRightN.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsAll.js defaultsDeep.js defaultsDeepAll.js defer.js delay.js difference.js differenceBy.js differenceWith.js dissoc.js dissocPath.js divide.js drop.js dropLast.js dropLastWhile.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js equals.js escape.js escapeRegExp.js every.js extend.js extendAll.js extendAllWith.js extendWith.js fill.js filter.js find.js findFrom.js findIndex.js findIndexFrom.js findKey.js findLast.js findLastFrom.js findLastIndex.js findLastIndexFrom.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fromPairs.js function.js functions.js functionsIn.js get.js getOr.js groupBy.js gt.js gte.js has.js hasIn.js head.js identical.js identity.js inRange.js includes.js includesFrom.js indexBy.js indexOf.js indexOfFrom.js init.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invertObj.js invoke.js invokeArgs.js invokeArgsMap.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js juxt.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lastIndexOfFrom.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeAll.js mergeAllWith.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js nAry.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitAll.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js pad.js padChars.js padCharsEnd.js padCharsStart.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js path.js pathEq.js pathOr.js paths.js pick.js pickAll.js pickBy.js pipe.js placeholder.js plant.js pluck.js prop.js propEq.js propOr.js property.js propertyOf.js props.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rangeStep.js rangeStepRight.js rearg.js reduce.js reduceRight.js reject.js remove.js repeat.js replace.js rest.js restFrom.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js spreadFrom.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js symmetricDifference.js symmetricDifferenceBy.js symmetricDifferenceWith.js tail.js take.js takeLast.js takeLastWhile.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimChars.js trimCharsEnd.js trimCharsStart.js trimEnd.js trimStart.js truncate.js unapply.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unnest.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js useWith.js util.js value.js valueOf.js values.js valuesIn.js where.js whereEq.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipAll.js zipObj.js zipObject.js zipObjectDeep.js zipWith.js fromPairs.js function.js functions.js functionsIn.js get.js groupBy.js gt.js gte.js has.js hasIn.js head.js identity.js inRange.js includes.js index.js indexOf.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invoke.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lodash.js lodash.min.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js package.json pad.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js pick.js pickBy.js plant.js property.js propertyOf.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rearg.js reduce.js reduceRight.js reject.js release.md remove.js repeat.js replace.js rest.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js tail.js take.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimEnd.js trimStart.js truncate.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js util.js value.js valueOf.js values.js valuesIn.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipObject.js zipObjectDeep.js zipWith.js lowercase-keys index.js package.json readme.md lru-cache README.md index.js package.json magic-string README.md dist magic-string.cjs.js magic-string.es.js magic-string.umd.js index.d.ts package.json make-dir index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md md5.js README.md index.js package.json md5 .travis.yml README.md demo index.html dist md5.min.js md5.js package.json test.js webpack.config.js merge2 README.md index.js package.json micromatch README.md index.js package.json mime-db HISTORY.md README.md db.json index.js package.json mime-types HISTORY.md README.md index.js package.json mimic-response index.d.ts index.js package.json readme.md minimatch README.md minimatch.js package.json minimist .github FUNDING.yml CHANGELOG.md README.md example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js mkdirp-classic README.md index.js package.json mkdirp CHANGELOG.md bin cmd.js index.js lib find-made.js mkdirp-manual.js mkdirp-native.js opts-arg.js path-arg.js use-native.js package.json ms index.js license.md package.json readme.md mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json napi-build-utils README.md index.js index.md package.json ncp .travis.yml LICENSE.md README.md lib ncp.js package.json test ncp.js near-api-js README.md browser-exports.js dist near-api-js.js near-api-js.min.js lib account.d.ts account.js account_creator.d.ts account_creator.js account_multisig.d.ts account_multisig.js browser-connect.d.ts browser-connect.js browser-index.d.ts browser-index.js common-index.d.ts common-index.js connect.d.ts connect.js connection.d.ts connection.js constants.d.ts constants.js contract.d.ts contract.js generated rpc_error_schema.json index.d.ts index.js key_stores browser-index.d.ts browser-index.js browser_local_storage_key_store.d.ts browser_local_storage_key_store.js in_memory_key_store.d.ts in_memory_key_store.js index.d.ts index.js keystore.d.ts keystore.js merge_key_store.d.ts merge_key_store.js unencrypted_file_system_keystore.d.ts unencrypted_file_system_keystore.js near.d.ts near.js providers index.d.ts index.js json-rpc-provider.d.ts json-rpc-provider.js provider.d.ts provider.js res error_messages.d.ts error_messages.json signer.d.ts signer.js transaction.d.ts transaction.js utils enums.d.ts enums.js errors.d.ts errors.js exponential-backoff.d.ts exponential-backoff.js format.d.ts format.js index.d.ts index.js key_pair.d.ts key_pair.js network.d.ts network.js rpc_errors.d.ts rpc_errors.js serialize.d.ts serialize.js setup-node-fetch.d.ts setup-node-fetch.js web.d.ts web.js validators.d.ts validators.js wallet-account.d.ts wallet-account.js node_modules bn.js CHANGELOG.md README.md lib bn.js package.json package.json near-cli README.md bin near-cli.js commands add-key.js call.js create-account.js delete-key.js dev-deploy.js evm-call.js evm-dev-init.js evm-view.js generate-key.js js.js proposals.js repl.js set-x-api-key.js tx-status.js validators.js view-state.js config.js context index.d.ts get-config.js index.js middleware abi.js base64-args.js initial-balance.js key-store.js ledger.js print-options.js seed-phrase.js package.json test_environment.js utils capture-login-success.js check-credentials.js check-version.js connect.js create-dev-account.js deprecation-warning.js error-handlers.js eventtracking.js exit-on-error.js explorer.js implicit-accountid.js inspect-response.js log-event.js readline.js settings.js validators-info.js verify-account.js x-api-key-settings.js near-hd-key README.md dist index.d.ts index.js utils.d.ts utils.js package.json near-ledger-js .travis.yml README.md demo demo.js index.html index.js package.json supportedTransports.js near-sdk-js README.md builder builder.c lib api.d.ts api.js build-tools include-bytes.d.ts include-bytes.js near-bindgen-exporter.d.ts near-bindgen-exporter.js cli cli.d.ts cli.js deps binaryen wasi-stub run.sh quickjs .github workflows release-artifacts.yml build.sh cutils.c cutils.h examples fib.c fib_module.js hello.js hello_module.js pi_bigdecimal.js pi_bigfloat.js pi_bigint.js point.c test_fib.js test_point.js libbf.c libbf.h libregexp-opcode.h libregexp.c libregexp.h libunicode-table.h libunicode.c libunicode.h list.h qjs.c qjsc.c qjscalc.js quickjs-atom.h quickjs-libc-min.c quickjs-libc-min.h quickjs-libc.c quickjs-libc.h quickjs-opcode.h quickjs.h readme.txt release.sh repl.js run-test262.c test262_errors.txt test262o_errors.txt tests bjson.c microbench.js test_bignum.js test_bjson.js test_builtin.js test_closure.js test_language.js test_loop.js test_op_overloading.js test_qjscalc.js test_std.js test_worker.js test_worker_module.js unicode_download.sh unicode_gen.c unicode_gen_def.h wasi-sdk lib clang 10.0.0 include __clang_cuda_builtin_vars.h __clang_cuda_cmath.h __clang_cuda_complex_builtins.h __clang_cuda_device_functions.h __clang_cuda_intrinsics.h __clang_cuda_libdevice_declares.h __clang_cuda_math_forward_declares.h __clang_cuda_runtime_wrapper.h __stddef_max_align_t.h __wmmintrin_aes.h __wmmintrin_pclmul.h adxintrin.h altivec.h ammintrin.h arm64intr.h arm_acle.h arm_cmse.h arm_fp16.h arm_mve.h armintr.h avx2intrin.h avx512bf16intrin.h avx512bitalgintrin.h avx512bwintrin.h avx512cdintrin.h avx512dqintrin.h avx512erintrin.h avx512fintrin.h avx512ifmaintrin.h avx512ifmavlintrin.h avx512pfintrin.h avx512vbmi2intrin.h avx512vbmiintrin.h avx512vbmivlintrin.h avx512vlbf16intrin.h avx512vlbitalgintrin.h avx512vlbwintrin.h avx512vlcdintrin.h avx512vldqintrin.h avx512vlintrin.h avx512vlvbmi2intrin.h avx512vlvnniintrin.h avx512vlvp2intersectintrin.h avx512vnniintrin.h avx512vp2intersectintrin.h avx512vpopcntdqintrin.h avx512vpopcntdqvlintrin.h avxintrin.h bmi2intrin.h bmiintrin.h cetintrin.h cldemoteintrin.h clflushoptintrin.h clwbintrin.h clzerointrin.h cpuid.h emmintrin.h enqcmdintrin.h f16cintrin.h float.h fma4intrin.h fmaintrin.h fxsrintrin.h gfniintrin.h htmintrin.h htmxlintrin.h ia32intrin.h immintrin.h intrin.h inttypes.h invpcidintrin.h iso646.h limits.h lwpintrin.h lzcntintrin.h mm3dnow.h mm_malloc.h mmintrin.h movdirintrin.h msa.h mwaitxintrin.h nmmintrin.h opencl-c-base.h opencl-c.h openmp_wrappers __clang_openmp_math.h __clang_openmp_math_declares.h math.h pconfigintrin.h pkuintrin.h pmmintrin.h popcntintrin.h ppc_wrappers emmintrin.h mm_malloc.h mmintrin.h pmmintrin.h smmintrin.h tmmintrin.h xmmintrin.h prfchwintrin.h ptwriteintrin.h rdseedintrin.h rtmintrin.h s390intrin.h sgxintrin.h shaintrin.h smmintrin.h stdalign.h stdarg.h stdatomic.h stdbool.h stddef.h stdint.h stdnoreturn.h tbmintrin.h tgmath.h tmmintrin.h unwind.h vadefs.h vaesintrin.h varargs.h vecintrin.h vpclmulqdqintrin.h waitpkgintrin.h wbnoinvdintrin.h wmmintrin.h x86intrin.h xmmintrin.h xopintrin.h xsavecintrin.h xsaveintrin.h xsaveoptintrin.h xsavesintrin.h xtestintrin.h share clang clang-format-diff.py clang-format-sublime.py clang-format.py clang-tidy-diff.py run-clang-tidy.py wasi-sysroot include __errno.h __errno_values.h __fd_set.h __function___isatty.h __functions_malloc.h __functions_memcpy.h __header_dirent.h __header_fcntl.h __header_inttypes.h __header_netinet_in.h __header_poll.h __header_stdlib.h __header_string.h __header_sys_ioctl.h __header_sys_resource.h __header_sys_socket.h __header_sys_stat.h __header_time.h __header_unistd.h __macro_FD_SETSIZE.h __macro_PAGESIZE.h __mode_t.h __seek.h __struct_dirent.h __struct_in6_addr.h __struct_in_addr.h __struct_iovec.h __struct_msghdr.h __struct_pollfd.h __struct_rusage.h __struct_sockaddr.h __struct_sockaddr_in.h __struct_sockaddr_in6.h __struct_sockaddr_storage.h __struct_sockaddr_un.h __struct_stat.h __struct_timespec.h __struct_timeval.h __struct_tm.h __struct_tms.h __typedef_DIR.h __typedef_blkcnt_t.h __typedef_blksize_t.h __typedef_clock_t.h __typedef_clockid_t.h __typedef_dev_t.h __typedef_fd_set.h __typedef_gid_t.h __typedef_in_addr_t.h __typedef_in_port_t.h __typedef_ino_t.h __typedef_mode_t.h __typedef_nfds_t.h __typedef_nlink_t.h __typedef_off_t.h __typedef_sa_family_t.h __typedef_sigset_t.h __typedef_socklen_t.h __typedef_ssize_t.h __typedef_suseconds_t.h __typedef_time_t.h __typedef_uid_t.h alloca.h ar.h arpa ftp.h inet.h nameser.h nameser_compat.h telnet.h tftp.h assert.h bits alltypes.h dirent.h fcntl.h fenv.h float.h hwcap.h io.h ioctl.h ioctl_fix.h ipcstat.h limits.h mman.h poll.h posix.h reg.h resource.h signal.h socket.h stat.h stdint.h byteswap.h c++ v1 __bsd_locale_defaults.h __bsd_locale_fallbacks.h __cxxabi_config.h complex.h ctype.h cxxabi.h errno.h fenv.h float.h inttypes.h limits.h locale.h math.h setjmp.h stdbool.h stddef.h stdint.h stdio.h stdlib.h string.h support android locale_bionic.h fuchsia xlocale.h ibm limits.h locale_mgmt_aix.h support.h xlocale.h musl xlocale.h newlib xlocale.h solaris floatingpoint.h wchar.h xlocale.h win32 limits_msvc_win32.h locale_win32.h xlocale __nop_locale_mgmt.h __posix_l_fallback.h __strtonum_fallback.h tgmath.h wchar.h wctype.h complex.h cpio.h crypt.h ctype.h dirent.h endian.h err.h errno.h fcntl.h features.h fenv.h float.h fmtmsg.h fnmatch.h ftw.h getopt.h glob.h iconv.h ifaddrs.h inttypes.h iso646.h langinfo.h libgen.h limits.h locale.h malloc.h math.h memory.h monetary.h mqueue.h netinet icmp6.h igmp.h in.h in_systm.h ip.h ip6.h ip_icmp.h tcp.h udp.h netpacket packet.h nl_types.h poll.h regex.h sched.h search.h semaphore.h signal.h stdalign.h stdbool.h stdc-predef.h stdint.h stdio.h stdio_ext.h stdlib.h stdnoreturn.h string.h strings.h stropts.h sys dir.h errno.h eventfd.h fcntl.h file.h ioctl.h mman.h param.h poll.h random.h reg.h resource.h select.h signal.h socket.h stat.h stropts.h syscall.h sysinfo.h time.h timeb.h times.h timex.h ttydefaults.h types.h uio.h un.h utsname.h syscall.h sysexits.h tar.h tgmath.h threads.h time.h uchar.h unistd.h utime.h values.h wasi api.h libc-environ.h libc-find-relpath.h libc.h wchar.h wctype.h share wasm32-wasi defined-symbols.txt include-all.c predefined-macros.txt undefined-symbols.txt post-install.d.ts post-install.js utils.d.ts utils.js collections index.d.ts index.js lookup-map.d.ts lookup-map.js lookup-set.d.ts lookup-set.js unordered-map.d.ts unordered-map.js unordered-set.d.ts unordered-set.js vector.d.ts vector.js index.d.ts index.js near-bindgen.d.ts near-bindgen.js promise.d.ts promise.js types account_id.d.ts account_id.js collections.d.ts collections.js gas.d.ts gas.js index.d.ts index.js primitives.d.ts primitives.js public_key.d.ts public_key.js vm_types.d.ts vm_types.js utils.d.ts utils.js package.json near-seed-phrase .eslintrc.yml .fossa.yml .travis.yml index.js package.json test index.test.js node-abi .circleci config.yml .github workflows update-abi.yml .releaserc.json CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js package.json scripts update-abi-registry.js test index.js node-addon-api CHANGELOG.md LICENSE.md README.md index.js napi-inl.deprecated.h napi-inl.h napi.h nothing.c package-support.json package.json tools README.md check-napi.js clang-format.js conversion.js node-fetch LICENSE.md README.md browser.js lib index.es.js index.js package.json node-gyp-build README.md bin.js build-test.js index.js optional.js package.json node-hid LICENSE-bsd.txt Publishing.md README.md hidapi .appveyor.yml .builds alpine.yml archlinux.yml fedora-mingw.yml freebsd.yml .cirrus.yml AUTHORS.txt HACKING.txt LICENSE-bsd.txt LICENSE-gpl3.txt LICENSE-orig.txt LICENSE.txt README.md hidapi hidapi.h hidtest test.c libusb hid.c linux hid.c mac hid.c testgui copy_to_bundle.sh mac_support.h test.cpp testgui.sln windows hid.c hidapi.sln nodehid.js package.json src buzzers.js powermate.js show-devices.js test-bigredbutton.js test-blink1.js test-buzzers.js test-ci.js test-macbookprotrackpad.js test-powermate.js test-ps3-rumbleled.js test-ps3.js test-teensyrawhid.js test-tinyusbrawhid.js testReadSync.js node-releases README.md data processed envs.json release-schedule release-schedule.json package.json normalize-url index.d.ts index.js package.json readme.md npmlog CHANGELOG.md README.md log.js package.json number-is-nan index.js package.json readme.md o3 README.md index.js lib Class.js abstractMethod.js index.js package.json object-assign index.js package.json readme.md once README.md once.js package.json open index.d.ts index.js package.json readme.md p-cancelable index.d.ts index.js package.json readme.md p-limit index.js package.json readme.md p-locate index.js package.json readme.md p-try index.js package.json readme.md package-json index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md parse-json index.js package.json readme.md parse-passwd README.md index.js package.json path-browserify .github FUNDING.yml .travis.yml CHANGELOG.md README.md index.js package.json security.md test index.js test-path-basename.js test-path-dirname.js test-path-extname.js test-path-isabsolute.js test-path-join.js test-path-parse-format.js test-path-relative.js test-path-resolve.js test-path-zero-length-strings.js test-path.js path-exists index.js package.json readme.md path-is-absolute index.js package.json readme.md path-parse README.md index.js package.json pbkdf2 README.md browser.js index.js lib async.js default-encoding.js precondition.js sync-browser.js sync.js to-buffer.js package.json picocolors README.md package.json picocolors.browser.js picocolors.d.ts picocolors.js types.ts picomatch CHANGELOG.md README.md index.js lib constants.js parse.js picomatch.js scan.js utils.js package.json pify index.js package.json readme.md pkg-conf index.js package.json readme.md platform README.md package.json platform.js prebuild-install CHANGELOG.md CONTRIBUTING.md README.md asset.js bin.js download.js error.js help.txt index.js log.js package.json proxy.js rc.js util.js prepend-http index.js package.json readme.md pretty-format README.md build collections.d.ts collections.js index.d.ts index.js plugins AsymmetricMatcher.d.ts AsymmetricMatcher.js ConvertAnsi.d.ts ConvertAnsi.js DOMCollection.d.ts DOMCollection.js DOMElement.d.ts DOMElement.js Immutable.d.ts Immutable.js ReactElement.d.ts ReactElement.js ReactTestComponent.d.ts ReactTestComponent.js lib escapeHTML.d.ts escapeHTML.js markup.d.ts markup.js types.d.ts types.js node_modules ansi-styles index.d.ts index.js package.json readme.md package.json process-nextick-args index.js license.md package.json readme.md pump .travis.yml README.md index.js package.json test-browser.js test-node.js pupa index.d.ts index.js package.json readme.md queue-microtask README.md index.d.ts index.js package.json randombytes .travis.yml .zuul.yml README.md browser.js index.js package.json test.js rc README.md browser.js cli.js index.js lib utils.js package.json test ini.js nested-env-vars.js test.js react-is README.md build-info.json cjs react-is.development.js react-is.production.min.js index.js package.json umd react-is.development.js react-is.production.min.js readable-stream CONTRIBUTING.md GOVERNANCE.md README.md errors-browser.js errors.js experimentalWarning.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams async_iterator.js buffer_list.js destroy.js end-of-stream.js from-browser.js from.js pipeline.js state.js stream-browser.js stream.js package.json readable-browser.js readable.js registry-auth-token CHANGELOG.md README.md base64.js index.js package.json registry-url.js registry-url index.d.ts index.js package.json readme.md remove-trailing-slash history.md index.d.ts index.js package.json readme.md require-directory .travis.yml index.js package.json resolve .github FUNDING.yml SECURITY.md async.js example async.js sync.js index.js lib async.js caller.js core.js core.json homedir.js is-core.js node-modules-paths.js normalize-options.js sync.js package.json sync.js test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js home_paths.js home_paths_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json false_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json malformed_package_json index.js package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json nested_symlinks mylib async.js package.json sync.js other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js package bar.js package.json without_basedir main.js resolver_sync.js shadowed_core.js shadowed_core node_modules util index.js subdirs.js symlinks.js responselike README.md package.json src index.js reusify .coveralls.yml .travis.yml README.md benchmarks createNoCodeFunction.js fib.js reuseNoCodeFunction.js package.json reusify.js test.js rimraf CHANGELOG.md README.md bin.js package.json rimraf.js ripemd160 CHANGELOG.md README.md index.js package.json rollup-plugin-sourcemaps CHANGELOG.md README.md dist __tests__ index.d.ts index.d.ts index.js package.json rollup CHANGELOG.md LICENSE.md README.md dist es package.json rollup.browser.js rollup.js shared rollup.js watch.js loadConfigFile.js rollup.browser.js rollup.d.ts rollup.js shared index.js loadConfigFile.js mergeOptions.js rollup.js watch-cli.js watch.js package.json run-parallel README.md index.js package.json rxjs AsyncSubject.d.ts AsyncSubject.js BehaviorSubject.d.ts BehaviorSubject.js InnerSubscriber.d.ts InnerSubscriber.js LICENSE.txt Notification.d.ts Notification.js Observable.d.ts Observable.js Observer.d.ts Observer.js Operator.d.ts Operator.js OuterSubscriber.d.ts OuterSubscriber.js README.md ReplaySubject.d.ts ReplaySubject.js Rx.d.ts Rx.js Scheduler.d.ts Scheduler.js Subject.d.ts Subject.js SubjectSubscription.d.ts SubjectSubscription.js Subscriber.d.ts Subscriber.js Subscription.d.ts Subscription.js _esm2015 LICENSE.txt README.md ajax index.js fetch index.js index.js internal-compatibility index.js internal AsyncSubject.js BehaviorSubject.js InnerSubscriber.js Notification.js Observable.js Observer.js Operator.js OuterSubscriber.js ReplaySubject.js Rx.js Scheduler.js Subject.js SubjectSubscription.js Subscriber.js Subscription.js config.js innerSubscribe.js observable ConnectableObservable.js SubscribeOnObservable.js bindCallback.js bindNodeCallback.js combineLatest.js concat.js defer.js dom AjaxObservable.js WebSocketSubject.js ajax.js fetch.js webSocket.js empty.js forkJoin.js from.js fromArray.js fromEvent.js fromEventPattern.js fromIterable.js fromPromise.js generate.js iif.js interval.js merge.js never.js of.js onErrorResumeNext.js pairs.js partition.js race.js range.js throwError.js timer.js using.js zip.js operators audit.js auditTime.js buffer.js bufferCount.js bufferTime.js bufferToggle.js bufferWhen.js catchError.js combineAll.js combineLatest.js concat.js concatAll.js concatMap.js concatMapTo.js count.js debounce.js debounceTime.js defaultIfEmpty.js delay.js delayWhen.js dematerialize.js distinct.js distinctUntilChanged.js distinctUntilKeyChanged.js elementAt.js endWith.js every.js exhaust.js exhaustMap.js expand.js filter.js finalize.js find.js findIndex.js first.js groupBy.js ignoreElements.js index.js isEmpty.js last.js map.js mapTo.js materialize.js max.js merge.js mergeAll.js mergeMap.js mergeMapTo.js mergeScan.js min.js multicast.js observeOn.js onErrorResumeNext.js pairwise.js partition.js pluck.js publish.js publishBehavior.js publishLast.js publishReplay.js race.js reduce.js refCount.js repeat.js repeatWhen.js retry.js retryWhen.js sample.js sampleTime.js scan.js sequenceEqual.js share.js shareReplay.js single.js skip.js skipLast.js skipUntil.js skipWhile.js startWith.js subscribeOn.js switchAll.js switchMap.js switchMapTo.js take.js takeLast.js takeUntil.js takeWhile.js tap.js throttle.js throttleTime.js throwIfEmpty.js timeInterval.js timeout.js timeoutWith.js timestamp.js toArray.js window.js windowCount.js windowTime.js windowToggle.js windowWhen.js withLatestFrom.js zip.js zipAll.js scheduled scheduleArray.js scheduleIterable.js scheduleObservable.js schedulePromise.js scheduled.js scheduler Action.js AnimationFrameAction.js AnimationFrameScheduler.js AsapAction.js AsapScheduler.js AsyncAction.js AsyncScheduler.js QueueAction.js QueueScheduler.js VirtualTimeScheduler.js animationFrame.js asap.js async.js queue.js symbol iterator.js observable.js rxSubscriber.js testing ColdObservable.js HotObservable.js SubscriptionLog.js SubscriptionLoggable.js TestMessage.js TestScheduler.js types.js util ArgumentOutOfRangeError.js EmptyError.js Immediate.js ObjectUnsubscribedError.js TimeoutError.js UnsubscriptionError.js applyMixins.js canReportError.js errorObject.js hostReportError.js identity.js isArray.js isArrayLike.js isDate.js isFunction.js isInteropObservable.js isIterable.js isNumeric.js isObject.js isObservable.js isPromise.js isScheduler.js noop.js not.js pipe.js root.js subscribeTo.js subscribeToArray.js subscribeToIterable.js subscribeToObservable.js subscribeToPromise.js subscribeToResult.js toSubscriber.js tryCatch.js operators index.js path-mapping.js testing index.js webSocket index.js _esm5 LICENSE.txt README.md ajax index.js fetch index.js index.js internal-compatibility index.js internal AsyncSubject.js BehaviorSubject.js InnerSubscriber.js Notification.js Observable.js Observer.js Operator.js OuterSubscriber.js ReplaySubject.js Rx.js Scheduler.js Subject.js SubjectSubscription.js Subscriber.js Subscription.js config.js innerSubscribe.js observable ConnectableObservable.js SubscribeOnObservable.js bindCallback.js bindNodeCallback.js combineLatest.js concat.js defer.js dom AjaxObservable.js WebSocketSubject.js ajax.js fetch.js webSocket.js empty.js forkJoin.js from.js fromArray.js fromEvent.js fromEventPattern.js fromIterable.js fromPromise.js generate.js iif.js interval.js merge.js never.js of.js onErrorResumeNext.js pairs.js partition.js race.js range.js throwError.js timer.js using.js zip.js operators audit.js auditTime.js buffer.js bufferCount.js bufferTime.js bufferToggle.js bufferWhen.js catchError.js combineAll.js combineLatest.js concat.js concatAll.js concatMap.js concatMapTo.js count.js debounce.js debounceTime.js defaultIfEmpty.js delay.js delayWhen.js dematerialize.js distinct.js distinctUntilChanged.js distinctUntilKeyChanged.js elementAt.js endWith.js every.js exhaust.js exhaustMap.js expand.js filter.js finalize.js find.js findIndex.js first.js groupBy.js ignoreElements.js index.js isEmpty.js last.js map.js mapTo.js materialize.js max.js merge.js mergeAll.js mergeMap.js mergeMapTo.js mergeScan.js min.js multicast.js observeOn.js onErrorResumeNext.js pairwise.js partition.js pluck.js publish.js publishBehavior.js publishLast.js publishReplay.js race.js reduce.js refCount.js repeat.js repeatWhen.js retry.js retryWhen.js sample.js sampleTime.js scan.js sequenceEqual.js share.js shareReplay.js single.js skip.js skipLast.js skipUntil.js skipWhile.js startWith.js subscribeOn.js switchAll.js switchMap.js switchMapTo.js take.js takeLast.js takeUntil.js takeWhile.js tap.js throttle.js throttleTime.js throwIfEmpty.js timeInterval.js timeout.js timeoutWith.js timestamp.js toArray.js window.js windowCount.js windowTime.js windowToggle.js windowWhen.js withLatestFrom.js zip.js zipAll.js scheduled scheduleArray.js scheduleIterable.js scheduleObservable.js schedulePromise.js scheduled.js scheduler Action.js AnimationFrameAction.js AnimationFrameScheduler.js AsapAction.js AsapScheduler.js AsyncAction.js AsyncScheduler.js QueueAction.js QueueScheduler.js VirtualTimeScheduler.js animationFrame.js asap.js async.js queue.js symbol iterator.js observable.js rxSubscriber.js testing ColdObservable.js HotObservable.js SubscriptionLog.js SubscriptionLoggable.js TestMessage.js TestScheduler.js types.js util ArgumentOutOfRangeError.js EmptyError.js Immediate.js ObjectUnsubscribedError.js TimeoutError.js UnsubscriptionError.js applyMixins.js canReportError.js errorObject.js hostReportError.js identity.js isArray.js isArrayLike.js isDate.js isFunction.js isInteropObservable.js isIterable.js isNumeric.js isObject.js isObservable.js isPromise.js isScheduler.js noop.js not.js pipe.js root.js subscribeTo.js subscribeToArray.js subscribeToIterable.js subscribeToObservable.js subscribeToPromise.js subscribeToResult.js toSubscriber.js tryCatch.js operators index.js path-mapping.js testing index.js webSocket index.js add observable bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom ajax.d.ts ajax.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js if.d.ts if.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js race.d.ts race.js range.d.ts range.js throw.d.ts throw.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operator audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catch.d.ts catch.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js do.d.ts do.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finally.d.ts finally.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js isEmpty.d.ts isEmpty.js last.d.ts last.js let.d.ts let.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switch.d.ts switch.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js toPromise.d.ts toPromise.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js ajax index.d.ts index.js package.json bundles rxjs.umd.js rxjs.umd.min.js fetch index.d.ts index.js package.json index.d.ts index.js interfaces.d.ts interfaces.js internal-compatibility index.d.ts index.js package.json internal AsyncSubject.d.ts AsyncSubject.js BehaviorSubject.d.ts BehaviorSubject.js InnerSubscriber.d.ts InnerSubscriber.js Notification.d.ts Notification.js Observable.d.ts Observable.js Observer.d.ts Observer.js Operator.d.ts Operator.js OuterSubscriber.d.ts OuterSubscriber.js ReplaySubject.d.ts ReplaySubject.js Rx.d.ts Rx.js Scheduler.d.ts Scheduler.js Subject.d.ts Subject.js SubjectSubscription.d.ts SubjectSubscription.js Subscriber.d.ts Subscriber.js Subscription.d.ts Subscription.js config.d.ts config.js innerSubscribe.d.ts innerSubscribe.js observable ConnectableObservable.d.ts ConnectableObservable.js SubscribeOnObservable.d.ts SubscribeOnObservable.js bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom AjaxObservable.d.ts AjaxObservable.js WebSocketSubject.d.ts WebSocketSubject.js ajax.d.ts ajax.js fetch.d.ts fetch.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromArray.d.ts fromArray.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromIterable.d.ts fromIterable.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js iif.d.ts iif.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js partition.d.ts partition.js race.d.ts race.js range.d.ts range.js throwError.d.ts throwError.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operators audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catchError.d.ts catchError.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js elementAt.d.ts elementAt.js endWith.d.ts endWith.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finalize.d.ts finalize.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js index.d.ts index.js isEmpty.d.ts isEmpty.js last.d.ts last.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js refCount.d.ts refCount.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switchAll.d.ts switchAll.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js tap.d.ts tap.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js throwIfEmpty.d.ts throwIfEmpty.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js scheduled scheduleArray.d.ts scheduleArray.js scheduleIterable.d.ts scheduleIterable.js scheduleObservable.d.ts scheduleObservable.js schedulePromise.d.ts schedulePromise.js scheduled.d.ts scheduled.js scheduler Action.d.ts Action.js AnimationFrameAction.d.ts AnimationFrameAction.js AnimationFrameScheduler.d.ts AnimationFrameScheduler.js AsapAction.d.ts AsapAction.js AsapScheduler.d.ts AsapScheduler.js AsyncAction.d.ts AsyncAction.js AsyncScheduler.d.ts AsyncScheduler.js QueueAction.d.ts QueueAction.js QueueScheduler.d.ts QueueScheduler.js VirtualTimeScheduler.d.ts VirtualTimeScheduler.js animationFrame.d.ts animationFrame.js asap.d.ts asap.js async.d.ts async.js queue.d.ts queue.js symbol iterator.d.ts iterator.js observable.d.ts observable.js rxSubscriber.d.ts rxSubscriber.js testing ColdObservable.d.ts ColdObservable.js HotObservable.d.ts HotObservable.js SubscriptionLog.d.ts SubscriptionLog.js SubscriptionLoggable.d.ts SubscriptionLoggable.js TestMessage.d.ts TestMessage.js TestScheduler.d.ts TestScheduler.js types.d.ts types.js util ArgumentOutOfRangeError.d.ts ArgumentOutOfRangeError.js EmptyError.d.ts EmptyError.js Immediate.d.ts Immediate.js ObjectUnsubscribedError.d.ts ObjectUnsubscribedError.js TimeoutError.d.ts TimeoutError.js UnsubscriptionError.d.ts UnsubscriptionError.js applyMixins.d.ts applyMixins.js canReportError.d.ts canReportError.js errorObject.d.ts errorObject.js hostReportError.d.ts hostReportError.js identity.d.ts identity.js isArray.d.ts isArray.js isArrayLike.d.ts isArrayLike.js isDate.d.ts isDate.js isFunction.d.ts isFunction.js isInteropObservable.d.ts isInteropObservable.js isIterable.d.ts isIterable.js isNumeric.d.ts isNumeric.js isObject.d.ts isObject.js isObservable.d.ts isObservable.js isPromise.d.ts isPromise.js isScheduler.d.ts isScheduler.js noop.d.ts noop.js not.d.ts not.js pipe.d.ts pipe.js root.d.ts root.js subscribeTo.d.ts subscribeTo.js subscribeToArray.d.ts subscribeToArray.js subscribeToIterable.d.ts subscribeToIterable.js subscribeToObservable.d.ts subscribeToObservable.js subscribeToPromise.d.ts subscribeToPromise.js subscribeToResult.d.ts subscribeToResult.js toSubscriber.d.ts toSubscriber.js tryCatch.d.ts tryCatch.js migrations collection.json update-6_0_0 index.js observable ArrayLikeObservable.d.ts ArrayLikeObservable.js ArrayObservable.d.ts ArrayObservable.js BoundCallbackObservable.d.ts BoundCallbackObservable.js BoundNodeCallbackObservable.d.ts BoundNodeCallbackObservable.js ConnectableObservable.d.ts ConnectableObservable.js DeferObservable.d.ts DeferObservable.js EmptyObservable.d.ts EmptyObservable.js ErrorObservable.d.ts ErrorObservable.js ForkJoinObservable.d.ts ForkJoinObservable.js FromEventObservable.d.ts FromEventObservable.js FromEventPatternObservable.d.ts FromEventPatternObservable.js FromObservable.d.ts FromObservable.js GenerateObservable.d.ts GenerateObservable.js IfObservable.d.ts IfObservable.js IntervalObservable.d.ts IntervalObservable.js IteratorObservable.d.ts IteratorObservable.js NeverObservable.d.ts NeverObservable.js PairsObservable.d.ts PairsObservable.js PromiseObservable.d.ts PromiseObservable.js RangeObservable.d.ts RangeObservable.js ScalarObservable.d.ts ScalarObservable.js SubscribeOnObservable.d.ts SubscribeOnObservable.js TimerObservable.d.ts TimerObservable.js UsingObservable.d.ts UsingObservable.js bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom AjaxObservable.d.ts AjaxObservable.js WebSocketSubject.d.ts WebSocketSubject.js ajax.d.ts ajax.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromArray.d.ts fromArray.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromIterable.d.ts fromIterable.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js if.d.ts if.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js race.d.ts race.js range.d.ts range.js throw.d.ts throw.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operator audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catch.d.ts catch.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js do.d.ts do.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finally.d.ts finally.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js isEmpty.d.ts isEmpty.js last.d.ts last.js let.d.ts let.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switch.d.ts switch.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js toPromise.d.ts toPromise.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js operators audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catchError.d.ts catchError.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finalize.d.ts finalize.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js index.d.ts index.js isEmpty.d.ts isEmpty.js last.d.ts last.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js package.json pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js refCount.d.ts refCount.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switchAll.d.ts switchAll.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js tap.d.ts tap.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js throwIfEmpty.d.ts throwIfEmpty.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js package.json scheduler animationFrame.d.ts animationFrame.js asap.d.ts asap.js async.d.ts async.js queue.d.ts queue.js src AsyncSubject.ts BehaviorSubject.ts InnerSubscriber.ts LICENSE.txt MiscJSDoc.ts Notification.ts Observable.ts Observer.ts Operator.ts OuterSubscriber.ts README.md ReplaySubject.ts Rx.global.js Rx.ts Scheduler.ts Subject.ts SubjectSubscription.ts Subscriber.ts Subscription.ts add observable bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom ajax.ts webSocket.ts empty.ts forkJoin.ts from.ts fromEvent.ts fromEventPattern.ts fromPromise.ts generate.ts if.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts race.ts range.ts throw.ts timer.ts using.ts zip.ts operator audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catch.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts do.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finally.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts isEmpty.ts last.ts let.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switch.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts throttle.ts throttleTime.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts toPromise.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts ajax index.ts package.json fetch index.ts package.json index.ts interfaces.ts internal-compatibility index.ts package.json internal AsyncSubject.ts BehaviorSubject.ts InnerSubscriber.ts Notification.ts Observable.ts Observer.ts Operator.ts OuterSubscriber.ts ReplaySubject.ts Rx.ts Scheduler.ts Subject.ts SubjectSubscription.ts Subscriber.ts Subscription.ts config.ts innerSubscribe.ts observable ConnectableObservable.ts SubscribeOnObservable.ts bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom AjaxObservable.ts MiscJSDoc.ts WebSocketSubject.ts ajax.ts fetch.ts webSocket.ts empty.ts forkJoin.ts from.ts fromArray.ts fromEvent.ts fromEventPattern.ts fromIterable.ts fromObservable.ts fromPromise.ts generate.ts iif.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts partition.ts race.ts range.ts throwError.ts timer.ts using.ts zip.ts operators audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catchError.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts elementAt.ts endWith.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finalize.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts index.ts isEmpty.ts last.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts refCount.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switchAll.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts tap.ts throttle.ts throttleTime.ts throwIfEmpty.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts scheduled scheduleArray.ts scheduleIterable.ts scheduleObservable.ts schedulePromise.ts scheduled.ts scheduler Action.ts AnimationFrameAction.ts AnimationFrameScheduler.ts AsapAction.ts AsapScheduler.ts AsyncAction.ts AsyncScheduler.ts QueueAction.ts QueueScheduler.ts VirtualTimeScheduler.ts animationFrame.ts asap.ts async.ts queue.ts symbol iterator.ts observable.ts rxSubscriber.ts testing ColdObservable.ts HotObservable.ts SubscriptionLog.ts SubscriptionLoggable.ts TestMessage.ts TestScheduler.ts types.ts umd.ts util ArgumentOutOfRangeError.ts EmptyError.ts Immediate.ts ObjectUnsubscribedError.ts TimeoutError.ts UnsubscriptionError.ts applyMixins.ts canReportError.ts errorObject.ts hostReportError.ts identity.ts isArray.ts isArrayLike.ts isDate.ts isFunction.ts isInteropObservable.ts isIterable.ts isNumeric.ts isObject.ts isObservable.ts isPromise.ts isScheduler.ts noop.ts not.ts pipe.ts root.ts subscribeTo.ts subscribeToArray.ts subscribeToIterable.ts subscribeToObservable.ts subscribeToPromise.ts subscribeToResult.ts toSubscriber.ts tryCatch.ts observable ArrayLikeObservable.ts ArrayObservable.ts BoundCallbackObservable.ts BoundNodeCallbackObservable.ts ConnectableObservable.ts DeferObservable.ts EmptyObservable.ts ErrorObservable.ts ForkJoinObservable.ts FromEventObservable.ts FromEventPatternObservable.ts FromObservable.ts GenerateObservable.ts IfObservable.ts IntervalObservable.ts IteratorObservable.ts NeverObservable.ts PairsObservable.ts PromiseObservable.ts RangeObservable.ts ScalarObservable.ts SubscribeOnObservable.ts TimerObservable.ts UsingObservable.ts bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom AjaxObservable.ts WebSocketSubject.ts ajax.ts webSocket.ts empty.ts forkJoin.ts from.ts fromArray.ts fromEvent.ts fromEventPattern.ts fromIterable.ts fromPromise.ts generate.ts if.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts race.ts range.ts throw.ts timer.ts using.ts zip.ts operator audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catch.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts do.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finally.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts isEmpty.ts last.ts let.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switch.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts throttle.ts throttleTime.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts toPromise.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts operators audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catchError.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finalize.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts index.ts isEmpty.ts last.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts package.json pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts refCount.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switchAll.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts tap.ts throttle.ts throttleTime.ts throwIfEmpty.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts scheduler animationFrame.ts asap.ts async.ts queue.ts symbol iterator.ts observable.ts rxSubscriber.ts testing index.ts package.json tsconfig.json util ArgumentOutOfRangeError.ts EmptyError.ts Immediate.ts ObjectUnsubscribedError.ts TimeoutError.ts UnsubscriptionError.ts applyMixins.ts errorObject.ts hostReportError.ts identity.ts isArray.ts isArrayLike.ts isDate.ts isFunction.ts isIterable.ts isNumeric.ts isObject.ts isObservable.ts isPromise.ts isScheduler.ts noop.ts not.ts pipe.ts root.ts subscribeTo.ts subscribeToArray.ts subscribeToIterable.ts subscribeToObservable.ts subscribeToPromise.ts subscribeToResult.ts toSubscriber.ts tryCatch.ts webSocket index.ts package.json symbol iterator.d.ts iterator.js observable.d.ts observable.js rxSubscriber.d.ts rxSubscriber.js testing index.d.ts index.js package.json util ArgumentOutOfRangeError.d.ts ArgumentOutOfRangeError.js EmptyError.d.ts EmptyError.js Immediate.d.ts Immediate.js ObjectUnsubscribedError.d.ts ObjectUnsubscribedError.js TimeoutError.d.ts TimeoutError.js UnsubscriptionError.d.ts UnsubscriptionError.js applyMixins.d.ts applyMixins.js errorObject.d.ts errorObject.js hostReportError.d.ts hostReportError.js identity.d.ts identity.js isArray.d.ts isArray.js isArrayLike.d.ts isArrayLike.js isDate.d.ts isDate.js isFunction.d.ts isFunction.js isIterable.d.ts isIterable.js isNumeric.d.ts isNumeric.js isObject.d.ts isObject.js isObservable.d.ts isObservable.js isPromise.d.ts isPromise.js isScheduler.d.ts isScheduler.js noop.d.ts noop.js not.d.ts not.js pipe.d.ts pipe.js root.d.ts root.js subscribeTo.d.ts subscribeTo.js subscribeToArray.d.ts subscribeToArray.js subscribeToIterable.d.ts subscribeToIterable.js subscribeToObservable.d.ts subscribeToObservable.js subscribeToPromise.d.ts subscribeToPromise.js subscribeToResult.d.ts subscribeToResult.js toSubscriber.d.ts toSubscriber.js tryCatch.d.ts tryCatch.js webSocket index.d.ts index.js package.json safe-buffer README.md index.d.ts index.js package.json semver-diff index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md semver README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json setprototypeof README.md index.d.ts index.js package.json test index.js sha.js .travis.yml README.md bin.js hash.js index.js package.json sha.js sha1.js sha224.js sha256.js sha384.js sha512.js test hash.js test.js vectors.js signal-exit LICENSE.txt README.md index.js package.json signals.js signale index.js license.md node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json readme.md signale.js types.js simple-concat .travis.yml README.md index.js package.json test basic.js simple-get .github dependabot.yml workflows ci.yml README.md index.js package.json slash index.d.ts index.js package.json readme.md source-map-resolve changelog.md index.js package.json readme.md sourcemap-codec CHANGELOG.md README.md dist sourcemap-codec.es.js sourcemap-codec.umd.js types sourcemap-codec.d.ts package.json stack-utils LICENSE.md index.js node_modules escape-string-regexp index.d.ts index.js package.json readme.md package.json readme.md statuses HISTORY.md README.md codes.json index.js package.json stoppable lib stoppable.js package.json readme.md string-width index.d.ts index.js package.json readme.md string_decoder README.md lib string_decoder.js package.json strip-ansi index.d.ts index.js package.json readme.md strip-bom index.js package.json readme.md strip-json-comments index.js package.json readme.md supports-color browser.js index.js package.json readme.md supports-preserve-symlinks-flag .github FUNDING.yml CHANGELOG.md README.md browser.js index.js package.json test index.js tar-fs .travis.yml README.md index.js package.json test fixtures a hello.txt b a test.txt index.js tar-stream README.md extract.js headers.js index.js pack.js package.json sandbox.js tcp-port-used README.md index.js node_modules debug README.md package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md package.json test.js text-encoding-utf-8 LICENSE.md README.md lib encoding.js encoding.lib.js package.json src encoding.js polyfill.js to-fast-properties index.js package.json readme.md to-readable-stream index.js package.json readme.md to-regex-range README.md index.js package.json toidentifier HISTORY.md README.md index.js package.json tr46 index.js lib mappingTable.json package.json ts-morph dist ts-morph.js lib ts-morph.d.ts package.json readme.md tslib CopyrightNotice.txt LICENSE.txt README.md modules index.js package.json package.json test validateModuleExportsMatchCommonJS index.js package.json tslib.d.ts tslib.es6.html tslib.es6.js tslib.html tslib.js tunnel-agent README.md index.js package.json tweetnacl AUTHORS.md CHANGELOG.md PULL_REQUEST_TEMPLATE.md README.md nacl-fast.js nacl-fast.min.js nacl.d.ts nacl.js nacl.min.js package.json type-detect README.md index.js package.json type-detect.js type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts typedarray-to-buffer .airtap.yml .travis.yml README.md index.js package.json test basic.js typescript LICENSE.txt README.md SECURITY.md ThirdPartyNoticeText.txt lib README.md cancellationToken.js cs diagnosticMessages.generated.json de diagnosticMessages.generated.json dynamicImportCompat.js es diagnosticMessages.generated.json fr diagnosticMessages.generated.json it diagnosticMessages.generated.json ja diagnosticMessages.generated.json ko diagnosticMessages.generated.json lib.d.ts lib.dom.d.ts lib.dom.iterable.d.ts lib.es2015.collection.d.ts lib.es2015.core.d.ts lib.es2015.d.ts lib.es2015.generator.d.ts lib.es2015.iterable.d.ts lib.es2015.promise.d.ts lib.es2015.proxy.d.ts lib.es2015.reflect.d.ts lib.es2015.symbol.d.ts lib.es2015.symbol.wellknown.d.ts lib.es2016.array.include.d.ts lib.es2016.d.ts lib.es2016.full.d.ts lib.es2017.d.ts lib.es2017.full.d.ts lib.es2017.intl.d.ts lib.es2017.object.d.ts lib.es2017.sharedmemory.d.ts lib.es2017.string.d.ts lib.es2017.typedarrays.d.ts lib.es2018.asyncgenerator.d.ts lib.es2018.asynciterable.d.ts lib.es2018.d.ts lib.es2018.full.d.ts lib.es2018.intl.d.ts lib.es2018.promise.d.ts lib.es2018.regexp.d.ts lib.es2019.array.d.ts lib.es2019.d.ts lib.es2019.full.d.ts lib.es2019.intl.d.ts lib.es2019.object.d.ts lib.es2019.string.d.ts lib.es2019.symbol.d.ts lib.es2020.bigint.d.ts lib.es2020.d.ts lib.es2020.date.d.ts lib.es2020.full.d.ts lib.es2020.intl.d.ts lib.es2020.number.d.ts lib.es2020.promise.d.ts lib.es2020.sharedmemory.d.ts lib.es2020.string.d.ts lib.es2020.symbol.wellknown.d.ts lib.es2021.d.ts lib.es2021.full.d.ts lib.es2021.intl.d.ts lib.es2021.promise.d.ts lib.es2021.string.d.ts lib.es2021.weakref.d.ts lib.es2022.array.d.ts lib.es2022.d.ts lib.es2022.error.d.ts lib.es2022.full.d.ts lib.es2022.intl.d.ts lib.es2022.object.d.ts lib.es2022.sharedmemory.d.ts lib.es2022.string.d.ts lib.es5.d.ts lib.es6.d.ts lib.esnext.d.ts lib.esnext.full.d.ts lib.esnext.intl.d.ts lib.esnext.promise.d.ts lib.esnext.string.d.ts lib.esnext.weakref.d.ts lib.scripthost.d.ts lib.webworker.d.ts lib.webworker.importscripts.d.ts lib.webworker.iterable.d.ts pl diagnosticMessages.generated.json protocol.d.ts pt-br diagnosticMessages.generated.json ru diagnosticMessages.generated.json tr diagnosticMessages.generated.json tsserverlibrary.d.ts typesMap.json typescript.d.ts typescriptServices.d.ts watchGuard.js zh-cn diagnosticMessages.generated.json zh-tw diagnosticMessages.generated.json package.json u2f-api .travis.yml README.md index.d.ts index.js lib google-u2f-api.js u2f-api.js package.json scripts test.sh test.in setup.js tsconfig.json u2f-api index.ts u3 README.md index.js lib cache.js eachCombination.js index.js package.json unique-string index.d.ts index.js package.json readme.md update-browserslist-db README.md check-npm-version.js cli.js index.d.ts index.js package.json utils.js update-notifier check.js index.js package.json readme.md url-parse-lax index.js package.json readme.md usb CHANGELOG.md README.md libusb .private README.txt bd.cmd bm.sh bwince.cmd post-rewrite.sh pre-commit.sh wbs.txt wbs_wince.txt .travis.yml INSTALL_WIN.txt README.md Xcode config.h android config.h appveyor.yml appveyor_cygwin.bat appveyor_minGW.bat autogen.sh bootstrap.sh examples dpfp.c dpfp_threaded.c ezusb.c ezusb.h fxload.c getopt getopt.c getopt.h getopt1.c hotplugtest.c listdevs.c sam3u_benchmark.c testlibusb.c xusb.c libusb core.c descriptor.c hotplug.c hotplug.h io.c libusb.h libusbi.h os darwin_usb.c darwin_usb.h haiku_pollfs.cpp haiku_usb.h haiku_usb_backend.cpp haiku_usb_raw.cpp haiku_usb_raw.h linux_netlink.c linux_udev.c linux_usbfs.c linux_usbfs.h netbsd_usb.c openbsd_usb.c poll_posix.c poll_posix.h poll_windows.c poll_windows.h sunos_usb.c sunos_usb.h threads_posix.c threads_posix.h threads_windows.c threads_windows.h wince_usb.c wince_usb.h windows_common.h windows_nt_common.c windows_nt_common.h windows_nt_shared_types.h windows_usbdk.c windows_usbdk.h windows_winusb.c windows_winusb.h strerror.c sync.c version.h version_nano.h msvc appveyor.bat config.h ddk_build.cmd errno.h inttypes.h libusb_2005.sln libusb_2010.sln libusb_2012.sln libusb_2013.sln libusb_2015.sln libusb_2017.sln libusb_wince.sln missing.c missing.h stdint.h tests libusb_testlib.h stress.c testlib.c travis-autogen.sh libusb_config config.h node_modules node-addon-api LICENSE.md README.md index.js napi-inl.deprecated.h napi-inl.h napi.h nothing.c package-support.json package.json tools README.md check-napi.js clang-format.js conversion.js eslint-format.js package.json src helpers.h node_usb.h uv_async_queue.h test usb.coffee usb.js util-deprecate History.md README.md browser.js node.js package.json uuid CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md dist esm-browser index.js md5.js nil.js parse.js regex.js rng.js sha1.js stringify.js v1.js v3.js v35.js v4.js v5.js validate.js version.js esm-node index.js md5.js nil.js parse.js regex.js rng.js sha1.js stringify.js v1.js v3.js v35.js v4.js v5.js validate.js version.js index.js md5-browser.js md5.js nil.js parse.js regex.js rng-browser.js rng.js sha1-browser.js sha1.js stringify.js umd uuid.min.js uuidNIL.min.js uuidParse.min.js uuidStringify.min.js uuidValidate.min.js uuidVersion.min.js uuidv1.min.js uuidv3.min.js uuidv4.min.js uuidv5.min.js uuid-bin.js v1.js v3.js v35.js v4.js v5.js validate.js version.js package.json v8flags README.md config-path.js index.js package.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js public-api.js url-state-machine.js utils.js package.json wide-align README.md align.js package.json widest-line index.d.ts index.js package.json readme.md wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js write-file-atomic CHANGELOG.md README.md index.js package.json xdg-basedir index.d.ts index.js package.json readme.md y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json package-lock.json package.json src contract.ts tsconfig.json integration-tests node_modules .package-lock.json @cspotcode source-map-support LICENSE.md README.md browser-source-map-support.js package.json register-hook-require.d.ts register-hook-require.js register.d.ts register.js source-map-support.d.ts source-map-support.js @jridgewell resolve-uri README.md dist resolve-uri.umd.js types resolve-uri.d.ts package.json sourcemap-codec README.md dist sourcemap-codec.umd.js types sourcemap-codec.d.ts package.json src sourcemap-codec.ts trace-mapping README.md dist trace-mapping.umd.js types any-map.d.ts binary-search.d.ts by-source.d.ts resolve.d.ts sort.d.ts sourcemap-segment.d.ts strip-filename.d.ts trace-mapping.d.ts types.d.ts package.json @nodelib fs.scandir README.md out adapters fs.d.ts fs.js constants.d.ts constants.js index.d.ts index.js providers async.d.ts async.js common.d.ts common.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js utils fs.d.ts fs.js index.d.ts index.js package.json fs.stat README.md out adapters fs.d.ts fs.js index.d.ts index.js providers async.d.ts async.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js package.json fs.walk README.md out index.d.ts index.js providers async.d.ts async.js index.d.ts index.js stream.d.ts stream.js sync.d.ts sync.js readers async.d.ts async.js common.d.ts common.js reader.d.ts reader.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js package.json @sindresorhus is dist index.d.ts index.js types.d.ts types.js package.json readme.md @szmarczak http-timer README.md dist source index.d.ts index.js package.json @tsconfig node10 README.md package.json tsconfig.json node12 README.md package.json tsconfig.json node14 README.md package.json tsconfig.json node16 README.md package.json tsconfig.json @types bn.js README.md index.d.ts package.json cacheable-request README.md index.d.ts package.json http-cache-semantics README.md index.d.ts package.json keyv README.md index.d.ts package.json node README.md assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts package.json path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts ts4.8 assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts responselike README.md index.d.ts package.json acorn-walk CHANGELOG.md README.md dist walk.d.ts walk.js package.json acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js acorn.mjs.d.ts bin.js package.json aggregate-error index.d.ts index.js package.json readme.md ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md anymatch README.md index.d.ts index.js package.json arg LICENSE.md README.md index.d.ts index.js package.json argparse CHANGELOG.md README.md index.js lib action.js action append.js append constant.js count.js help.js store.js store constant.js false.js true.js subparsers.js version.js action_container.js argparse.js argument error.js exclusive.js group.js argument_parser.js const.js help added_formatters.js formatter.js namespace.js utils.js package.json array-find-index index.js package.json readme.md array-union index.d.ts index.js package.json readme.md arrgv .travis.yml README.md index.js package.json test.js arrify index.d.ts index.js package.json readme.md ava index.d.ts lib api.js assert.js chalk.js cli.js code-excerpt.js concordance-options.js context-ref.js create-chain.js environment-variables.js eslint-plugin-helper-worker.js extensions.js fork.js globs.js is-ci.js like-selector.js line-numbers.js load-config.js module-types.js node-arguments.js parse-test-args.js plugin-support shared-worker-loader.js shared-workers.js provider-manager.js reporters beautify-stack.js colors.js default.js format-serialized-error.js improper-usage-messages.js prefix-title.js tap.js run-status.js runner.js scheduler.js serialize-error.js snapshot-manager.js test.js watcher.js worker base.js dependency-tracker.js line-numbers.js package.json plugin.d.ts readme.md types assertions.d.ts subscribable.d.ts test-fn.d.ts try-fn.d.ts balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js base64url dist base64url.d.ts base64url.js pad-string.d.ts pad-string.js index.js package.json readme.md binary-extensions binary-extensions.json binary-extensions.json.d.ts index.d.ts index.js package.json readme.md blueimp-md5 LICENSE.txt README.md js md5.js md5.min.js package.json bn.js README.md lib bn.js package.json borsh .eslintrc.yml .travis.yml LICENSE-MIT.txt README.md borsh-ts .eslintrc.yml index.ts test .eslintrc.yml fuzz borsh-roundtrip.js transaction-example enums.d.ts enums.js key_pair.d.ts key_pair.js serialize.d.ts serialize.js signer.d.ts signer.js transaction.d.ts transaction.js serialize.test.js lib index.d.ts index.js package.json tsconfig.json brace-expansion README.md index.js package.json braces CHANGELOG.md README.md index.js lib compile.js constants.js expand.js parse.js stringify.js utils.js package.json bs58 CHANGELOG.md README.md index.js package.json cacheable-lookup README.md index.d.ts package.json source index.js cacheable-request README.md package.json src index.js callsites index.d.ts index.js package.json readme.md capability Array.prototype.forEach.js Array.prototype.map.js Error.captureStackTrace.js Error.prototype.stack.js Function.prototype.bind.js Object.create.js Object.defineProperties.js Object.defineProperty.js Object.prototype.hasOwnProperty.js README.md arguments.callee.caller.js es5.js index.js lib CapabilityDetector.js definitions.js index.js package.json strict mode.js cbor LICENSE.md README.md lib cbor.js commented.js constants.js decoder.js diagnose.js encoder.js map.js simple.js tagged.js utils.js package.json types lib cbor.d.ts commented.d.ts constants.d.ts decoder.d.ts diagnose.d.ts encoder.d.ts map.d.ts simple.d.ts tagged.d.ts utils.d.ts vendor binary-parse-stream index.d.ts vendor binary-parse-stream README.md index.js chalk package.json readme.md source index.d.ts index.js utilities.js vendor ansi-styles index.d.ts index.js supports-color browser.d.ts browser.js index.d.ts index.js chokidar README.md index.js lib constants.js fsevents-handler.js nodefs-handler.js package.json types index.d.ts chownr README.md chownr.js package.json chunkd README.md dist chunkd.d.ts chunkd.js package.json ci-info CHANGELOG.md README.md index.d.ts index.js package.json vendors.json ci-parallel-vars README.md index.js package.json clean-stack index.d.ts index.js package.json readme.md clean-yaml-object index.js package.json readme.md cli-truncate index.d.ts index.js package.json readme.md cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js node_modules ansi-regex index.d.ts index.js package.json readme.md emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js is-fullwidth-code-point index.d.ts index.js package.json readme.md string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md package.json clone-response README.md package.json src index.js code-excerpt dist index.d.ts index.js package.json readme.md color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json common-path-prefix README.md index.d.ts index.js package.json concat-map .travis.yml example map.js index.js package.json test map.js concordance README.md index.js lib Circular.js Indenter.js Registry.js compare.js complexValues arguments.js arrayBuffer.js boxed.js dataView.js date.js error.js function.js global.js map.js object.js promise.js regexp.js set.js typedArray.js constants.js describe.js diff.js encoder.js format.js formatUtils.js getCtor.js getObjectKeys.js getStringTag.js hasLength.js isEnumerable.js lineBuilder.js metaDescriptors item.js mapEntry.js pointer.js property.js stats.js pluginRegistry.js primitiveValues bigInt.js boolean.js null.js number.js string.js symbol.js undefined.js recursorUtils.js serialize.js shouldCompareDeep.js symbolProperties.js themeUtils.js package.json convert-to-spaces dist index.d.ts index.js package.json readme.md create-require CHANGELOG.md README.md create-require.d.ts create-require.js package.json currently-unhandled browser.js core.js index.js package.json readme.md date-time index.d.ts index.js package.json readme.md debug README.md node_modules ms index.js license.md package.json readme.md package.json src browser.js common.js index.js node.js decompress-response index.d.ts index.js node_modules mimic-response index.d.ts index.js package.json readme.md package.json readme.md defer-to-connect README.md dist source index.d.ts index.js package.json del index.d.ts index.js node_modules aggregate-error index.d.ts index.js package.json readme.md clean-stack index.d.ts index.js package.json readme.md globby gitignore.js index.d.ts index.js package.json readme.md stream-utils.js indent-string index.d.ts index.js package.json readme.md p-map index.d.ts index.js package.json readme.md package.json readme.md depd History.md Readme.md index.js lib browser index.js package.json diff CONTRIBUTING.md README.md dist diff.js diff.min.js lib convert dmp.js xml.js diff array.js base.js character.js css.js json.js line.js sentence.js word.js index.es6.js index.js patch apply.js create.js merge.js parse.js util array.js distance-iterator.js params.js package.json release-notes.md runtime.js dir-glob index.js package.json readme.md eastasianwidth README.md eastasianwidth.js package.json emittery index.d.ts index.js package.json readme.md emoji-regex LICENSE-MIT.txt README.md RGI_Emoji.d.ts RGI_Emoji.js es2015 RGI_Emoji.d.ts RGI_Emoji.js index.d.ts index.js text.d.ts text.js index.d.ts index.js package.json text.d.ts text.js end-of-stream README.md index.js package.json error-polyfill README.md index.js lib index.js non-v8 Frame.js FrameStringParser.js FrameStringSource.js index.js prepareStackTrace.js unsupported.js v8.js package.json escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-string-regexp index.d.ts index.js package.json readme.md esprima README.md bin esparse.js esvalidate.js dist esprima.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json fast-diff .travis.yml README.md diff.d.ts diff.js package.json test.js fast-glob README.md out index.d.ts index.js managers patterns.d.ts patterns.js tasks.d.ts tasks.js providers async.d.ts async.js filters deep.d.ts deep.js entry.d.ts entry.js error.d.ts error.js matchers matcher.d.ts matcher.js partial.d.ts partial.js provider.d.ts provider.js stream.d.ts stream.js sync.d.ts sync.js transformers entry.d.ts entry.js readers async.d.ts async.js reader.d.ts reader.js stream.d.ts stream.js sync.d.ts sync.js settings.d.ts settings.js types index.d.ts index.js utils array.d.ts array.js errno.d.ts errno.js fs.d.ts fs.js index.d.ts index.js path.d.ts path.js pattern.d.ts pattern.js stream.d.ts stream.js string.d.ts string.js package.json fastq .github dependabot.yml workflows ci.yml README.md bench.js example.js index.d.ts package.json queue.js test example.ts promise.js test.js tsconfig.json figures index.d.ts index.js package.json readme.md fill-range README.md index.js package.json find-up index.d.ts index.js package.json readme.md fs-extra README.md lib copy copy-sync.js copy.js index.js empty index.js ensure file.js index.js link.js symlink-paths.js symlink-type.js symlink.js fs index.js index.js json index.js jsonfile.js output-json-sync.js output-json.js mkdirs index.js make-dir.js utils.js move index.js move-sync.js move.js output-file index.js path-exists index.js remove index.js rimraf.js util stat.js utimes.js package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json fsevents README.md fsevents.d.ts fsevents.js package.json get-caller-file LICENSE.md README.md index.d.ts index.js package.json get-stream buffer-stream.js index.d.ts index.js package.json readme.md glob-parent CHANGELOG.md README.md index.js package.json glob README.md common.js glob.js package.json sync.js globby ignore.js index.d.ts index.js node_modules slash index.d.ts index.js package.json readme.md package.json readme.md utilities.js got dist source as-promise create-rejection.d.ts create-rejection.js index.d.ts index.js normalize-arguments.d.ts normalize-arguments.js parse-body.d.ts parse-body.js types.d.ts types.js core calculate-retry-delay.d.ts calculate-retry-delay.js index.d.ts index.js utils dns-ip-version.d.ts dns-ip-version.js get-body-size.d.ts get-body-size.js get-buffer.d.ts get-buffer.js is-form-data.d.ts is-form-data.js is-response-ok.d.ts is-response-ok.js options-to-url.d.ts options-to-url.js proxy-events.d.ts proxy-events.js timed-out.d.ts timed-out.js unhandle.d.ts unhandle.js url-to-options.d.ts url-to-options.js weakable-map.d.ts weakable-map.js create.d.ts create.js index.d.ts index.js types.d.ts types.js utils deep-freeze.d.ts deep-freeze.js deprecation-warning.d.ts deprecation-warning.js package.json readme.md graceful-fs README.md clone.js graceful-fs.js legacy-streams.js package.json polyfills.js http-cache-semantics README.md index.js package.json http-errors HISTORY.md README.md index.js node_modules depd History.md Readme.md index.js lib browser index.js compat callsite-tostring.js event-listener-count.js index.js package.json package.json http2-wrapper README.md package.json source agent.js auto.js client-request.js incoming-message.js index.js utils calculate-server-name.js errors.js is-request-pseudo-header.js proxy-events.js url-to-options.js ignore-by-default README.md index.js package.json ignore README.md index.d.ts index.js legacy.js package.json imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json indent-string index.d.ts index.js package.json readme.md inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json irregular-plurals index.d.ts index.js irregular-plurals.json package.json readme.md is-binary-path index.d.ts index.js package.json readme.md is-error .travis.yml README.md index.js package.json test index.js is-extglob README.md index.js package.json is-fullwidth-code-point index.d.ts index.js package.json readme.md is-glob README.md index.js package.json is-number README.md index.js package.json is-path-cwd index.d.ts index.js package.json readme.md is-path-inside index.d.ts index.js package.json readme.md is-plain-object README.md dist is-plain-object.js is-plain-object.d.ts package.json is-promise index.d.ts index.js package.json readme.md is-unicode-supported index.d.ts index.js package.json readme.md js-sha256 CHANGELOG.md LICENSE.txt README.md build sha256.min.js index.d.ts package.json src sha256.js js-string-escape CHANGELOG.md README.md index.js package.json js-yaml CHANGELOG.md README.md bin js-yaml.js dist js-yaml.js js-yaml.min.js index.js lib js-yaml.js js-yaml common.js dumper.js exception.js loader.js mark.js schema.js schema core.js default_full.js default_safe.js failsafe.js json.js type.js type binary.js bool.js float.js int.js js function.js regexp.js undefined.js map.js merge.js null.js omap.js pairs.js seq.js set.js str.js timestamp.js package.json json-buffer .travis.yml README.md index.js package.json test index.js jsonfile CHANGELOG.md README.md index.js package.json utils.js keyv README.md package.json src index.d.ts index.js load-json-file index.d.ts index.js package.json readme.md locate-path index.d.ts index.js package.json readme.md lodash README.md _DataView.js _Hash.js _LazyWrapper.js _ListCache.js _LodashWrapper.js _Map.js _MapCache.js _Promise.js _Set.js _SetCache.js _Stack.js _Symbol.js _Uint8Array.js _WeakMap.js _apply.js _arrayAggregator.js _arrayEach.js _arrayEachRight.js _arrayEvery.js _arrayFilter.js _arrayIncludes.js _arrayIncludesWith.js _arrayLikeKeys.js _arrayMap.js _arrayPush.js _arrayReduce.js _arrayReduceRight.js _arraySample.js _arraySampleSize.js _arrayShuffle.js _arraySome.js _asciiSize.js _asciiToArray.js _asciiWords.js _assignMergeValue.js _assignValue.js _assocIndexOf.js _baseAggregator.js _baseAssign.js _baseAssignIn.js _baseAssignValue.js _baseAt.js _baseClamp.js _baseClone.js _baseConforms.js _baseConformsTo.js _baseCreate.js _baseDelay.js _baseDifference.js _baseEach.js _baseEachRight.js _baseEvery.js _baseExtremum.js _baseFill.js _baseFilter.js _baseFindIndex.js _baseFindKey.js _baseFlatten.js _baseFor.js _baseForOwn.js _baseForOwnRight.js _baseForRight.js _baseFunctions.js _baseGet.js _baseGetAllKeys.js _baseGetTag.js _baseGt.js _baseHas.js _baseHasIn.js _baseInRange.js _baseIndexOf.js _baseIndexOfWith.js _baseIntersection.js _baseInverter.js _baseInvoke.js _baseIsArguments.js _baseIsArrayBuffer.js _baseIsDate.js _baseIsEqual.js _baseIsEqualDeep.js _baseIsMap.js _baseIsMatch.js _baseIsNaN.js _baseIsNative.js _baseIsRegExp.js _baseIsSet.js _baseIsTypedArray.js _baseIteratee.js _baseKeys.js _baseKeysIn.js _baseLodash.js _baseLt.js _baseMap.js _baseMatches.js _baseMatchesProperty.js _baseMean.js _baseMerge.js _baseMergeDeep.js _baseNth.js _baseOrderBy.js _basePick.js _basePickBy.js _baseProperty.js _basePropertyDeep.js _basePropertyOf.js _basePullAll.js _basePullAt.js _baseRandom.js _baseRange.js _baseReduce.js _baseRepeat.js _baseRest.js _baseSample.js _baseSampleSize.js _baseSet.js _baseSetData.js _baseSetToString.js _baseShuffle.js _baseSlice.js _baseSome.js _baseSortBy.js _baseSortedIndex.js _baseSortedIndexBy.js _baseSortedUniq.js _baseSum.js _baseTimes.js _baseToNumber.js _baseToPairs.js _baseToString.js _baseTrim.js _baseUnary.js _baseUniq.js _baseUnset.js _baseUpdate.js _baseValues.js _baseWhile.js _baseWrapperValue.js _baseXor.js _baseZipObject.js _cacheHas.js _castArrayLikeObject.js _castFunction.js _castPath.js _castRest.js _castSlice.js _charsEndIndex.js _charsStartIndex.js _cloneArrayBuffer.js _cloneBuffer.js _cloneDataView.js _cloneRegExp.js _cloneSymbol.js _cloneTypedArray.js _compareAscending.js _compareMultiple.js _composeArgs.js _composeArgsRight.js _copyArray.js _copyObject.js _copySymbols.js _copySymbolsIn.js _coreJsData.js _countHolders.js _createAggregator.js _createAssigner.js _createBaseEach.js _createBaseFor.js _createBind.js _createCaseFirst.js _createCompounder.js _createCtor.js _createCurry.js _createFind.js _createFlow.js _createHybrid.js _createInverter.js _createMathOperation.js _createOver.js _createPadding.js _createPartial.js _createRange.js _createRecurry.js _createRelationalOperation.js _createRound.js _createSet.js _createToPairs.js _createWrap.js _customDefaultsAssignIn.js _customDefaultsMerge.js _customOmitClone.js _deburrLetter.js _defineProperty.js _equalArrays.js _equalByTag.js _equalObjects.js _escapeHtmlChar.js _escapeStringChar.js _flatRest.js _freeGlobal.js _getAllKeys.js _getAllKeysIn.js _getData.js _getFuncName.js _getHolder.js _getMapData.js _getMatchData.js _getNative.js _getPrototype.js _getRawTag.js _getSymbols.js _getSymbolsIn.js _getTag.js _getValue.js _getView.js _getWrapDetails.js _hasPath.js _hasUnicode.js _hasUnicodeWord.js _hashClear.js _hashDelete.js _hashGet.js _hashHas.js _hashSet.js _initCloneArray.js _initCloneByTag.js _initCloneObject.js _insertWrapDetails.js _isFlattenable.js _isIndex.js _isIterateeCall.js _isKey.js _isKeyable.js _isLaziable.js _isMaskable.js _isMasked.js _isPrototype.js _isStrictComparable.js _iteratorToArray.js _lazyClone.js _lazyReverse.js _lazyValue.js _listCacheClear.js _listCacheDelete.js _listCacheGet.js _listCacheHas.js _listCacheSet.js _mapCacheClear.js _mapCacheDelete.js _mapCacheGet.js _mapCacheHas.js _mapCacheSet.js _mapToArray.js _matchesStrictComparable.js _memoizeCapped.js _mergeData.js _metaMap.js _nativeCreate.js _nativeKeys.js _nativeKeysIn.js _nodeUtil.js _objectToString.js _overArg.js _overRest.js _parent.js _reEscape.js _reEvaluate.js _reInterpolate.js _realNames.js _reorder.js _replaceHolders.js _root.js _safeGet.js _setCacheAdd.js _setCacheHas.js _setData.js _setToArray.js _setToPairs.js _setToString.js _setWrapToString.js _shortOut.js _shuffleSelf.js _stackClear.js _stackDelete.js _stackGet.js _stackHas.js _stackSet.js _strictIndexOf.js _strictLastIndexOf.js _stringSize.js _stringToArray.js _stringToPath.js _toKey.js _toSource.js _trimmedEndIndex.js _unescapeHtmlChar.js _unicodeSize.js _unicodeToArray.js _unicodeWords.js _updateWrapDetails.js _wrapperClone.js add.js after.js array.js ary.js assign.js assignIn.js assignInWith.js assignWith.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js concat.js cond.js conforms.js conformsTo.js constant.js core.js core.min.js countBy.js create.js curry.js curryRight.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsDeep.js defer.js delay.js difference.js differenceBy.js differenceWith.js divide.js drop.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js escape.js escapeRegExp.js every.js extend.js extendWith.js fill.js filter.js find.js findIndex.js findKey.js findLast.js findLastIndex.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fp.js fp F.js T.js __.js _baseConvert.js _convertBrowser.js _falseOptions.js _mapping.js _util.js add.js after.js all.js allPass.js always.js any.js anyPass.js apply.js array.js ary.js assign.js assignAll.js assignAllWith.js assignIn.js assignInAll.js assignInAllWith.js assignInWith.js assignWith.js assoc.js assocPath.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js complement.js compose.js concat.js cond.js conforms.js conformsTo.js constant.js contains.js convert.js countBy.js create.js curry.js curryN.js curryRight.js curryRightN.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsAll.js defaultsDeep.js defaultsDeepAll.js defer.js delay.js difference.js differenceBy.js differenceWith.js dissoc.js dissocPath.js divide.js drop.js dropLast.js dropLastWhile.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js equals.js escape.js escapeRegExp.js every.js extend.js extendAll.js extendAllWith.js extendWith.js fill.js filter.js find.js findFrom.js findIndex.js findIndexFrom.js findKey.js findLast.js findLastFrom.js findLastIndex.js findLastIndexFrom.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fromPairs.js function.js functions.js functionsIn.js get.js getOr.js groupBy.js gt.js gte.js has.js hasIn.js head.js identical.js identity.js inRange.js includes.js includesFrom.js indexBy.js indexOf.js indexOfFrom.js init.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invertObj.js invoke.js invokeArgs.js invokeArgsMap.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js juxt.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lastIndexOfFrom.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeAll.js mergeAllWith.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js nAry.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitAll.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js pad.js padChars.js padCharsEnd.js padCharsStart.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js path.js pathEq.js pathOr.js paths.js pick.js pickAll.js pickBy.js pipe.js placeholder.js plant.js pluck.js prop.js propEq.js propOr.js property.js propertyOf.js props.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rangeStep.js rangeStepRight.js rearg.js reduce.js reduceRight.js reject.js remove.js repeat.js replace.js rest.js restFrom.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js spreadFrom.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js symmetricDifference.js symmetricDifferenceBy.js symmetricDifferenceWith.js tail.js take.js takeLast.js takeLastWhile.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimChars.js trimCharsEnd.js trimCharsStart.js trimEnd.js trimStart.js truncate.js unapply.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unnest.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js useWith.js util.js value.js valueOf.js values.js valuesIn.js where.js whereEq.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipAll.js zipObj.js zipObject.js zipObjectDeep.js zipWith.js fromPairs.js function.js functions.js functionsIn.js get.js groupBy.js gt.js gte.js has.js hasIn.js head.js identity.js inRange.js includes.js index.js indexOf.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invoke.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lodash.js lodash.min.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js package.json pad.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js pick.js pickBy.js plant.js property.js propertyOf.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rearg.js reduce.js reduceRight.js reject.js release.md remove.js repeat.js replace.js rest.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js tail.js take.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimEnd.js trimStart.js truncate.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js util.js value.js valueOf.js values.js valuesIn.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipObject.js zipObjectDeep.js zipWith.js lowercase-keys index.d.ts index.js package.json readme.md lru-cache README.md index.js package.json make-error README.md dist make-error.js index.d.ts index.js package.json map-age-cleaner dist index.d.ts index.js package.json readme.md matcher index.d.ts index.js package.json readme.md md5-hex browser.js index.d.ts index.js package.json readme.md mem dist index.d.ts index.js package.json readme.md merge2 README.md index.js package.json micromatch README.md index.js package.json mimic-fn index.d.ts index.js package.json readme.md mimic-response index.js package.json readme.md minimatch README.md minimatch.js package.json minipass README.md index.d.ts index.js package.json minizlib README.md constants.js index.js package.json mkdirp CHANGELOG.md bin cmd.js index.js lib find-made.js mkdirp-manual.js mkdirp-native.js opts-arg.js path-arg.js use-native.js package.json ms index.js license.md package.json readme.md mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json near-api-js README.md browser-exports.js dist near-api-js.js near-api-js.min.js lib account.d.ts account.js account_creator.d.ts account_creator.js account_multisig.d.ts account_multisig.js browser-connect.d.ts browser-connect.js browser-index.d.ts browser-index.js common-index.d.ts common-index.js connect.d.ts connect.js connection.d.ts connection.js constants.d.ts constants.js contract.d.ts contract.js generated rpc_error_schema.json index.d.ts index.js key_stores browser-index.d.ts browser-index.js browser_local_storage_key_store.d.ts browser_local_storage_key_store.js in_memory_key_store.d.ts in_memory_key_store.js index.d.ts index.js keystore.d.ts keystore.js merge_key_store.d.ts merge_key_store.js unencrypted_file_system_keystore.d.ts unencrypted_file_system_keystore.js near.d.ts near.js providers index.d.ts index.js json-rpc-provider.d.ts json-rpc-provider.js provider.d.ts provider.js res error_messages.d.ts error_messages.json signer.d.ts signer.js transaction.d.ts transaction.js utils enums.d.ts enums.js errors.d.ts errors.js exponential-backoff.d.ts exponential-backoff.js format.d.ts format.js index.d.ts index.js key_pair.d.ts key_pair.js network.d.ts network.js rpc_errors.d.ts rpc_errors.js serialize.d.ts serialize.js setup-node-fetch.d.ts setup-node-fetch.js web.d.ts web.js validators.d.ts validators.js wallet-account.d.ts wallet-account.js node_modules bn.js CHANGELOG.md README.md lib bn.js package.json borsh .eslintrc.yml .travis.yml LICENSE-MIT.txt README.md borsh-ts .eslintrc.yml index.ts test .eslintrc.yml fuzz borsh-roundtrip.js transaction-example enums.d.ts enums.js key_pair.d.ts key_pair.js serialize.d.ts serialize.js signer.d.ts signer.js transaction.d.ts transaction.js serialize.test.js lib index.d.ts index.js package.json tsconfig.json package.json near-sandbox dist getBinary.d.ts getBinary.js index.d.ts index.js install.d.ts install.js run.d.ts run.js test.d.ts uninstall.d.ts uninstall.js utils.d.ts utils.js getBinary.js install.js package.json run.js uninstall.js near-units README.md dist bn.d.ts bn.js cli.d.ts cli.js gas.d.ts gas.js index.d.ts index.js near.d.ts near.js parse.d.ts parse.js utils.d.ts utils.js package.json near-workspaces README.md dist account account-manager.d.ts account-manager.js account.d.ts account.js index.d.ts index.js near-account-manager.d.ts near-account-manager.js near-account.d.ts near-account.js utils.d.ts utils.js contract-state.d.ts contract-state.js index.d.ts index.js internal-utils.d.ts internal-utils.js jsonrpc.d.ts jsonrpc.js record builder.d.ts builder.js index.d.ts index.js types.d.ts types.js server index.d.ts index.js server.d.ts server.js transaction-result.d.ts transaction-result.js transaction.d.ts transaction.js types.d.ts types.js utils.d.ts utils.js worker.d.ts worker.js package.json scripts install.js tsconfig.json node-fetch LICENSE.md README.md browser.js lib index.es.js index.js package.json node-port-check README.md definitions index.d.ts lib index.js package.json readme index.js nextVersion.txt shared content.md header.md history.md tsconfig.json nofilter LICENSE.md README.md lib index.js package.json types index.d.ts normalize-path README.md index.js package.json normalize-url index.d.ts index.js package.json readme.md o3 README.md index.js lib Class.js abstractMethod.js index.js package.json once README.md once.js package.json p-cancelable index.d.ts index.js package.json readme.md p-defer index.js package.json readme.md p-event index.d.ts index.js package.json readme.md p-limit index.d.ts index.js package.json readme.md p-locate index.d.ts index.js package.json readme.md p-map index.d.ts index.js package.json readme.md p-timeout index.d.ts index.js package.json readme.md parse-ms index.d.ts index.js package.json readme.md path-exists index.d.ts index.js package.json readme.md path-is-absolute index.js package.json readme.md path-type index.d.ts index.js package.json readme.md picomatch CHANGELOG.md README.md index.js lib constants.js parse.js picomatch.js scan.js utils.js package.json pkg-conf index.d.ts index.js package.json readme.md plur index.d.ts index.js package.json readme.md pretty-ms index.d.ts index.js package.json readme.md promisify-child-process LICENSE.md README.md index.d.ts package.json pump .travis.yml README.md index.js package.json test-browser.js test-node.js pure-uuid Gruntfile.js README.md package.json uuid.d.ts uuid.js uuid.min.js uuid.test.js queue-microtask README.md index.d.ts index.js package.json quick-lru index.d.ts index.js package.json readme.md readdirp README.md index.d.ts index.js package.json require-directory .travis.yml index.js package.json resolve-alpn README.md index.js package.json resolve-cwd index.d.ts index.js package.json readme.md resolve-from index.d.ts index.js package.json readme.md responselike README.md package.json src index.js reusify .coveralls.yml .travis.yml README.md benchmarks createNoCodeFunction.js fib.js reuseNoCodeFunction.js package.json reusify.js test.js rimraf CHANGELOG.md README.md bin.js package.json rimraf.js run-parallel README.md index.js package.json safe-buffer README.md index.d.ts index.js package.json semver README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js serialize-error index.d.ts index.js package.json readme.md setprototypeof README.md index.d.ts index.js package.json test index.js signal-exit LICENSE.txt README.md index.js package.json signals.js slash index.d.ts index.js package.json readme.md slice-ansi index.js package.json readme.md sprintf-js README.md bower.json demo angular.html dist angular-sprintf.min.js sprintf.min.js gruntfile.js package.json src angular-sprintf.js sprintf.js test test.js stack-utils LICENSE.md index.js node_modules escape-string-regexp index.d.ts index.js package.json readme.md package.json readme.md statuses HISTORY.md README.md codes.json index.js package.json string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md supertap dist index.d.ts index.js package.json readme.md tar README.md index.js lib create.js extract.js get-write-flag.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js normalize-unicode.js normalize-windows-path.js pack.js parse.js path-reservations.js pax.js read-entry.js replace.js strip-absolute-path.js strip-trailing-slashes.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json temp-dir index.d.ts index.js package.json readme.md text-encoding-utf-8 LICENSE.md README.md lib encoding.js encoding.lib.js package.json src encoding.js polyfill.js time-zone index.js package.json readme.md to-regex-range README.md index.js package.json toidentifier HISTORY.md README.md index.js package.json tr46 index.js lib mappingTable.json package.json ts-node README.md dist-raw NODE-LICENSE.md README.md node-internal-constants.js node-internal-errors.js node-internal-modules-cjs-helpers.js node-internal-modules-cjs-loader.js node-internal-modules-esm-get_format.js node-internal-modules-esm-resolve.js node-internal-modules-package_json_reader.js node-internal-repl-await.js node-internalBinding-fs.js node-nativemodule.js node-options.js node-primordials.js runmain-hack.js dist bin-cwd.d.ts bin-cwd.js bin-esm.d.ts bin-esm.js bin-script-deprecated.d.ts bin-script-deprecated.js bin-script.d.ts bin-script.js bin-transpile.d.ts bin-transpile.js bin.d.ts bin.js child argv-payload.d.ts argv-payload.js child-entrypoint.d.ts child-entrypoint.js child-loader.d.ts child-loader.js child-require.d.ts child-require.js spawn-child.d.ts spawn-child.js cjs-resolve-hooks.d.ts cjs-resolve-hooks.js configuration.d.ts configuration.js esm.d.ts esm.js file-extensions.d.ts file-extensions.js index.d.ts index.js module-type-classifier.d.ts module-type-classifier.js node-module-type-classifier.d.ts node-module-type-classifier.js repl.d.ts repl.js resolver-functions.d.ts resolver-functions.js transpilers swc.d.ts swc.js types.d.ts types.js ts-compiler-types.d.ts ts-compiler-types.js ts-internals.d.ts ts-internals.js ts-transpile-module.d.ts ts-transpile-module.js tsconfig-schema.d.ts tsconfig-schema.js tsconfigs.d.ts tsconfigs.js util.d.ts util.js node10 tsconfig.json node12 tsconfig.json node14 tsconfig.json node16 tsconfig.json package.json register files.js index.js transpile-only.js type-check.js transpilers swc-experimental.js swc.js tsconfig.schema.json tsconfig.schemastore-schema.json tweetnacl AUTHORS.md CHANGELOG.md PULL_REQUEST_TEMPLATE.md README.md nacl-fast.js nacl-fast.min.js nacl.d.ts nacl.js nacl.min.js package.json type-fest index.d.ts package.json readme.md source async-return-type.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts except.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts value-of.d.ts typescript LICENSE.txt README.md SECURITY.md ThirdPartyNoticeText.txt lib README.md cancellationToken.js cs diagnosticMessages.generated.json de diagnosticMessages.generated.json dynamicImportCompat.js es diagnosticMessages.generated.json fr diagnosticMessages.generated.json it diagnosticMessages.generated.json ja diagnosticMessages.generated.json ko diagnosticMessages.generated.json lib.d.ts lib.dom.d.ts lib.dom.iterable.d.ts lib.es2015.collection.d.ts lib.es2015.core.d.ts lib.es2015.d.ts lib.es2015.generator.d.ts lib.es2015.iterable.d.ts lib.es2015.promise.d.ts lib.es2015.proxy.d.ts lib.es2015.reflect.d.ts lib.es2015.symbol.d.ts lib.es2015.symbol.wellknown.d.ts lib.es2016.array.include.d.ts lib.es2016.d.ts lib.es2016.full.d.ts lib.es2017.d.ts lib.es2017.full.d.ts lib.es2017.intl.d.ts lib.es2017.object.d.ts lib.es2017.sharedmemory.d.ts lib.es2017.string.d.ts lib.es2017.typedarrays.d.ts lib.es2018.asyncgenerator.d.ts lib.es2018.asynciterable.d.ts lib.es2018.d.ts lib.es2018.full.d.ts lib.es2018.intl.d.ts lib.es2018.promise.d.ts lib.es2018.regexp.d.ts lib.es2019.array.d.ts lib.es2019.d.ts lib.es2019.full.d.ts lib.es2019.intl.d.ts lib.es2019.object.d.ts lib.es2019.string.d.ts lib.es2019.symbol.d.ts lib.es2020.bigint.d.ts lib.es2020.d.ts lib.es2020.date.d.ts lib.es2020.full.d.ts lib.es2020.intl.d.ts lib.es2020.number.d.ts lib.es2020.promise.d.ts lib.es2020.sharedmemory.d.ts lib.es2020.string.d.ts lib.es2020.symbol.wellknown.d.ts lib.es2021.d.ts lib.es2021.full.d.ts lib.es2021.intl.d.ts lib.es2021.promise.d.ts lib.es2021.string.d.ts lib.es2021.weakref.d.ts lib.es2022.array.d.ts lib.es2022.d.ts lib.es2022.error.d.ts lib.es2022.full.d.ts lib.es2022.intl.d.ts lib.es2022.object.d.ts lib.es2022.sharedmemory.d.ts lib.es2022.string.d.ts lib.es5.d.ts lib.es6.d.ts lib.esnext.d.ts lib.esnext.full.d.ts lib.esnext.intl.d.ts lib.esnext.promise.d.ts lib.esnext.string.d.ts lib.esnext.weakref.d.ts lib.scripthost.d.ts lib.webworker.d.ts lib.webworker.importscripts.d.ts lib.webworker.iterable.d.ts pl diagnosticMessages.generated.json protocol.d.ts pt-br diagnosticMessages.generated.json ru diagnosticMessages.generated.json tr diagnosticMessages.generated.json tsserverlibrary.d.ts typesMap.json typescript.d.ts typescriptServices.d.ts watchGuard.js zh-cn diagnosticMessages.generated.json zh-tw diagnosticMessages.generated.json package.json u3 README.md index.js lib cache.js eachCombination.js index.js package.json universalify README.md index.js package.json v8-compile-cache-lib CHANGELOG.md README.md package.json v8-compile-cache.d.ts v8-compile-cache.js webidl-conversions LICENSE.md README.md lib index.js package.json well-known-symbols README.md index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js public-api.js url-state-machine.js utils.js package.json wrap-ansi index.js node_modules ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js is-fullwidth-code-point index.d.ts index.js package.json readme.md string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md package.json readme.md wrappy README.md package.json wrappy.js write-file-atomic LICENSE.md README.md lib index.js package.json y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js maybe-async-result.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json cs.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json uk_UA.json uz.json zh_CN.json zh_TW.json node_modules ansi-regex index.d.ts index.js package.json readme.md emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js is-fullwidth-code-point index.d.ts index.js package.json readme.md string-width index.d.ts index.js package.json readme.md strip-ansi index.d.ts index.js package.json readme.md package.json yn index.d.ts index.js lenient.js package.json readme.md yocto-queue index.d.ts index.js package.json readme.md package-lock.json package.json src main.ava.ts node_modules .bin sha.js .package-lock.json @babel code-frame README.md lib index.js package.json helper-validator-identifier README.md lib identifier.js index.js keyword.js package.json scripts generate-identifier-regex.js highlight README.md lib index.js node_modules ansi-styles index.js package.json readme.md chalk index.js package.json readme.md templates.js types index.d.ts color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js escape-string-regexp index.js package.json readme.md has-flag index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json @jest environment build index.d.ts index.js package.json fake-timers build index.d.ts index.js legacyFakeTimers.d.ts legacyFakeTimers.js modernFakeTimers.d.ts modernFakeTimers.js package.json types build Circus.d.ts Circus.js Config.d.ts Config.js Global.d.ts Global.js TestResult.d.ts TestResult.js Transform.d.ts Transform.js index.d.ts index.js package.json @ledgerhq devices CHANGELOG.md README.md jest.config.ts lib-es ble receiveAPDU.d.ts receiveAPDU.js sendAPDU.d.ts sendAPDU.js hid-framing.d.ts hid-framing.js index.d.ts index.js scrambling.d.ts scrambling.js lib ble receiveAPDU.d.ts receiveAPDU.js sendAPDU.d.ts sendAPDU.js hid-framing.d.ts hid-framing.js index.d.ts index.js scrambling.d.ts scrambling.js package.json src ble receiveAPDU.ts sendAPDU.ts hid-framing.ts index.ts scrambling.ts tests identifyTargetId.test.ts tsconfig.json errors CHANGELOG.md README.md jest.config.ts lib-es deserializeError.test.d.ts deserializeError.test.js helpers.d.ts helpers.js index.d.ts index.js index.test.d.ts index.test.js lib deserializeError.test.d.ts deserializeError.test.js helpers.d.ts helpers.js index.d.ts index.js index.test.d.ts index.test.js package.json src deserializeError.test.ts helpers.ts index.test.ts index.ts tsconfig.json hw-transport-node-hid-noevents CHANGELOG.md README.md jest.config.ts lib-es TransportNodeHid.d.ts TransportNodeHid.js lib TransportNodeHid.d.ts TransportNodeHid.js node_modules decompress-response index.d.ts index.js package.json readme.md detect-libc README.md bin detect-libc.js lib detect-libc.js package.json mimic-response index.d.ts index.js package.json readme.md node-abi .github workflows update-abi.yml .travis.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js package.json scripts update-abi-registry.js test index.js node-hid Publishing.md README.md hidapi .appveyor.yml .builds alpine.yml archlinux.yml fedora-mingw.yml freebsd.yml .cirrus.yml AUTHORS.txt HACKING.txt LICENSE-bsd.txt LICENSE-gpl3.txt LICENSE-orig.txt LICENSE.txt README.md hidapi hidapi.h hidtest test.c libusb hid.c linux hid.c mac hid.c testgui copy_to_bundle.sh mac_support.h test.cpp testgui.sln windows hid.c hidapi.sln nodehid.js package.json src buzzers.js powermate.js show-devices.js test-bigredbutton.js test-blink1.js test-buzzers.js test-ci.js test-macbookprotrackpad.js test-powermate.js test-ps3-rumbleled.js test-ps3.js test-teensyrawhid.js test-tinyusbrawhid.js testReadSync.js prebuild-install CHANGELOG.md CONTRIBUTING.md README.md asset.js bin.js download.js error.js help.txt index.js log.js package.json proxy.js rc.js util.js semver CHANGELOG.md README.md package.json semver.js simple-get README.md index.js package.json package.json src TransportNodeHid.ts tsconfig.json hw-transport-node-hid CHANGELOG.md README.md jest.config.ts lib-es TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js lib TransportNodeHid.d.ts TransportNodeHid.js listenDevices.d.ts listenDevices.js package.json src TransportNodeHid.ts listenDevices.ts tsconfig.json hw-transport-u2f README.md lib-es TransportU2F.js lib TransportU2F.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportU2F.js hw-transport-webhid README.md flow webhid.js lib-es TransportWebHID.js lib TransportWebHID.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportWebHID.js hw-transport-webusb README.md flow webusb.js lib-es TransportWebUSB.js webusb.js lib TransportWebUSB.js webusb.js node_modules @ledgerhq devices README.md lib-es ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js lib ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js package.json src ble receiveAPDU.js sendAPDU.js hid-framing.js index.js scrambling.js errors README.md dist helpers.d.ts index.cjs.js index.d.ts index.js package.json src helpers.ts index.ts hw-transport README.md lib-es Transport.js lib Transport.js package.json src Transport.js logs README.md lib-es index.js lib index.js package.json src index.js package.json src TransportWebUSB.js webusb.js hw-transport CHANGELOG.md README.md jest.config.ts lib-es Transport.d.ts Transport.js lib Transport.d.ts Transport.js package.json src Transport.ts tsconfig.json logs CHANGELOG.md README.md jest.config.ts lib-es index.d.ts index.js lib index.d.ts index.js package.json src index.ts tsconfig.json @segment loosely-validate-event HISTORY.md README.md circle.yml index.js package.json test.js @sindresorhus is dist index.d.ts index.js package.json readme.md @sinonjs commons README.md lib called-in-order.js called-in-order.test.js class-name.js class-name.test.js deprecated.js deprecated.test.js every.js every.test.js function-name.js function-name.test.js global.js global.test.js index.js index.test.js order-by-first-call.js order-by-first-call.test.js prototypes README.md array.js copy-prototype-methods.js copy-prototype-methods.test.js function.js index.js index.test.js map.js object.js set.js string.js throws-on-proto.js type-of.js type-of.test.js value-to-string.js value-to-string.test.js package.json types called-in-order.d.ts class-name.d.ts deprecated.d.ts every.d.ts function-name.d.ts global.d.ts index.d.ts order-by-first-call.d.ts prototypes array.d.ts copy-prototype-methods.d.ts function.d.ts index.d.ts map.d.ts object.d.ts set.d.ts string.d.ts throws-on-proto.d.ts type-of.d.ts value-to-string.d.ts fake-timers CHANGELOG.md README.md package.json src fake-timers-src.js @szmarczak http-timer README.md package.json source index.js @types istanbul-lib-coverage README.md index.d.ts package.json istanbul-lib-report README.md index.d.ts package.json istanbul-reports README.md index.d.ts package.json node README.md assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts package.json path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts ts4.8 assert.d.ts assert strict.d.ts async_hooks.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts diagnostics_channel.d.ts dns.d.ts dns promises.d.ts dom-events.d.ts domain.d.ts events.d.ts fs.d.ts fs promises.d.ts globals.d.ts globals.global.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts readline promises.d.ts repl.d.ts stream.d.ts stream consumers.d.ts promises.d.ts web.d.ts string_decoder.d.ts test.d.ts timers.d.ts timers promises.d.ts tls.d.ts trace_events.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts wasi.d.ts worker_threads.d.ts zlib.d.ts stack-utils README.md index.d.ts package.json yargs-parser README.md index.d.ts package.json yargs README.md helpers.d.ts index.d.ts package.json yargs.d.ts analytics-node History.md index.js package.json readme.md ansi-align CHANGELOG.md README.md index.js package.json ansi-regex index.d.ts index.js package.json readme.md ansi-styles index.d.ts index.js package.json readme.md aproba README.md index.js package.json are-we-there-yet CHANGES.md README.md index.js node_modules readable-stream .travis.yml CONTRIBUTING.md GOVERNANCE.md README.md doc wg-meetings 2015-01-30.md duplex-browser.js duplex.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams BufferList.js destroy.js stream-browser.js stream.js package.json passthrough.js readable-browser.js readable.js transform.js writable-browser.js writable.js safe-buffer README.md index.d.ts index.js package.json string_decoder .travis.yml README.md lib string_decoder.js package.json package.json tracker-base.js tracker-group.js tracker-stream.js tracker.js ascii-table .travis.yml ascii-table.js ascii-table.min.js bower.json example simple.js simple.txt index.js package.json readme.md test.js asynckit README.md bench.js index.js lib abort.js async.js defer.js iterate.js readable_asynckit.js readable_parallel.js readable_serial.js readable_serial_ordered.js state.js streamify.js terminator.js package.json parallel.js serial.js serialOrdered.js stream.js axios-retry CHANGELOG.md README.md es index.js index.d.ts index.js lib index.js package.json axios CHANGELOG.md README.md SECURITY.md UPGRADE_GUIDE.md dist axios.js axios.min.js index.d.ts index.js lib adapters README.md http.js xhr.js axios.js cancel CancelToken.js CanceledError.js isCancel.js core Axios.js AxiosError.js InterceptorManager.js README.md buildFullPath.js dispatchRequest.js mergeConfig.js settle.js transformData.js defaults env FormData.js index.js transitional.js env README.md data.js helpers README.md bind.js buildURL.js combineURLs.js cookies.js deprecatedMethod.js isAbsoluteURL.js isAxiosError.js isURLSameOrigin.js normalizeHeaderName.js null.js parseHeaders.js parseProtocol.js spread.js toFormData.js validator.js utils.js package.json tsconfig.json tslint.json balanced-match .github FUNDING.yml LICENSE.md README.md index.js package.json base-x LICENSE.md README.md package.json src index.d.ts index.js base64-js README.md base64js.min.js index.d.ts index.js package.json bindings LICENSE.md README.md bindings.js package.json bip39-light .travis.yml README.md index.js package.json test index.js readme.js vectors.json wordlist.json wordlists english.json bip39 CHANGELOG.md README.md node_modules @types node README.md assert.d.ts async_hooks.d.ts base.d.ts buffer.d.ts child_process.d.ts cluster.d.ts console.d.ts constants.d.ts crypto.d.ts dgram.d.ts dns.d.ts domain.d.ts events.d.ts fs.d.ts globals.d.ts http.d.ts http2.d.ts https.d.ts index.d.ts inspector.d.ts module.d.ts net.d.ts os.d.ts package.json path.d.ts perf_hooks.d.ts process.d.ts punycode.d.ts querystring.d.ts readline.d.ts repl.d.ts stream.d.ts string_decoder.d.ts timers.d.ts tls.d.ts trace_events.d.ts ts3.2 globals.d.ts index.d.ts util.d.ts tty.d.ts url.d.ts util.d.ts v8.d.ts vm.d.ts worker_threads.d.ts zlib.d.ts package.json src _wordlists.js index.js wordlists chinese_simplified.json chinese_traditional.json english.json french.json italian.json japanese.json korean.json spanish.json types _wordlists.d.ts index.d.ts wordlists.d.ts bl .travis.yml BufferList.js LICENSE.md README.md bl.js package.json test convert.js indexOf.js isBufferList.js test.js bn.js README.md lib bn.js package.json borsh .eslintrc.yml .travis.yml LICENSE-MIT.txt README.md borsh-ts .eslintrc.yml index.ts test .eslintrc.yml fuzz borsh-roundtrip.js transaction-example enums.d.ts enums.js key_pair.d.ts key_pair.js serialize.d.ts serialize.js signer.d.ts signer.js transaction.d.ts transaction.js serialize.test.js lib index.d.ts index.js package.json tsconfig.json boxen index.d.ts index.js package.json readme.md brace-expansion README.md index.js package.json braces CHANGELOG.md README.md index.js lib compile.js constants.js expand.js parse.js stringify.js utils.js package.json bs58 CHANGELOG.md README.md index.js package.json buffer AUTHORS.md README.md index.d.ts index.js package.json cacheable-request README.md node_modules get-stream buffer-stream.js index.d.ts index.js package.json readme.md lowercase-keys index.d.ts index.js package.json readme.md package.json src index.js camelcase index.d.ts index.js package.json readme.md capability Array.prototype.forEach.js Array.prototype.map.js Error.captureStackTrace.js Error.prototype.stack.js Function.prototype.bind.js Object.create.js Object.defineProperties.js Object.defineProperty.js Object.prototype.hasOwnProperty.js README.md arguments.callee.caller.js es5.js index.js lib CapabilityDetector.js definitions.js index.js package.json strict mode.js chalk index.d.ts package.json readme.md source index.js templates.js util.js charenc README.js charenc.js package.json chownr README.md chownr.js package.json ci-info CHANGELOG.md README.md index.js package.json vendors.json cipher-base .travis.yml README.md index.js package.json test.js cli-boxes boxes.json index.d.ts index.js package.json readme.md cliui CHANGELOG.md LICENSE.txt README.md build lib index.js string-utils.js package.json clone-response README.md node_modules mimic-response index.js package.json readme.md package.json src index.js code-point-at index.js package.json readme.md color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name README.md index.js package.json combined-stream Readme.md lib combined_stream.js package.json component-type Readme.md component.json index.js package.json test index.html mocha.css mocha.js tests.js concat-map .travis.yml example map.js index.js package.json test map.js configstore index.js package.json readme.md console-control-strings README.md index.js package.json core-util-is README.md lib util.js package.json create-hash .travis.yml README.md browser.js index.js md5.js package.json test.js create-hmac README.md browser.js index.js legacy.js package.json crypt crypt.js package.json crypto-random-string index.d.ts index.js package.json readme.md debug README.md node_modules ms index.js license.md package.json readme.md package.json src browser.js common.js index.js node.js decompress-response index.d.ts index.js package.json readme.md deep-extend CHANGELOG.md README.md index.js lib deep-extend.js package.json deep-is .travis.yml example cmp.js index.js package.json test NaN.js cmp.js neg-vs-pos-0.js defer-to-connect README.md dist index.d.ts index.js package.json define-lazy-prop index.d.ts index.js package.json readme.md delayed-stream Readme.md lib delayed_stream.js package.json delegates History.md Readme.md index.js package.json test index.js depd History.md Readme.md index.js lib browser index.js package.json detect-libc README.md index.d.ts lib detect-libc.js process.js package.json dot-prop index.d.ts index.js package.json readme.md duplexer3 index.js package.json readme.md emoji-regex LICENSE-MIT.txt README.md es2015 index.js text.js index.d.ts index.js package.json text.js end-of-stream README.md index.js package.json error-polyfill README.md index.js lib index.js non-v8 Frame.js FrameStringParser.js FrameStringSource.js index.js prepareStackTrace.js unsupported.js v8.js package.json escalade dist index.js index.d.ts package.json readme.md sync index.d.ts index.js escape-goat index.d.ts index.js package.json readme.md escape-string-regexp index.d.ts index.js package.json readme.md events .airtap.yml .github FUNDING.yml .travis.yml History.md Readme.md events.js package.json security.md tests add-listeners.js check-listener-leaks.js common.js errors.js events-list.js events-once.js index.js legacy-compat.js listener-count.js listeners-side-effects.js listeners.js max-listeners.js method-names.js modify-in-emit.js num-args.js once.js prepend.js remove-all-listeners.js remove-listeners.js set-max-listeners-side-effects.js special-event-names.js subclass.js symbols.js expand-template .travis.yml README.md index.js package.json test.js file-uri-to-path .travis.yml History.md README.md index.d.ts index.js package.json test test.js tests.json fill-range README.md index.js package.json flagged-respawn README.md index.js lib is-v8flags.js remover.js reorder.js respawn.js package.json follow-redirects README.md debug.js http.js https.js index.js package.json form-data Readme.md index.d.ts lib browser.js form_data.js populate.js package.json fs-constants README.md browser.js index.js package.json fs.realpath README.md index.js old.js package.json gauge CHANGELOG.md README.md base-theme.js error.js has-color.js index.js node_modules ansi-regex index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.js package.json readme.md package.json plumbing.js process.js progress-bar.js render-template.js set-immediate.js set-interval.js spin.js template-item.js theme-set.js themes.js wide-truncate.js get-caller-file LICENSE.md README.md index.d.ts index.js package.json get-stream buffer-stream.js index.js package.json readme.md github-from-package .travis.yml example package.json url.js index.js package.json test a.json b.json c.json d.json e.json url.js glob README.md common.js glob.js package.json sync.js global-dirs index.d.ts index.js node_modules ini README.md ini.js package.json package.json readme.md got node_modules decompress-response index.js package.json readme.md mimic-response index.js package.json readme.md package.json readme.md source as-promise.js as-stream.js create.js errors.js get-response.js index.js known-hook-events.js merge.js normalize-arguments.js progress.js request-as-event-emitter.js utils deep-freeze.js get-body-size.js is-form-data.js timed-out.js url-to-options.js graceful-fs README.md clone.js graceful-fs.js legacy-streams.js package.json polyfills.js has-flag index.d.ts index.js package.json readme.md has-unicode README.md index.js package.json has-yarn index.d.ts index.js package.json readme.md hash-base README.md index.js package.json homedir-polyfill README.md index.js package.json polyfill.js http-cache-semantics README.md index.js package.json http-errors HISTORY.md README.md index.js node_modules depd History.md Readme.md index.js lib browser index.js compat callsite-tostring.js event-listener-count.js index.js package.json package.json ieee754 README.md index.d.ts index.js package.json import-lazy index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json ini README.md ini.js package.json ip-regex index.d.ts index.js package.json readme.md is-buffer README.md index.js package.json test basic.js is-ci CHANGELOG.md README.md bin.js index.js package.json is-docker cli.js index.d.ts index.js package.json readme.md is-fullwidth-code-point index.d.ts index.js package.json readme.md is-installed-globally index.d.ts index.js package.json readme.md is-npm index.d.ts index.js package.json readme.md is-number README.md index.js package.json is-obj index.d.ts index.js package.json readme.md is-path-inside index.d.ts index.js package.json readme.md is-retry-allowed index.js package.json readme.md is-typedarray LICENSE.md README.md index.js package.json test.js is-url .travis.yml History.md Readme.md index.js package.json test index.js is-wsl index.d.ts index.js package.json readme.md is-yarn-global .travis.yml README.md index.js package.json is2 README.md index.d.ts index.js package.json tests.js isarray .travis.yml README.md component.json index.js package.json test.js jest-environment-node build index.d.ts index.js package.json jest-message-util build index.d.ts index.js types.d.ts types.js package.json jest-mock README.md build index.d.ts index.js package.json jest-util build ErrorWithStack.d.ts ErrorWithStack.js clearLine.d.ts clearLine.js convertDescriptorToString.d.ts convertDescriptorToString.js createDirectory.d.ts createDirectory.js createProcessObject.d.ts createProcessObject.js deepCyclicCopy.d.ts deepCyclicCopy.js formatTime.d.ts formatTime.js globsToMatcher.d.ts globsToMatcher.js index.d.ts index.js installCommonGlobals.d.ts installCommonGlobals.js interopRequireDefault.d.ts interopRequireDefault.js isInteractive.d.ts isInteractive.js isPromise.d.ts isPromise.js pluralize.d.ts pluralize.js preRunMessage.d.ts preRunMessage.js replacePathSepForGlob.d.ts replacePathSepForGlob.js requireOrImportModule.d.ts requireOrImportModule.js setGlobal.d.ts setGlobal.js specialChars.d.ts specialChars.js testPathPatternToRegExp.d.ts testPathPatternToRegExp.js tryRealpath.d.ts tryRealpath.js node_modules ci-info CHANGELOG.md README.md index.d.ts index.js package.json vendors.json package.json join-component History.md Readme.md component.json index.js package.json test index.js js-sha256 CHANGELOG.md LICENSE.txt README.md build sha256.min.js index.d.ts package.json src sha256.js js-tokens CHANGELOG.md README.md index.js package.json json-buffer .travis.yml README.md index.js package.json test index.js keyv README.md package.json src index.js latest-version index.d.ts index.js package.json readme.md lodash.isstring README.md index.js package.json lodash README.md _DataView.js _Hash.js _LazyWrapper.js _ListCache.js _LodashWrapper.js _Map.js _MapCache.js _Promise.js _Set.js _SetCache.js _Stack.js _Symbol.js _Uint8Array.js _WeakMap.js _apply.js _arrayAggregator.js _arrayEach.js _arrayEachRight.js _arrayEvery.js _arrayFilter.js _arrayIncludes.js _arrayIncludesWith.js _arrayLikeKeys.js _arrayMap.js _arrayPush.js _arrayReduce.js _arrayReduceRight.js _arraySample.js _arraySampleSize.js _arrayShuffle.js _arraySome.js _asciiSize.js _asciiToArray.js _asciiWords.js _assignMergeValue.js _assignValue.js _assocIndexOf.js _baseAggregator.js _baseAssign.js _baseAssignIn.js _baseAssignValue.js _baseAt.js _baseClamp.js _baseClone.js _baseConforms.js _baseConformsTo.js _baseCreate.js _baseDelay.js _baseDifference.js _baseEach.js _baseEachRight.js _baseEvery.js _baseExtremum.js _baseFill.js _baseFilter.js _baseFindIndex.js _baseFindKey.js _baseFlatten.js _baseFor.js _baseForOwn.js _baseForOwnRight.js _baseForRight.js _baseFunctions.js _baseGet.js _baseGetAllKeys.js _baseGetTag.js _baseGt.js _baseHas.js _baseHasIn.js _baseInRange.js _baseIndexOf.js _baseIndexOfWith.js _baseIntersection.js _baseInverter.js _baseInvoke.js _baseIsArguments.js _baseIsArrayBuffer.js _baseIsDate.js _baseIsEqual.js _baseIsEqualDeep.js _baseIsMap.js _baseIsMatch.js _baseIsNaN.js _baseIsNative.js _baseIsRegExp.js _baseIsSet.js _baseIsTypedArray.js _baseIteratee.js _baseKeys.js _baseKeysIn.js _baseLodash.js _baseLt.js _baseMap.js _baseMatches.js _baseMatchesProperty.js _baseMean.js _baseMerge.js _baseMergeDeep.js _baseNth.js _baseOrderBy.js _basePick.js _basePickBy.js _baseProperty.js _basePropertyDeep.js _basePropertyOf.js _basePullAll.js _basePullAt.js _baseRandom.js _baseRange.js _baseReduce.js _baseRepeat.js _baseRest.js _baseSample.js _baseSampleSize.js _baseSet.js _baseSetData.js _baseSetToString.js _baseShuffle.js _baseSlice.js _baseSome.js _baseSortBy.js _baseSortedIndex.js _baseSortedIndexBy.js _baseSortedUniq.js _baseSum.js _baseTimes.js _baseToNumber.js _baseToPairs.js _baseToString.js _baseTrim.js _baseUnary.js _baseUniq.js _baseUnset.js _baseUpdate.js _baseValues.js _baseWhile.js _baseWrapperValue.js _baseXor.js _baseZipObject.js _cacheHas.js _castArrayLikeObject.js _castFunction.js _castPath.js _castRest.js _castSlice.js _charsEndIndex.js _charsStartIndex.js _cloneArrayBuffer.js _cloneBuffer.js _cloneDataView.js _cloneRegExp.js _cloneSymbol.js _cloneTypedArray.js _compareAscending.js _compareMultiple.js _composeArgs.js _composeArgsRight.js _copyArray.js _copyObject.js _copySymbols.js _copySymbolsIn.js _coreJsData.js _countHolders.js _createAggregator.js _createAssigner.js _createBaseEach.js _createBaseFor.js _createBind.js _createCaseFirst.js _createCompounder.js _createCtor.js _createCurry.js _createFind.js _createFlow.js _createHybrid.js _createInverter.js _createMathOperation.js _createOver.js _createPadding.js _createPartial.js _createRange.js _createRecurry.js _createRelationalOperation.js _createRound.js _createSet.js _createToPairs.js _createWrap.js _customDefaultsAssignIn.js _customDefaultsMerge.js _customOmitClone.js _deburrLetter.js _defineProperty.js _equalArrays.js _equalByTag.js _equalObjects.js _escapeHtmlChar.js _escapeStringChar.js _flatRest.js _freeGlobal.js _getAllKeys.js _getAllKeysIn.js _getData.js _getFuncName.js _getHolder.js _getMapData.js _getMatchData.js _getNative.js _getPrototype.js _getRawTag.js _getSymbols.js _getSymbolsIn.js _getTag.js _getValue.js _getView.js _getWrapDetails.js _hasPath.js _hasUnicode.js _hasUnicodeWord.js _hashClear.js _hashDelete.js _hashGet.js _hashHas.js _hashSet.js _initCloneArray.js _initCloneByTag.js _initCloneObject.js _insertWrapDetails.js _isFlattenable.js _isIndex.js _isIterateeCall.js _isKey.js _isKeyable.js _isLaziable.js _isMaskable.js _isMasked.js _isPrototype.js _isStrictComparable.js _iteratorToArray.js _lazyClone.js _lazyReverse.js _lazyValue.js _listCacheClear.js _listCacheDelete.js _listCacheGet.js _listCacheHas.js _listCacheSet.js _mapCacheClear.js _mapCacheDelete.js _mapCacheGet.js _mapCacheHas.js _mapCacheSet.js _mapToArray.js _matchesStrictComparable.js _memoizeCapped.js _mergeData.js _metaMap.js _nativeCreate.js _nativeKeys.js _nativeKeysIn.js _nodeUtil.js _objectToString.js _overArg.js _overRest.js _parent.js _reEscape.js _reEvaluate.js _reInterpolate.js _realNames.js _reorder.js _replaceHolders.js _root.js _safeGet.js _setCacheAdd.js _setCacheHas.js _setData.js _setToArray.js _setToPairs.js _setToString.js _setWrapToString.js _shortOut.js _shuffleSelf.js _stackClear.js _stackDelete.js _stackGet.js _stackHas.js _stackSet.js _strictIndexOf.js _strictLastIndexOf.js _stringSize.js _stringToArray.js _stringToPath.js _toKey.js _toSource.js _trimmedEndIndex.js _unescapeHtmlChar.js _unicodeSize.js _unicodeToArray.js _unicodeWords.js _updateWrapDetails.js _wrapperClone.js add.js after.js array.js ary.js assign.js assignIn.js assignInWith.js assignWith.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js concat.js cond.js conforms.js conformsTo.js constant.js core.js core.min.js countBy.js create.js curry.js curryRight.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsDeep.js defer.js delay.js difference.js differenceBy.js differenceWith.js divide.js drop.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js escape.js escapeRegExp.js every.js extend.js extendWith.js fill.js filter.js find.js findIndex.js findKey.js findLast.js findLastIndex.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fp.js fp F.js T.js __.js _baseConvert.js _convertBrowser.js _falseOptions.js _mapping.js _util.js add.js after.js all.js allPass.js always.js any.js anyPass.js apply.js array.js ary.js assign.js assignAll.js assignAllWith.js assignIn.js assignInAll.js assignInAllWith.js assignInWith.js assignWith.js assoc.js assocPath.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js complement.js compose.js concat.js cond.js conforms.js conformsTo.js constant.js contains.js convert.js countBy.js create.js curry.js curryN.js curryRight.js curryRightN.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsAll.js defaultsDeep.js defaultsDeepAll.js defer.js delay.js difference.js differenceBy.js differenceWith.js dissoc.js dissocPath.js divide.js drop.js dropLast.js dropLastWhile.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js equals.js escape.js escapeRegExp.js every.js extend.js extendAll.js extendAllWith.js extendWith.js fill.js filter.js find.js findFrom.js findIndex.js findIndexFrom.js findKey.js findLast.js findLastFrom.js findLastIndex.js findLastIndexFrom.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fromPairs.js function.js functions.js functionsIn.js get.js getOr.js groupBy.js gt.js gte.js has.js hasIn.js head.js identical.js identity.js inRange.js includes.js includesFrom.js indexBy.js indexOf.js indexOfFrom.js init.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invertObj.js invoke.js invokeArgs.js invokeArgsMap.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js juxt.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lastIndexOfFrom.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeAll.js mergeAllWith.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js nAry.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitAll.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js pad.js padChars.js padCharsEnd.js padCharsStart.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js path.js pathEq.js pathOr.js paths.js pick.js pickAll.js pickBy.js pipe.js placeholder.js plant.js pluck.js prop.js propEq.js propOr.js property.js propertyOf.js props.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rangeStep.js rangeStepRight.js rearg.js reduce.js reduceRight.js reject.js remove.js repeat.js replace.js rest.js restFrom.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js spreadFrom.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js symmetricDifference.js symmetricDifferenceBy.js symmetricDifferenceWith.js tail.js take.js takeLast.js takeLastWhile.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimChars.js trimCharsEnd.js trimCharsStart.js trimEnd.js trimStart.js truncate.js unapply.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unnest.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js useWith.js util.js value.js valueOf.js values.js valuesIn.js where.js whereEq.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipAll.js zipObj.js zipObject.js zipObjectDeep.js zipWith.js fromPairs.js function.js functions.js functionsIn.js get.js groupBy.js gt.js gte.js has.js hasIn.js head.js identity.js inRange.js includes.js index.js indexOf.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invoke.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lodash.js lodash.min.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js package.json pad.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js pick.js pickBy.js plant.js property.js propertyOf.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rearg.js reduce.js reduceRight.js reject.js release.md remove.js repeat.js replace.js rest.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js tail.js take.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimEnd.js trimStart.js truncate.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js util.js value.js valueOf.js values.js valuesIn.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipObject.js zipObjectDeep.js zipWith.js lowercase-keys index.js package.json readme.md lru-cache README.md index.js package.json make-dir index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md md5.js README.md index.js package.json md5 .travis.yml README.md demo index.html dist md5.min.js md5.js package.json test.js webpack.config.js micromatch README.md index.js package.json mime-db HISTORY.md README.md db.json index.js package.json mime-types HISTORY.md README.md index.js package.json mimic-response index.d.ts index.js package.json readme.md minimatch README.md minimatch.js package.json minimist .github FUNDING.yml CHANGELOG.md README.md example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js proto.js short.js stop_early.js unknown.js whitespace.js mkdirp-classic README.md index.js package.json ms index.js license.md package.json readme.md mustache CHANGELOG.md README.md mustache.js mustache.min.js package.json napi-build-utils README.md index.js index.md package.json ncp .travis.yml LICENSE.md README.md lib ncp.js package.json test ncp.js near-api-js README.md browser-exports.js dist near-api-js.js near-api-js.min.js lib account.d.ts account.js account_creator.d.ts account_creator.js account_multisig.d.ts account_multisig.js browser-connect.d.ts browser-connect.js browser-index.d.ts browser-index.js common-index.d.ts common-index.js connect.d.ts connect.js connection.d.ts connection.js constants.d.ts constants.js contract.d.ts contract.js generated rpc_error_schema.json index.d.ts index.js key_stores browser-index.d.ts browser-index.js browser_local_storage_key_store.d.ts browser_local_storage_key_store.js in_memory_key_store.d.ts in_memory_key_store.js index.d.ts index.js keystore.d.ts keystore.js merge_key_store.d.ts merge_key_store.js unencrypted_file_system_keystore.d.ts unencrypted_file_system_keystore.js near.d.ts near.js providers index.d.ts index.js json-rpc-provider.d.ts json-rpc-provider.js provider.d.ts provider.js res error_messages.d.ts error_messages.json signer.d.ts signer.js transaction.d.ts transaction.js utils enums.d.ts enums.js errors.d.ts errors.js exponential-backoff.d.ts exponential-backoff.js format.d.ts format.js index.d.ts index.js key_pair.d.ts key_pair.js network.d.ts network.js rpc_errors.d.ts rpc_errors.js serialize.d.ts serialize.js setup-node-fetch.d.ts setup-node-fetch.js web.d.ts web.js validators.d.ts validators.js wallet-account.d.ts wallet-account.js node_modules bn.js CHANGELOG.md README.md lib bn.js package.json package.json near-cli README.md bin near-cli.js commands add-key.js call.js create-account.js delete-key.js dev-deploy.js evm-call.js evm-dev-init.js evm-view.js generate-key.js js.js proposals.js repl.js set-x-api-key.js tx-status.js validators.js view-state.js config.js context index.d.ts get-config.js index.js middleware abi.js base64-args.js initial-balance.js key-store.js ledger.js print-options.js seed-phrase.js package.json test_environment.js utils capture-login-success.js check-credentials.js check-version.js connect.js create-dev-account.js deprecation-warning.js error-handlers.js eventtracking.js exit-on-error.js explorer.js implicit-accountid.js inspect-response.js log-event.js readline.js settings.js validators-info.js verify-account.js x-api-key-settings.js near-hd-key README.md dist index.d.ts index.js utils.d.ts utils.js package.json near-ledger-js .travis.yml README.md demo demo.js index.html index.js package.json supportedTransports.js near-seed-phrase .eslintrc.yml .fossa.yml .travis.yml index.js package.json test index.test.js node-abi .circleci config.yml .github workflows update-abi.yml .releaserc.json CODE_OF_CONDUCT.md CONTRIBUTING.md README.md abi_registry.json index.js package.json scripts update-abi-registry.js test index.js node-addon-api CHANGELOG.md LICENSE.md README.md index.js napi-inl.deprecated.h napi-inl.h napi.h nothing.c package-support.json package.json tools README.md check-napi.js clang-format.js conversion.js node-fetch LICENSE.md README.md browser.js lib index.es.js index.js package.json node-gyp-build README.md bin.js build-test.js index.js optional.js package.json node-hid LICENSE-bsd.txt Publishing.md README.md hidapi .appveyor.yml .builds alpine.yml archlinux.yml fedora-mingw.yml freebsd.yml .cirrus.yml AUTHORS.txt HACKING.txt LICENSE-bsd.txt LICENSE-gpl3.txt LICENSE-orig.txt LICENSE.txt README.md hidapi hidapi.h hidtest test.c libusb hid.c linux hid.c mac hid.c testgui copy_to_bundle.sh mac_support.h test.cpp testgui.sln windows hid.c hidapi.sln nodehid.js package.json src buzzers.js powermate.js show-devices.js test-bigredbutton.js test-blink1.js test-buzzers.js test-ci.js test-macbookprotrackpad.js test-powermate.js test-ps3-rumbleled.js test-ps3.js test-teensyrawhid.js test-tinyusbrawhid.js testReadSync.js normalize-url index.d.ts index.js package.json readme.md npmlog CHANGELOG.md README.md log.js package.json number-is-nan index.js package.json readme.md o3 README.md index.js lib Class.js abstractMethod.js index.js package.json object-assign index.js package.json readme.md once README.md once.js package.json open index.d.ts index.js package.json readme.md p-cancelable index.d.ts index.js package.json readme.md package-json index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md parse-passwd README.md index.js package.json path-is-absolute index.js package.json readme.md pbkdf2 README.md browser.js index.js lib async.js default-encoding.js precondition.js sync-browser.js sync.js to-buffer.js package.json picomatch CHANGELOG.md README.md index.js lib constants.js parse.js picomatch.js scan.js utils.js package.json platform README.md package.json platform.js prebuild-install CHANGELOG.md CONTRIBUTING.md README.md asset.js bin.js download.js error.js help.txt index.js log.js package.json proxy.js rc.js util.js prepend-http index.js package.json readme.md pretty-format README.md build collections.d.ts collections.js index.d.ts index.js plugins AsymmetricMatcher.d.ts AsymmetricMatcher.js ConvertAnsi.d.ts ConvertAnsi.js DOMCollection.d.ts DOMCollection.js DOMElement.d.ts DOMElement.js Immutable.d.ts Immutable.js ReactElement.d.ts ReactElement.js ReactTestComponent.d.ts ReactTestComponent.js lib escapeHTML.d.ts escapeHTML.js markup.d.ts markup.js types.d.ts types.js node_modules ansi-styles index.d.ts index.js package.json readme.md package.json process-nextick-args index.js license.md package.json readme.md pump .travis.yml README.md index.js package.json test-browser.js test-node.js pupa index.d.ts index.js package.json readme.md randombytes .travis.yml .zuul.yml README.md browser.js index.js package.json test.js rc README.md browser.js cli.js index.js lib utils.js package.json test ini.js nested-env-vars.js test.js react-is README.md build-info.json cjs react-is.development.js react-is.production.min.js index.js package.json umd react-is.development.js react-is.production.min.js readable-stream CONTRIBUTING.md GOVERNANCE.md README.md errors-browser.js errors.js experimentalWarning.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams async_iterator.js buffer_list.js destroy.js end-of-stream.js from-browser.js from.js pipeline.js state.js stream-browser.js stream.js package.json readable-browser.js readable.js registry-auth-token CHANGELOG.md README.md base64.js index.js package.json registry-url.js registry-url index.d.ts index.js package.json readme.md remove-trailing-slash history.md index.d.ts index.js package.json readme.md require-directory .travis.yml index.js package.json responselike README.md package.json src index.js rimraf CHANGELOG.md README.md bin.js package.json rimraf.js ripemd160 CHANGELOG.md README.md index.js package.json rxjs AsyncSubject.d.ts AsyncSubject.js BehaviorSubject.d.ts BehaviorSubject.js InnerSubscriber.d.ts InnerSubscriber.js LICENSE.txt Notification.d.ts Notification.js Observable.d.ts Observable.js Observer.d.ts Observer.js Operator.d.ts Operator.js OuterSubscriber.d.ts OuterSubscriber.js README.md ReplaySubject.d.ts ReplaySubject.js Rx.d.ts Rx.js Scheduler.d.ts Scheduler.js Subject.d.ts Subject.js SubjectSubscription.d.ts SubjectSubscription.js Subscriber.d.ts Subscriber.js Subscription.d.ts Subscription.js _esm2015 LICENSE.txt README.md ajax index.js fetch index.js index.js internal-compatibility index.js internal AsyncSubject.js BehaviorSubject.js InnerSubscriber.js Notification.js Observable.js Observer.js Operator.js OuterSubscriber.js ReplaySubject.js Rx.js Scheduler.js Subject.js SubjectSubscription.js Subscriber.js Subscription.js config.js innerSubscribe.js observable ConnectableObservable.js SubscribeOnObservable.js bindCallback.js bindNodeCallback.js combineLatest.js concat.js defer.js dom AjaxObservable.js WebSocketSubject.js ajax.js fetch.js webSocket.js empty.js forkJoin.js from.js fromArray.js fromEvent.js fromEventPattern.js fromIterable.js fromPromise.js generate.js iif.js interval.js merge.js never.js of.js onErrorResumeNext.js pairs.js partition.js race.js range.js throwError.js timer.js using.js zip.js operators audit.js auditTime.js buffer.js bufferCount.js bufferTime.js bufferToggle.js bufferWhen.js catchError.js combineAll.js combineLatest.js concat.js concatAll.js concatMap.js concatMapTo.js count.js debounce.js debounceTime.js defaultIfEmpty.js delay.js delayWhen.js dematerialize.js distinct.js distinctUntilChanged.js distinctUntilKeyChanged.js elementAt.js endWith.js every.js exhaust.js exhaustMap.js expand.js filter.js finalize.js find.js findIndex.js first.js groupBy.js ignoreElements.js index.js isEmpty.js last.js map.js mapTo.js materialize.js max.js merge.js mergeAll.js mergeMap.js mergeMapTo.js mergeScan.js min.js multicast.js observeOn.js onErrorResumeNext.js pairwise.js partition.js pluck.js publish.js publishBehavior.js publishLast.js publishReplay.js race.js reduce.js refCount.js repeat.js repeatWhen.js retry.js retryWhen.js sample.js sampleTime.js scan.js sequenceEqual.js share.js shareReplay.js single.js skip.js skipLast.js skipUntil.js skipWhile.js startWith.js subscribeOn.js switchAll.js switchMap.js switchMapTo.js take.js takeLast.js takeUntil.js takeWhile.js tap.js throttle.js throttleTime.js throwIfEmpty.js timeInterval.js timeout.js timeoutWith.js timestamp.js toArray.js window.js windowCount.js windowTime.js windowToggle.js windowWhen.js withLatestFrom.js zip.js zipAll.js scheduled scheduleArray.js scheduleIterable.js scheduleObservable.js schedulePromise.js scheduled.js scheduler Action.js AnimationFrameAction.js AnimationFrameScheduler.js AsapAction.js AsapScheduler.js AsyncAction.js AsyncScheduler.js QueueAction.js QueueScheduler.js VirtualTimeScheduler.js animationFrame.js asap.js async.js queue.js symbol iterator.js observable.js rxSubscriber.js testing ColdObservable.js HotObservable.js SubscriptionLog.js SubscriptionLoggable.js TestMessage.js TestScheduler.js types.js util ArgumentOutOfRangeError.js EmptyError.js Immediate.js ObjectUnsubscribedError.js TimeoutError.js UnsubscriptionError.js applyMixins.js canReportError.js errorObject.js hostReportError.js identity.js isArray.js isArrayLike.js isDate.js isFunction.js isInteropObservable.js isIterable.js isNumeric.js isObject.js isObservable.js isPromise.js isScheduler.js noop.js not.js pipe.js root.js subscribeTo.js subscribeToArray.js subscribeToIterable.js subscribeToObservable.js subscribeToPromise.js subscribeToResult.js toSubscriber.js tryCatch.js operators index.js path-mapping.js testing index.js webSocket index.js _esm5 LICENSE.txt README.md ajax index.js fetch index.js index.js internal-compatibility index.js internal AsyncSubject.js BehaviorSubject.js InnerSubscriber.js Notification.js Observable.js Observer.js Operator.js OuterSubscriber.js ReplaySubject.js Rx.js Scheduler.js Subject.js SubjectSubscription.js Subscriber.js Subscription.js config.js innerSubscribe.js observable ConnectableObservable.js SubscribeOnObservable.js bindCallback.js bindNodeCallback.js combineLatest.js concat.js defer.js dom AjaxObservable.js WebSocketSubject.js ajax.js fetch.js webSocket.js empty.js forkJoin.js from.js fromArray.js fromEvent.js fromEventPattern.js fromIterable.js fromPromise.js generate.js iif.js interval.js merge.js never.js of.js onErrorResumeNext.js pairs.js partition.js race.js range.js throwError.js timer.js using.js zip.js operators audit.js auditTime.js buffer.js bufferCount.js bufferTime.js bufferToggle.js bufferWhen.js catchError.js combineAll.js combineLatest.js concat.js concatAll.js concatMap.js concatMapTo.js count.js debounce.js debounceTime.js defaultIfEmpty.js delay.js delayWhen.js dematerialize.js distinct.js distinctUntilChanged.js distinctUntilKeyChanged.js elementAt.js endWith.js every.js exhaust.js exhaustMap.js expand.js filter.js finalize.js find.js findIndex.js first.js groupBy.js ignoreElements.js index.js isEmpty.js last.js map.js mapTo.js materialize.js max.js merge.js mergeAll.js mergeMap.js mergeMapTo.js mergeScan.js min.js multicast.js observeOn.js onErrorResumeNext.js pairwise.js partition.js pluck.js publish.js publishBehavior.js publishLast.js publishReplay.js race.js reduce.js refCount.js repeat.js repeatWhen.js retry.js retryWhen.js sample.js sampleTime.js scan.js sequenceEqual.js share.js shareReplay.js single.js skip.js skipLast.js skipUntil.js skipWhile.js startWith.js subscribeOn.js switchAll.js switchMap.js switchMapTo.js take.js takeLast.js takeUntil.js takeWhile.js tap.js throttle.js throttleTime.js throwIfEmpty.js timeInterval.js timeout.js timeoutWith.js timestamp.js toArray.js window.js windowCount.js windowTime.js windowToggle.js windowWhen.js withLatestFrom.js zip.js zipAll.js scheduled scheduleArray.js scheduleIterable.js scheduleObservable.js schedulePromise.js scheduled.js scheduler Action.js AnimationFrameAction.js AnimationFrameScheduler.js AsapAction.js AsapScheduler.js AsyncAction.js AsyncScheduler.js QueueAction.js QueueScheduler.js VirtualTimeScheduler.js animationFrame.js asap.js async.js queue.js symbol iterator.js observable.js rxSubscriber.js testing ColdObservable.js HotObservable.js SubscriptionLog.js SubscriptionLoggable.js TestMessage.js TestScheduler.js types.js util ArgumentOutOfRangeError.js EmptyError.js Immediate.js ObjectUnsubscribedError.js TimeoutError.js UnsubscriptionError.js applyMixins.js canReportError.js errorObject.js hostReportError.js identity.js isArray.js isArrayLike.js isDate.js isFunction.js isInteropObservable.js isIterable.js isNumeric.js isObject.js isObservable.js isPromise.js isScheduler.js noop.js not.js pipe.js root.js subscribeTo.js subscribeToArray.js subscribeToIterable.js subscribeToObservable.js subscribeToPromise.js subscribeToResult.js toSubscriber.js tryCatch.js operators index.js path-mapping.js testing index.js webSocket index.js add observable bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom ajax.d.ts ajax.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js if.d.ts if.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js race.d.ts race.js range.d.ts range.js throw.d.ts throw.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operator audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catch.d.ts catch.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js do.d.ts do.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finally.d.ts finally.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js isEmpty.d.ts isEmpty.js last.d.ts last.js let.d.ts let.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switch.d.ts switch.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js toPromise.d.ts toPromise.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js ajax index.d.ts index.js package.json bundles rxjs.umd.js rxjs.umd.min.js fetch index.d.ts index.js package.json index.d.ts index.js interfaces.d.ts interfaces.js internal-compatibility index.d.ts index.js package.json internal AsyncSubject.d.ts AsyncSubject.js BehaviorSubject.d.ts BehaviorSubject.js InnerSubscriber.d.ts InnerSubscriber.js Notification.d.ts Notification.js Observable.d.ts Observable.js Observer.d.ts Observer.js Operator.d.ts Operator.js OuterSubscriber.d.ts OuterSubscriber.js ReplaySubject.d.ts ReplaySubject.js Rx.d.ts Rx.js Scheduler.d.ts Scheduler.js Subject.d.ts Subject.js SubjectSubscription.d.ts SubjectSubscription.js Subscriber.d.ts Subscriber.js Subscription.d.ts Subscription.js config.d.ts config.js innerSubscribe.d.ts innerSubscribe.js observable ConnectableObservable.d.ts ConnectableObservable.js SubscribeOnObservable.d.ts SubscribeOnObservable.js bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom AjaxObservable.d.ts AjaxObservable.js WebSocketSubject.d.ts WebSocketSubject.js ajax.d.ts ajax.js fetch.d.ts fetch.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromArray.d.ts fromArray.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromIterable.d.ts fromIterable.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js iif.d.ts iif.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js partition.d.ts partition.js race.d.ts race.js range.d.ts range.js throwError.d.ts throwError.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operators audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catchError.d.ts catchError.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js elementAt.d.ts elementAt.js endWith.d.ts endWith.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finalize.d.ts finalize.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js index.d.ts index.js isEmpty.d.ts isEmpty.js last.d.ts last.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js refCount.d.ts refCount.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switchAll.d.ts switchAll.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js tap.d.ts tap.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js throwIfEmpty.d.ts throwIfEmpty.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js scheduled scheduleArray.d.ts scheduleArray.js scheduleIterable.d.ts scheduleIterable.js scheduleObservable.d.ts scheduleObservable.js schedulePromise.d.ts schedulePromise.js scheduled.d.ts scheduled.js scheduler Action.d.ts Action.js AnimationFrameAction.d.ts AnimationFrameAction.js AnimationFrameScheduler.d.ts AnimationFrameScheduler.js AsapAction.d.ts AsapAction.js AsapScheduler.d.ts AsapScheduler.js AsyncAction.d.ts AsyncAction.js AsyncScheduler.d.ts AsyncScheduler.js QueueAction.d.ts QueueAction.js QueueScheduler.d.ts QueueScheduler.js VirtualTimeScheduler.d.ts VirtualTimeScheduler.js animationFrame.d.ts animationFrame.js asap.d.ts asap.js async.d.ts async.js queue.d.ts queue.js symbol iterator.d.ts iterator.js observable.d.ts observable.js rxSubscriber.d.ts rxSubscriber.js testing ColdObservable.d.ts ColdObservable.js HotObservable.d.ts HotObservable.js SubscriptionLog.d.ts SubscriptionLog.js SubscriptionLoggable.d.ts SubscriptionLoggable.js TestMessage.d.ts TestMessage.js TestScheduler.d.ts TestScheduler.js types.d.ts types.js util ArgumentOutOfRangeError.d.ts ArgumentOutOfRangeError.js EmptyError.d.ts EmptyError.js Immediate.d.ts Immediate.js ObjectUnsubscribedError.d.ts ObjectUnsubscribedError.js TimeoutError.d.ts TimeoutError.js UnsubscriptionError.d.ts UnsubscriptionError.js applyMixins.d.ts applyMixins.js canReportError.d.ts canReportError.js errorObject.d.ts errorObject.js hostReportError.d.ts hostReportError.js identity.d.ts identity.js isArray.d.ts isArray.js isArrayLike.d.ts isArrayLike.js isDate.d.ts isDate.js isFunction.d.ts isFunction.js isInteropObservable.d.ts isInteropObservable.js isIterable.d.ts isIterable.js isNumeric.d.ts isNumeric.js isObject.d.ts isObject.js isObservable.d.ts isObservable.js isPromise.d.ts isPromise.js isScheduler.d.ts isScheduler.js noop.d.ts noop.js not.d.ts not.js pipe.d.ts pipe.js root.d.ts root.js subscribeTo.d.ts subscribeTo.js subscribeToArray.d.ts subscribeToArray.js subscribeToIterable.d.ts subscribeToIterable.js subscribeToObservable.d.ts subscribeToObservable.js subscribeToPromise.d.ts subscribeToPromise.js subscribeToResult.d.ts subscribeToResult.js toSubscriber.d.ts toSubscriber.js tryCatch.d.ts tryCatch.js migrations collection.json update-6_0_0 index.js observable ArrayLikeObservable.d.ts ArrayLikeObservable.js ArrayObservable.d.ts ArrayObservable.js BoundCallbackObservable.d.ts BoundCallbackObservable.js BoundNodeCallbackObservable.d.ts BoundNodeCallbackObservable.js ConnectableObservable.d.ts ConnectableObservable.js DeferObservable.d.ts DeferObservable.js EmptyObservable.d.ts EmptyObservable.js ErrorObservable.d.ts ErrorObservable.js ForkJoinObservable.d.ts ForkJoinObservable.js FromEventObservable.d.ts FromEventObservable.js FromEventPatternObservable.d.ts FromEventPatternObservable.js FromObservable.d.ts FromObservable.js GenerateObservable.d.ts GenerateObservable.js IfObservable.d.ts IfObservable.js IntervalObservable.d.ts IntervalObservable.js IteratorObservable.d.ts IteratorObservable.js NeverObservable.d.ts NeverObservable.js PairsObservable.d.ts PairsObservable.js PromiseObservable.d.ts PromiseObservable.js RangeObservable.d.ts RangeObservable.js ScalarObservable.d.ts ScalarObservable.js SubscribeOnObservable.d.ts SubscribeOnObservable.js TimerObservable.d.ts TimerObservable.js UsingObservable.d.ts UsingObservable.js bindCallback.d.ts bindCallback.js bindNodeCallback.d.ts bindNodeCallback.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js defer.d.ts defer.js dom AjaxObservable.d.ts AjaxObservable.js WebSocketSubject.d.ts WebSocketSubject.js ajax.d.ts ajax.js webSocket.d.ts webSocket.js empty.d.ts empty.js forkJoin.d.ts forkJoin.js from.d.ts from.js fromArray.d.ts fromArray.js fromEvent.d.ts fromEvent.js fromEventPattern.d.ts fromEventPattern.js fromIterable.d.ts fromIterable.js fromPromise.d.ts fromPromise.js generate.d.ts generate.js if.d.ts if.js interval.d.ts interval.js merge.d.ts merge.js never.d.ts never.js of.d.ts of.js onErrorResumeNext.d.ts onErrorResumeNext.js pairs.d.ts pairs.js race.d.ts race.js range.d.ts range.js throw.d.ts throw.js timer.d.ts timer.js using.d.ts using.js zip.d.ts zip.js operator audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catch.d.ts catch.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js do.d.ts do.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finally.d.ts finally.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js isEmpty.d.ts isEmpty.js last.d.ts last.js let.d.ts let.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switch.d.ts switch.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js toPromise.d.ts toPromise.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js operators audit.d.ts audit.js auditTime.d.ts auditTime.js buffer.d.ts buffer.js bufferCount.d.ts bufferCount.js bufferTime.d.ts bufferTime.js bufferToggle.d.ts bufferToggle.js bufferWhen.d.ts bufferWhen.js catchError.d.ts catchError.js combineAll.d.ts combineAll.js combineLatest.d.ts combineLatest.js concat.d.ts concat.js concatAll.d.ts concatAll.js concatMap.d.ts concatMap.js concatMapTo.d.ts concatMapTo.js count.d.ts count.js debounce.d.ts debounce.js debounceTime.d.ts debounceTime.js defaultIfEmpty.d.ts defaultIfEmpty.js delay.d.ts delay.js delayWhen.d.ts delayWhen.js dematerialize.d.ts dematerialize.js distinct.d.ts distinct.js distinctUntilChanged.d.ts distinctUntilChanged.js distinctUntilKeyChanged.d.ts distinctUntilKeyChanged.js elementAt.d.ts elementAt.js every.d.ts every.js exhaust.d.ts exhaust.js exhaustMap.d.ts exhaustMap.js expand.d.ts expand.js filter.d.ts filter.js finalize.d.ts finalize.js find.d.ts find.js findIndex.d.ts findIndex.js first.d.ts first.js groupBy.d.ts groupBy.js ignoreElements.d.ts ignoreElements.js index.d.ts index.js isEmpty.d.ts isEmpty.js last.d.ts last.js map.d.ts map.js mapTo.d.ts mapTo.js materialize.d.ts materialize.js max.d.ts max.js merge.d.ts merge.js mergeAll.d.ts mergeAll.js mergeMap.d.ts mergeMap.js mergeMapTo.d.ts mergeMapTo.js mergeScan.d.ts mergeScan.js min.d.ts min.js multicast.d.ts multicast.js observeOn.d.ts observeOn.js onErrorResumeNext.d.ts onErrorResumeNext.js package.json pairwise.d.ts pairwise.js partition.d.ts partition.js pluck.d.ts pluck.js publish.d.ts publish.js publishBehavior.d.ts publishBehavior.js publishLast.d.ts publishLast.js publishReplay.d.ts publishReplay.js race.d.ts race.js reduce.d.ts reduce.js refCount.d.ts refCount.js repeat.d.ts repeat.js repeatWhen.d.ts repeatWhen.js retry.d.ts retry.js retryWhen.d.ts retryWhen.js sample.d.ts sample.js sampleTime.d.ts sampleTime.js scan.d.ts scan.js sequenceEqual.d.ts sequenceEqual.js share.d.ts share.js shareReplay.d.ts shareReplay.js single.d.ts single.js skip.d.ts skip.js skipLast.d.ts skipLast.js skipUntil.d.ts skipUntil.js skipWhile.d.ts skipWhile.js startWith.d.ts startWith.js subscribeOn.d.ts subscribeOn.js switchAll.d.ts switchAll.js switchMap.d.ts switchMap.js switchMapTo.d.ts switchMapTo.js take.d.ts take.js takeLast.d.ts takeLast.js takeUntil.d.ts takeUntil.js takeWhile.d.ts takeWhile.js tap.d.ts tap.js throttle.d.ts throttle.js throttleTime.d.ts throttleTime.js throwIfEmpty.d.ts throwIfEmpty.js timeInterval.d.ts timeInterval.js timeout.d.ts timeout.js timeoutWith.d.ts timeoutWith.js timestamp.d.ts timestamp.js toArray.d.ts toArray.js window.d.ts window.js windowCount.d.ts windowCount.js windowTime.d.ts windowTime.js windowToggle.d.ts windowToggle.js windowWhen.d.ts windowWhen.js withLatestFrom.d.ts withLatestFrom.js zip.d.ts zip.js zipAll.d.ts zipAll.js package.json scheduler animationFrame.d.ts animationFrame.js asap.d.ts asap.js async.d.ts async.js queue.d.ts queue.js src AsyncSubject.ts BehaviorSubject.ts InnerSubscriber.ts LICENSE.txt MiscJSDoc.ts Notification.ts Observable.ts Observer.ts Operator.ts OuterSubscriber.ts README.md ReplaySubject.ts Rx.global.js Rx.ts Scheduler.ts Subject.ts SubjectSubscription.ts Subscriber.ts Subscription.ts add observable bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom ajax.ts webSocket.ts empty.ts forkJoin.ts from.ts fromEvent.ts fromEventPattern.ts fromPromise.ts generate.ts if.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts race.ts range.ts throw.ts timer.ts using.ts zip.ts operator audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catch.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts do.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finally.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts isEmpty.ts last.ts let.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switch.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts throttle.ts throttleTime.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts toPromise.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts ajax index.ts package.json fetch index.ts package.json index.ts interfaces.ts internal-compatibility index.ts package.json internal AsyncSubject.ts BehaviorSubject.ts InnerSubscriber.ts Notification.ts Observable.ts Observer.ts Operator.ts OuterSubscriber.ts ReplaySubject.ts Rx.ts Scheduler.ts Subject.ts SubjectSubscription.ts Subscriber.ts Subscription.ts config.ts innerSubscribe.ts observable ConnectableObservable.ts SubscribeOnObservable.ts bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom AjaxObservable.ts MiscJSDoc.ts WebSocketSubject.ts ajax.ts fetch.ts webSocket.ts empty.ts forkJoin.ts from.ts fromArray.ts fromEvent.ts fromEventPattern.ts fromIterable.ts fromObservable.ts fromPromise.ts generate.ts iif.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts partition.ts race.ts range.ts throwError.ts timer.ts using.ts zip.ts operators audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catchError.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts elementAt.ts endWith.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finalize.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts index.ts isEmpty.ts last.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts refCount.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switchAll.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts tap.ts throttle.ts throttleTime.ts throwIfEmpty.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts scheduled scheduleArray.ts scheduleIterable.ts scheduleObservable.ts schedulePromise.ts scheduled.ts scheduler Action.ts AnimationFrameAction.ts AnimationFrameScheduler.ts AsapAction.ts AsapScheduler.ts AsyncAction.ts AsyncScheduler.ts QueueAction.ts QueueScheduler.ts VirtualTimeScheduler.ts animationFrame.ts asap.ts async.ts queue.ts symbol iterator.ts observable.ts rxSubscriber.ts testing ColdObservable.ts HotObservable.ts SubscriptionLog.ts SubscriptionLoggable.ts TestMessage.ts TestScheduler.ts types.ts umd.ts util ArgumentOutOfRangeError.ts EmptyError.ts Immediate.ts ObjectUnsubscribedError.ts TimeoutError.ts UnsubscriptionError.ts applyMixins.ts canReportError.ts errorObject.ts hostReportError.ts identity.ts isArray.ts isArrayLike.ts isDate.ts isFunction.ts isInteropObservable.ts isIterable.ts isNumeric.ts isObject.ts isObservable.ts isPromise.ts isScheduler.ts noop.ts not.ts pipe.ts root.ts subscribeTo.ts subscribeToArray.ts subscribeToIterable.ts subscribeToObservable.ts subscribeToPromise.ts subscribeToResult.ts toSubscriber.ts tryCatch.ts observable ArrayLikeObservable.ts ArrayObservable.ts BoundCallbackObservable.ts BoundNodeCallbackObservable.ts ConnectableObservable.ts DeferObservable.ts EmptyObservable.ts ErrorObservable.ts ForkJoinObservable.ts FromEventObservable.ts FromEventPatternObservable.ts FromObservable.ts GenerateObservable.ts IfObservable.ts IntervalObservable.ts IteratorObservable.ts NeverObservable.ts PairsObservable.ts PromiseObservable.ts RangeObservable.ts ScalarObservable.ts SubscribeOnObservable.ts TimerObservable.ts UsingObservable.ts bindCallback.ts bindNodeCallback.ts combineLatest.ts concat.ts defer.ts dom AjaxObservable.ts WebSocketSubject.ts ajax.ts webSocket.ts empty.ts forkJoin.ts from.ts fromArray.ts fromEvent.ts fromEventPattern.ts fromIterable.ts fromPromise.ts generate.ts if.ts interval.ts merge.ts never.ts of.ts onErrorResumeNext.ts pairs.ts race.ts range.ts throw.ts timer.ts using.ts zip.ts operator audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catch.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts do.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finally.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts isEmpty.ts last.ts let.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switch.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts throttle.ts throttleTime.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts toPromise.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts operators audit.ts auditTime.ts buffer.ts bufferCount.ts bufferTime.ts bufferToggle.ts bufferWhen.ts catchError.ts combineAll.ts combineLatest.ts concat.ts concatAll.ts concatMap.ts concatMapTo.ts count.ts debounce.ts debounceTime.ts defaultIfEmpty.ts delay.ts delayWhen.ts dematerialize.ts distinct.ts distinctUntilChanged.ts distinctUntilKeyChanged.ts elementAt.ts every.ts exhaust.ts exhaustMap.ts expand.ts filter.ts finalize.ts find.ts findIndex.ts first.ts groupBy.ts ignoreElements.ts index.ts isEmpty.ts last.ts map.ts mapTo.ts materialize.ts max.ts merge.ts mergeAll.ts mergeMap.ts mergeMapTo.ts mergeScan.ts min.ts multicast.ts observeOn.ts onErrorResumeNext.ts package.json pairwise.ts partition.ts pluck.ts publish.ts publishBehavior.ts publishLast.ts publishReplay.ts race.ts reduce.ts refCount.ts repeat.ts repeatWhen.ts retry.ts retryWhen.ts sample.ts sampleTime.ts scan.ts sequenceEqual.ts share.ts shareReplay.ts single.ts skip.ts skipLast.ts skipUntil.ts skipWhile.ts startWith.ts subscribeOn.ts switchAll.ts switchMap.ts switchMapTo.ts take.ts takeLast.ts takeUntil.ts takeWhile.ts tap.ts throttle.ts throttleTime.ts throwIfEmpty.ts timeInterval.ts timeout.ts timeoutWith.ts timestamp.ts toArray.ts window.ts windowCount.ts windowTime.ts windowToggle.ts windowWhen.ts withLatestFrom.ts zip.ts zipAll.ts scheduler animationFrame.ts asap.ts async.ts queue.ts symbol iterator.ts observable.ts rxSubscriber.ts testing index.ts package.json tsconfig.json util ArgumentOutOfRangeError.ts EmptyError.ts Immediate.ts ObjectUnsubscribedError.ts TimeoutError.ts UnsubscriptionError.ts applyMixins.ts errorObject.ts hostReportError.ts identity.ts isArray.ts isArrayLike.ts isDate.ts isFunction.ts isIterable.ts isNumeric.ts isObject.ts isObservable.ts isPromise.ts isScheduler.ts noop.ts not.ts pipe.ts root.ts subscribeTo.ts subscribeToArray.ts subscribeToIterable.ts subscribeToObservable.ts subscribeToPromise.ts subscribeToResult.ts toSubscriber.ts tryCatch.ts webSocket index.ts package.json symbol iterator.d.ts iterator.js observable.d.ts observable.js rxSubscriber.d.ts rxSubscriber.js testing index.d.ts index.js package.json util ArgumentOutOfRangeError.d.ts ArgumentOutOfRangeError.js EmptyError.d.ts EmptyError.js Immediate.d.ts Immediate.js ObjectUnsubscribedError.d.ts ObjectUnsubscribedError.js TimeoutError.d.ts TimeoutError.js UnsubscriptionError.d.ts UnsubscriptionError.js applyMixins.d.ts applyMixins.js errorObject.d.ts errorObject.js hostReportError.d.ts hostReportError.js identity.d.ts identity.js isArray.d.ts isArray.js isArrayLike.d.ts isArrayLike.js isDate.d.ts isDate.js isFunction.d.ts isFunction.js isIterable.d.ts isIterable.js isNumeric.d.ts isNumeric.js isObject.d.ts isObject.js isObservable.d.ts isObservable.js isPromise.d.ts isPromise.js isScheduler.d.ts isScheduler.js noop.d.ts noop.js not.d.ts not.js pipe.d.ts pipe.js root.d.ts root.js subscribeTo.d.ts subscribeTo.js subscribeToArray.d.ts subscribeToArray.js subscribeToIterable.d.ts subscribeToIterable.js subscribeToObservable.d.ts subscribeToObservable.js subscribeToPromise.d.ts subscribeToPromise.js subscribeToResult.d.ts subscribeToResult.js toSubscriber.d.ts toSubscriber.js tryCatch.d.ts tryCatch.js webSocket index.d.ts index.js package.json safe-buffer README.md index.d.ts index.js package.json semver-diff index.d.ts index.js node_modules semver CHANGELOG.md README.md bin semver.js package.json semver.js package.json readme.md semver README.md bin semver.js classes comparator.js index.js range.js semver.js functions clean.js cmp.js coerce.js compare-build.js compare-loose.js compare.js diff.js eq.js gt.js gte.js inc.js lt.js lte.js major.js minor.js neq.js parse.js patch.js prerelease.js rcompare.js rsort.js satisfies.js sort.js valid.js index.js internal constants.js debug.js identifiers.js parse-options.js re.js package.json preload.js ranges gtr.js intersects.js ltr.js max-satisfying.js min-satisfying.js min-version.js outside.js simplify.js subset.js to-comparators.js valid.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json setprototypeof README.md index.d.ts index.js package.json test index.js sha.js .travis.yml README.md bin.js hash.js index.js package.json sha.js sha1.js sha224.js sha256.js sha384.js sha512.js test hash.js test.js vectors.js signal-exit LICENSE.txt README.md index.js package.json signals.js simple-concat .travis.yml README.md index.js package.json test basic.js simple-get .github dependabot.yml workflows ci.yml README.md index.js package.json slash index.d.ts index.js package.json readme.md stack-utils LICENSE.md index.js package.json readme.md statuses HISTORY.md README.md codes.json index.js package.json stoppable lib stoppable.js package.json readme.md string-width index.d.ts index.js package.json readme.md string_decoder README.md lib string_decoder.js package.json strip-ansi index.d.ts index.js package.json readme.md strip-json-comments index.js package.json readme.md supports-color browser.js index.js package.json readme.md tar-fs .travis.yml README.md index.js package.json test fixtures a hello.txt b a test.txt index.js tar-stream README.md extract.js headers.js index.js pack.js package.json sandbox.js tcp-port-used README.md index.js package.json test.js text-encoding-utf-8 LICENSE.md README.md lib encoding.js encoding.lib.js package.json src encoding.js polyfill.js to-readable-stream index.js package.json readme.md to-regex-range README.md index.js package.json toidentifier HISTORY.md README.md index.js package.json tr46 index.js lib mappingTable.json package.json tslib CopyrightNotice.txt LICENSE.txt README.md modules index.js package.json package.json test validateModuleExportsMatchCommonJS index.js package.json tslib.d.ts tslib.es6.html tslib.es6.js tslib.html tslib.js tunnel-agent README.md index.js package.json tweetnacl AUTHORS.md CHANGELOG.md PULL_REQUEST_TEMPLATE.md README.md nacl-fast.js nacl-fast.min.js nacl.d.ts nacl.js nacl.min.js package.json type-detect README.md index.js package.json type-detect.js type-fest base.d.ts index.d.ts package.json readme.md source async-return-type.d.ts asyncify.d.ts basic.d.ts conditional-except.d.ts conditional-keys.d.ts conditional-pick.d.ts entries.d.ts entry.d.ts except.d.ts fixed-length-array.d.ts iterable-element.d.ts literal-union.d.ts merge-exclusive.d.ts merge.d.ts mutable.d.ts opaque.d.ts package-json.d.ts partial-deep.d.ts promisable.d.ts promise-value.d.ts readonly-deep.d.ts require-at-least-one.d.ts require-exactly-one.d.ts set-optional.d.ts set-required.d.ts set-return-type.d.ts stringified.d.ts tsconfig-json.d.ts union-to-intersection.d.ts utilities.d.ts value-of.d.ts ts41 camel-case.d.ts delimiter-case.d.ts index.d.ts kebab-case.d.ts pascal-case.d.ts snake-case.d.ts typedarray-to-buffer .airtap.yml .travis.yml README.md index.js package.json test basic.js u2f-api .travis.yml README.md index.d.ts index.js lib google-u2f-api.js u2f-api.js package.json scripts test.sh test.in setup.js tsconfig.json u2f-api index.ts u3 README.md index.js lib cache.js eachCombination.js index.js package.json unique-string index.d.ts index.js package.json readme.md update-notifier check.js index.js package.json readme.md url-parse-lax index.js package.json readme.md usb CHANGELOG.md README.md libusb .private README.txt bd.cmd bm.sh bwince.cmd post-rewrite.sh pre-commit.sh wbs.txt wbs_wince.txt .travis.yml INSTALL_WIN.txt README.md Xcode config.h android config.h appveyor.yml appveyor_cygwin.bat appveyor_minGW.bat autogen.sh bootstrap.sh examples dpfp.c dpfp_threaded.c ezusb.c ezusb.h fxload.c getopt getopt.c getopt.h getopt1.c hotplugtest.c listdevs.c sam3u_benchmark.c testlibusb.c xusb.c libusb core.c descriptor.c hotplug.c hotplug.h io.c libusb.h libusbi.h os darwin_usb.c darwin_usb.h haiku_pollfs.cpp haiku_usb.h haiku_usb_backend.cpp haiku_usb_raw.cpp haiku_usb_raw.h linux_netlink.c linux_udev.c linux_usbfs.c linux_usbfs.h netbsd_usb.c openbsd_usb.c poll_posix.c poll_posix.h poll_windows.c poll_windows.h sunos_usb.c sunos_usb.h threads_posix.c threads_posix.h threads_windows.c threads_windows.h wince_usb.c wince_usb.h windows_common.h windows_nt_common.c windows_nt_common.h windows_nt_shared_types.h windows_usbdk.c windows_usbdk.h windows_winusb.c windows_winusb.h strerror.c sync.c version.h version_nano.h msvc appveyor.bat config.h ddk_build.cmd errno.h inttypes.h libusb_2005.sln libusb_2010.sln libusb_2012.sln libusb_2013.sln libusb_2015.sln libusb_2017.sln libusb_wince.sln missing.c missing.h stdint.h tests libusb_testlib.h stress.c testlib.c travis-autogen.sh libusb_config config.h node_modules node-addon-api LICENSE.md README.md index.js napi-inl.deprecated.h napi-inl.h napi.h nothing.c package-support.json package.json tools README.md check-napi.js clang-format.js conversion.js eslint-format.js package.json src helpers.h node_usb.h uv_async_queue.h test usb.coffee usb.js util-deprecate History.md README.md browser.js node.js package.json uuid CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md dist esm-browser index.js md5.js nil.js parse.js regex.js rng.js sha1.js stringify.js v1.js v3.js v35.js v4.js v5.js validate.js version.js esm-node index.js md5.js nil.js parse.js regex.js rng.js sha1.js stringify.js v1.js v3.js v35.js v4.js v5.js validate.js version.js index.js md5-browser.js md5.js nil.js parse.js regex.js rng-browser.js rng.js sha1-browser.js sha1.js stringify.js umd uuid.min.js uuidNIL.min.js uuidParse.min.js uuidStringify.min.js uuidValidate.min.js uuidVersion.min.js uuidv1.min.js uuidv3.min.js uuidv4.min.js uuidv5.min.js uuid-bin.js v1.js v3.js v35.js v4.js v5.js validate.js version.js package.json v8flags README.md config-path.js index.js package.json webidl-conversions LICENSE.md README.md lib index.js package.json whatwg-url LICENSE.txt README.md lib URL-impl.js URL.js public-api.js url-state-machine.js utils.js package.json wide-align README.md align.js package.json widest-line index.d.ts index.js package.json readme.md wrap-ansi index.js package.json readme.md wrappy README.md package.json wrappy.js write-file-atomic CHANGELOG.md README.md index.js package.json xdg-basedir index.d.ts index.js package.json readme.md y18n CHANGELOG.md README.md build lib cjs.js index.js platform-shims node.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md browser.js build lib index.js string-utils.js tokenize-arg-string.js yargs-parser-types.js yargs-parser.js package.json yargs CHANGELOG.md README.md build lib argsert.js command.js completion-templates.js completion.js middleware.js parse-command.js typings common-types.js yargs-parser-types.js usage.js utils apply-extends.js is-promise.js levenshtein.js obj-filter.js process-argv.js set-blocking.js which-module.js validation.js yargs-factory.js yerror.js helpers index.js package.json locales be.json de.json en.json es.json fi.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json package-lock.json package.json | Inspector mode only ----------- | | | cuda_builtin_vars.h - CUDA built-in variables __clang_cuda_cmath.h - Device-side CUDA cmath support __clang_cuda_device_functions.h - CUDA runtime support __clang_cuda_intrinsics.h - Device-side CUDA intrinsic wrappers __clang_cuda_runtime_wrapper.h - CUDA runtime support __stddef_max_align_t.h - Definition of max_align_t for modules __wmmintrin_aes.h - AES intrinsics __wmmintrin_pclmul.h - PCMUL intrinsics adxintrin.h - ADX intrinsics altivec.h - Standard header for type generic math extensions for CBEA predicates ammintrin.h - SSE4a intrinsics arm64intr.h - ARM64 Windows intrinsics arm_acle.h - ARM Non-Neon intrinsics arm_cmse.h - Arm CMSE support arm_fp16.h - ARM FP16 intrinsics arm_mve.h - ARM MVE intrinsics armintr.h - ARM Windows intrinsics avx2intrin.h - AVX2 intrinsics avx512bf16intrin.h - AVX512_BF16 intrinsics avx512bitalgintrin.h - BITALG intrinsics avx512bwintrin.h - AVX512BW intrinsics avx512cdintrin.h - AVX512CD intrinsics avx512dqintrin.h - AVX512DQ intrinsics avx512erintrin.h - AVX512ER intrinsics avx512fintrin.h - AVX512F intrinsics avx512ifmaintrin.h - IFMA intrinsics avx512ifmavlintrin.h - IFMA intrinsics avx512pfintrin.h - PF intrinsics avx512vbmi2intrin.h - VBMI2 intrinsics avx512vbmiintrin.h - VBMI intrinsics avx512vbmivlintrin.h - VBMI intrinsics avx512vlbf16intrin.h - AVX512_BF16 intrinsics avx512vlbitalgintrin.h - BITALG intrinsics avx512vlbwintrin.h - AVX512VL and AVX512BW intrinsics avx512vlcdintrin.h - AVX512VL and AVX512CD intrinsics avx512vldqintrin.h - AVX512VL and AVX512DQ intrinsics avx512vlintrin.h - AVX512VL intrinsics avx512vlvbmi2intrin.h - VBMI2 intrinsics avx512vlvnniintrin.h - VNNI intrinsics avx512vlvp2intersectintrin.h - VL VP2INTERSECT intrinsics avx512vnniintrin.h - VNNI intrinsics avx512vpintersectintrin.h - VP2INTERSECT intrinsics avx512vpopcntdqintrin.h - AVX512VPOPCNTDQ intrinsics avxintrin.h - AVX intrinsics bmi2intrin.h - BMI2 intrinsics bmiintrin.h - BMI intrinsics cetintrin.h - CET intrinsic cldemoteintrin.h - CLDEMOTE intrinsic clflushoptintrin.h - CLFLUSHOPT intrinsic clwbintrin.h - CLWB intrinsic clzerointrin.h - CLZERO cpuid.h - X86 cpu model detection emmintrin.h - SSE2 intrinsics enqcmdintrin.h - enqcmd intrinsics f16cintrin.h - F16C intrinsics float.h - Characteristics of floating point types fma4intrin.h - FMA4 intrinsics fmaintrin.h - FMA intrinsics fxsrintrin.h - FXSR intrinsic gfniintrin.h - GFNI intrinsics htmintrin.h - Standard header for PowerPC HTM ia32intrin.h immintrin.h - Intel intrinsics intrin.h inttypes.h - Standard header for integer printf macros invpcidintrin.h - INVPCID intrinsic limits.h - Standard header for integer sizes lwpintrin.h - LWP intrinsics lzcntintrin.h - LZCNT intrinsics mm3dnow.h - 3DNow! intrinsics mm_malloc.h - Allocating and Freeing Aligned Memory Blocks mmintrin.h - MMX intrinsics movdirintrin.h msa.h - MIPS MSA intrinsics mwaitxintrin.h - MONITORX MWAITX intrinsics nmmintrin.h - SSE4 intrinsics opencl-c-base.h - OpenCL C language base definitions opencl-c.h - OpenCL C language builtin function header __clang_openmp_math.h - OpenMP target math support __clang_openmp_math_declares.h - OpenMP math declares math.h - Alternative math.h header pconfigintrin.h - X86 platform configuration pkuintrin.h - PKU intrinsics pmmintrin.h - SSE3 intrinsics popcntintrin.h - POPCNT intrinsics emmintrin.h - Implementation of SSE2 intrinsics on PowerPC mm_malloc.h - Implementation of _mm_malloc and _mm_free mmintrin.h - Implementation of MMX intrinsics on PowerPC pmmintrin.h - Implementation of SSE3 intrinsics on PowerPC smmintrin.h - Implementation of SSE4 intrinsics on PowerPC tmmintrin.h - Implementation of SSSE3 intrinsics on PowerPC xmmintrin.h - Implementation of SSE intrinsics on PowerPC prfchwintrin.h - PREFETCHW intrinsic ptwriteintrin.h - PTWRITE intrinsic rdseedintrin.h - RDSEED intrinsics rtmintrin.h - RTM intrinsics s390intrin.h - SystemZ intrinsics sgxintrin.h - X86 SGX intrinsics configuration shaintrin.h - SHA intrinsics smmintrin.h - SSE4 intrinsics stdalign.h - Standard header for alignment stdarg.h - Variable argument handling stdatomic.h - Standard header for atomic types and operations stdbool.h - Standard header for booleans stddef.h - Basic type definitions stdint.h - Standard header for sized integer types stdnoreturn.h - Standard header for noreturn macro tbmintrin.h - TBM intrinsics tgmath.h - Standard header for type generic math tmmintrin.h - SSSE3 intrinsics unwind.h - Stack unwinding vadefs.h vaesintrin.h - VAES intrinsics varargs.h - Variable argument handling vecintrin.h - Vector intrinsics vpclmulqdqintrin.h - VPCLMULQDQ intrinsics waitpkgintrin.h - WAITPKG wmmintrin.h - AES intrinsics x86intrin.h - X86 intrinsics xmmintrin.h - SSE intrinsics xopintrin.h - XOP intrinsics xsavecintrin.h - XSAVEC intrinsic xsaveintrin.h - XSAVE intrinsic xsaveoptintrin.h - XSAVEOPT intrinsic xsavesintrin.h - XSAVES intrinsic xtestintrin.h - XTEST intrinsic __bsd_locale_defaults.h __bsd_locale_fallbacks.h __cxxabi_config.h complex.h ctype.h cxxabi.h errno.h math.h float.h inttypes.h limits.h locale.h setjmp.h stdbool.h stddef.h stdint.h stdio.h stdlib.h string.h support android locale_bionic.h fuchsia xlocale.h ibm limits.h locale_mgmt_aix.h support.h xlocale.h musl xlocale.h win32 limits_msvc_win32.h locale_win32.h xlocale __posix_l_fallback.h __strtonum_fallback.h support xlocale __nop_locale_mgmt.h tgmath.h wchar.h wctype.h nested-env-vars TypeScript ThirdPartyNotices DefinitelyTyped Unicode WebGL End of ThirdPartyNotices
# color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # flagged-respawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A tool for respawning node binaries when special flags are present. ## What is it? Say you wrote a command line tool that runs arbitrary javascript (e.g. task runner, test framework, etc). For the sake of discussion, let's pretend it's a testing harness you've named `testify`. Everything is going splendidly until one day you decide to test some code that relies on a feature behind a v8 flag in node (`--harmony`, for example). Without much thought, you run `testify --harmony spec tests.js`. It doesn't work. After digging around for a bit, you realize this produces a [`process.argv`](http://nodejs.org/docs/latest/api/process.html#process_process_argv) of: `['node', '/usr/local/bin/test', '--harmony', 'spec', 'tests.js']` Crap. The `--harmony` flag is in the wrong place! It should be applied to the **node** command, not our binary. What we actually wanted was this: `['node', '--harmony', '/usr/local/bin/test', 'spec', 'tests.js']` Flagged-respawn fixes this problem and handles all the edge cases respawning creates, such as: - Providing a method to determine if a respawn is needed. - Piping stderr/stdout from the child into the parent. - Making the parent process exit with the same code as the child. - If the child is killed, making the parent exit with the same signal. To see it in action, clone this repository and run `npm install` / `npm run respawn` / `npm run nospawn`. ## Sample Usage ```js #!/usr/bin/env node const flaggedRespawn = require('flagged-respawn'); // get a list of all possible v8 flags for the running version of node const v8flags = require('v8flags').fetch(); flaggedRespawn(v8flags, process.argv, function (ready, child) { if (ready) { console.log('Running!'); // your cli code here } else { console.log('Special flags found, respawning.'); } if (process.pid !== child.pid) { console.log('Respawned to PID:', child.pid); } }); ``` ## API ### <u>flaggedRespawn(flags, argv, [ forcedFlags, ] callback) : Void</u> Respawns the script itself when *argv* has special flag contained in *flags* and/or *forcedFlags* is not empty. Because members of *flags* and *forcedFlags* are passed to `node` command, each of them needs to be a node flag or a V8 flag. #### Forbid respawning If `--no-respawning` flag is given in *argv*, this function does not respawned even if *argv* contains members of flags or *forcedFlags* is not empty. (This flag is also used internally to prevent from respawning more than once). #### Parameter: | Parameter | Type | Description | |:--------------|:------:|:----------------------------------------------------| | *flags* | Array | An array of node flags and V8 flags which are available when present in *argv*. | | *argv* | Array | Command line arguments to respawn. | | *forcedFlags* | Array or String | An array of node flags or a string of a single flag and V8 flags for respawning forcely. | | *callback* | function | A called function when not respawning or after respawned. | * **<u><i>callback</i>(ready, proc, argv) : Void</u>** *callback* function is called both when respawned or not, and it can be distinguished by callback's argument: *ready*. (*ready* indicates whether a process spawned its child process (false) or not (true), but it does not indicate whether a process is a spawned child process or not. *ready* for a spawned child process is true.) *argv* is an array of command line arguments which is respawned (when *ready* is false) or is passed current process except flags within *flags* and `--no-respawning` (when *ready* is true). **Parameter:** | Parameter | Type | Description | |:----------|:-------:|:--------------------------| | *ready* | boolean | True, if not respawning and is ready to execute main function. | | *proc* | object | Child process object if respawned, otherwise current process object. | | *argv* | Array | An array of command line arguments. | ## License MIT [downloads-image]: http://img.shields.io/npm/dm/flagged-respawn.svg [npm-url]: https://www.npmjs.com/package/flagged-respawn [npm-image]: http://img.shields.io/npm/v/flagged-respawn.svg [travis-url]: https://travis-ci.org/gulpjs/flagged-respawn [travis-image]: http://img.shields.io/travis/gulpjs/flagged-respawn.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/flagged-respawn [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/flagged-respawn.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/flagged-respawn [coveralls-image]: http://img.shields.io/coveralls/gulpjs/flagged-respawn/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Sponsors [![Scout APM](./sponsors/scout-apm.png)](https://scoutapm.com/) My Open Source work is supported by [Scout APM](https://scoutapm.com/) and [other sponsors](https://github.com/sponsors/indutny). ## Notation ### Prefixes There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the end of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this trick one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # axios // env The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually. # simple-concat [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/simple-concat/master.svg [travis-url]: https://travis-ci.org/feross/simple-concat [npm-image]: https://img.shields.io/npm/v/simple-concat.svg [npm-url]: https://npmjs.org/package/simple-concat [downloads-image]: https://img.shields.io/npm/dm/simple-concat.svg [downloads-url]: https://npmjs.org/package/simple-concat [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Super-minimalist version of [`concat-stream`](https://github.com/maxogden/concat-stream). Less than 15 lines! ## install ``` npm install simple-concat ``` ## usage This example is longer than the implementation. ```js var s = new stream.PassThrough() concat(s, function (err, buf) { if (err) throw err console.error(buf) }) s.write('abc') setTimeout(function () { s.write('123') }, 10) setTimeout(function () { s.write('456') }, 20) setTimeout(function () { s.end('789') }, 30) ``` ## license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` # tslib This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions. This library is primarily used by the `--importHelpers` flag in TypeScript. When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: ```ts var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; exports.x = {}; exports.y = __assign({}, exports.x); ``` will instead be emitted as something like the following: ```ts var tslib_1 = require("tslib"); exports.x = {}; exports.y = tslib_1.__assign({}, exports.x); ``` Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. # Installing For the latest stable version, run: ## npm ```sh # TypeScript 2.3.3 or later npm install tslib # TypeScript 2.3.2 or earlier npm install [email protected] ``` ## yarn ```sh # TypeScript 2.3.3 or later yarn add tslib # TypeScript 2.3.2 or earlier yarn add [email protected] ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install [email protected] ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install [email protected] ``` # Usage Set the `importHelpers` compiler option on the command line: ``` tsc --importHelpers file.ts ``` or in your tsconfig.json: ```json { "compilerOptions": { "importHelpers": true } } ``` #### For bower and JSPM users You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: ```json { "compilerOptions": { "module": "amd", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["bower_components/tslib/tslib.d.ts"] } } } ``` For JSPM users: ```json { "compilerOptions": { "module": "system", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["jspm_packages/npm/tslib@1.[version].0/tslib.d.ts"] } } } ``` # Contribute There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. * [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). * Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). # Documentation * [Quick tutorial](http://www.typescriptlang.org/Tutorial) * [Programming handbook](http://www.typescriptlang.org/Handbook) * [Homepage](http://www.typescriptlang.org/) <table><thead> <tr> <th>Linux</th> <th>OS X</th> <th>Windows</th> <th>Coverage</th> <th>Downloads</th> </tr> </thead><tbody><tr> <td colspan="2" align="center"> <a href="https://travis-ci.org/kaelzhang/node-ignore"> <img src="https://travis-ci.org/kaelzhang/node-ignore.svg?branch=master" alt="Build Status" /></a> </td> <td align="center"> <a href="https://ci.appveyor.com/project/kaelzhang/node-ignore"> <img src="https://ci.appveyor.com/api/projects/status/github/kaelzhang/node-ignore?branch=master&svg=true" alt="Windows Build Status" /></a> </td> <td align="center"> <a href="https://codecov.io/gh/kaelzhang/node-ignore"> <img src="https://codecov.io/gh/kaelzhang/node-ignore/branch/master/graph/badge.svg" alt="Coverage Status" /></a> </td> <td align="center"> <a href="https://www.npmjs.org/package/ignore"> <img src="http://img.shields.io/npm/dm/ignore.svg" alt="npm module downloads per month" /></a> </td> </tr></tbody></table> # ignore `ignore` is a manager, filter and parser which implemented in pure JavaScript according to the [.gitignore spec 2.22.1](http://git-scm.com/docs/gitignore). `ignore` is used by eslint, gitbook and [many others](https://www.npmjs.com/browse/depended/ignore). Pay **ATTENTION** that [`minimatch`](https://www.npmjs.org/package/minimatch) (which used by `fstream-ignore`) does not follow the gitignore spec. To filter filenames according to a .gitignore file, I recommend this npm package, `ignore`. To parse an `.npmignore` file, you should use `minimatch`, because an `.npmignore` file is parsed by npm using `minimatch` and it does not work in the .gitignore way. ### Tested on `ignore` is fully tested, and has more than **five hundreds** of unit tests. - Linux + Node: `0.8` - `7.x` - Windows + Node: `0.10` - `7.x`, node < `0.10` is not tested due to the lack of support of appveyor. Actually, `ignore` does not rely on any versions of node specially. Since `4.0.0`, ignore will no longer support `node < 6` by default, to use in node < 6, `require('ignore/legacy')`. For details, see [CHANGELOG](https://github.com/kaelzhang/node-ignore/blob/master/CHANGELOG.md). ## Table Of Main Contents - [Usage](#usage) - [`Pathname` Conventions](#pathname-conventions) - See Also: - [`glob-gitignore`](https://www.npmjs.com/package/glob-gitignore) matches files using patterns and filters them according to gitignore rules. - [Upgrade Guide](#upgrade-guide) ## Install ```sh npm i ignore ``` ## Usage ```js import ignore from 'ignore' const ig = ignore().add(['.abc/*', '!.abc/d/']) ``` ### Filter the given paths ```js const paths = [ '.abc/a.js', // filtered out '.abc/d/e.js' // included ] ig.filter(paths) // ['.abc/d/e.js'] ig.ignores('.abc/a.js') // true ``` ### As the filter function ```js paths.filter(ig.createFilter()); // ['.abc/d/e.js'] ``` ### Win32 paths will be handled ```js ig.filter(['.abc\\a.js', '.abc\\d\\e.js']) // if the code above runs on windows, the result will be // ['.abc\\d\\e.js'] ``` ## Why another ignore? - `ignore` is a standalone module, and is much simpler so that it could easy work with other programs, unlike [isaacs](https://npmjs.org/~isaacs)'s [fstream-ignore](https://npmjs.org/package/fstream-ignore) which must work with the modules of the fstream family. - `ignore` only contains utility methods to filter paths according to the specified ignore rules, so - `ignore` never try to find out ignore rules by traversing directories or fetching from git configurations. - `ignore` don't cares about sub-modules of git projects. - Exactly according to [gitignore man page](http://git-scm.com/docs/gitignore), fixes some known matching issues of fstream-ignore, such as: - '`/*.js`' should only match '`a.js`', but not '`abc/a.js`'. - '`**/foo`' should match '`foo`' anywhere. - Prevent re-including a file if a parent directory of that file is excluded. - Handle trailing whitespaces: - `'a '`(one space) should not match `'a '`(two spaces). - `'a \ '` matches `'a '` - All test cases are verified with the result of `git check-ignore`. # Methods ## .add(pattern: string | Ignore): this ## .add(patterns: Array<string | Ignore>): this - **pattern** `String | Ignore` An ignore pattern string, or the `Ignore` instance - **patterns** `Array<String | Ignore>` Array of ignore patterns. Adds a rule or several rules to the current manager. Returns `this` Notice that a line starting with `'#'`(hash) is treated as a comment. Put a backslash (`'\'`) in front of the first hash for patterns that begin with a hash, if you want to ignore a file with a hash at the beginning of the filename. ```js ignore().add('#abc').ignores('#abc') // false ignore().add('\#abc').ignores('#abc') // true ``` `pattern` could either be a line of ignore pattern or a string of multiple ignore patterns, which means we could just `ignore().add()` the content of a ignore file: ```js ignore() .add(fs.readFileSync(filenameOfGitignore).toString()) .filter(filenames) ``` `pattern` could also be an `ignore` instance, so that we could easily inherit the rules of another `Ignore` instance. ## <strike>.addIgnoreFile(path)</strike> REMOVED in `3.x` for now. To upgrade `[email protected]` up to `3.x`, use ```js import fs from 'fs' if (fs.existsSync(filename)) { ignore().add(fs.readFileSync(filename).toString()) } ``` instead. ## .filter(paths: Array&lt;Pathname&gt;): Array&lt;Pathname&gt; ```ts type Pathname = string ``` Filters the given array of pathnames, and returns the filtered array. - **paths** `Array.<Pathname>` The array of `pathname`s to be filtered. ### `Pathname` Conventions: #### 1. `Pathname` should be a `path.relative()`d pathname `Pathname` should be a string that have been `path.join()`ed, or the return value of `path.relative()` to the current directory, ```js // WRONG, an error will be thrown ig.ignores('./abc') // WRONG, for it will never happen, and an error will be thrown // If the gitignore rule locates at the root directory, // `'/abc'` should be changed to `'abc'`. // ``` // path.relative('/', '/abc') -> 'abc' // ``` ig.ignores('/abc') // WRONG, that it is an absolute path on Windows, an error will be thrown ig.ignores('C:\\abc') // Right ig.ignores('abc') // Right ig.ignores(path.join('./abc')) // path.join('./abc') -> 'abc' ``` In other words, each `Pathname` here should be a relative path to the directory of the gitignore rules. Suppose the dir structure is: ``` /path/to/your/repo |-- a | |-- a.js | |-- .b | |-- .c |-- .DS_store ``` Then the `paths` might be like this: ```js [ 'a/a.js' '.b', '.c/.DS_store' ] ``` #### 2. filenames and dirnames `node-ignore` does NO `fs.stat` during path matching, so for the example below: ```js // First, we add a ignore pattern to ignore a directory ig.add('config/') // `ig` does NOT know if 'config', in the real world, // is a normal file, directory or something. ig.ignores('config') // `ig` treats `config` as a file, so it returns `false` ig.ignores('config/') // returns `true` ``` Specially for people who develop some library based on `node-ignore`, it is important to understand that. Usually, you could use [`glob`](http://npmjs.org/package/glob) with `option.mark = true` to fetch the structure of the current directory: ```js import glob from 'glob' glob('**', { // Adds a / character to directory matches. mark: true }, (err, files) => { if (err) { return console.error(err) } let filtered = ignore().add(patterns).filter(files) console.log(filtered) }) ``` ## .ignores(pathname: Pathname): boolean > new in 3.2.0 Returns `Boolean` whether `pathname` should be ignored. ```js ig.ignores('.abc/a.js') // true ``` ## .createFilter() Creates a filter function which could filter an array of paths with `Array.prototype.filter`. Returns `function(path)` the filter function. ## .test(pathname: Pathname) since 5.0.0 Returns `TestResult` ```ts interface TestResult { ignored: boolean // true if the `pathname` is finally unignored by some negative pattern unignored: boolean } ``` - `{ignored: true, unignored: false}`: the `pathname` is ignored - `{ignored: false, unignored: true}`: the `pathname` is unignored - `{ignored: false, unignored: false}`: the `pathname` is never matched by any ignore rules. ## static `ignore.isPathValid(pathname): boolean` since 5.0.0 Check whether the `pathname` is an valid `path.relative()`d path according to the [convention](#1-pathname-should-be-a-pathrelatived-pathname). This method is **NOT** used to check if an ignore pattern is valid. ```js ignore.isPathValid('./foo') // false ``` ## ignore(options) ### `options.ignorecase` since 4.0.0 Similar as the `core.ignorecase` option of [git-config](https://git-scm.com/docs/git-config), `node-ignore` will be case insensitive if `options.ignorecase` is set to `true` (the default value), otherwise case sensitive. ```js const ig = ignore({ ignorecase: false }) ig.add('*.png') ig.ignores('*.PNG') // false ``` ### `options.ignoreCase?: boolean` since 5.2.0 Which is alternative to `options.ignoreCase` ### `options.allowRelativePaths?: boolean` since 5.2.0 This option brings backward compatibility with projects which based on `[email protected]`. If `options.allowRelativePaths` is `true`, `ignore` will not check whether the given path to be tested is [`path.relative()`d](#pathname-conventions). However, passing a relative path, such as `'./foo'` or `'../foo'`, to test if it is ignored or not is not a good practise, which might lead to unexpected behavior ```js ignore({ allowRelativePaths: true }).ignores('../foo/bar.js') // And it will not throw ``` **** # Upgrade Guide ## Upgrade 4.x -> 5.x Since `5.0.0`, if an invalid `Pathname` passed into `ig.ignores()`, an error will be thrown, unless `options.allowRelative = true` is passed to the `Ignore` factory. While `ignore < 5.0.0` did not make sure what the return value was, as well as ```ts .ignores(pathname: Pathname): boolean .filter(pathnames: Array<Pathname>): Array<Pathname> .createFilter(): (pathname: Pathname) => boolean .test(pathname: Pathname): {ignored: boolean, unignored: boolean} ``` See the convention [here](#1-pathname-should-be-a-pathrelatived-pathname) for details. If there are invalid pathnames, the conversion and filtration should be done by users. ```js import {isPathValid} from 'ignore' // introduced in 5.0.0 const paths = [ // invalid ////////////////// '', false, '../foo', '.', ////////////////// // valid 'foo' ] .filter(isValidPath) ig.filter(paths) ``` ## Upgrade 3.x -> 4.x Since `4.0.0`, `ignore` will no longer support node < 6, to use `ignore` in node < 6: ```js var ignore = require('ignore/legacy') ``` ## Upgrade 2.x -> 3.x - All `options` of 2.x are unnecessary and removed, so just remove them. - `ignore()` instance is no longer an [`EventEmitter`](nodejs.org/api/events.html), and all events are unnecessary and removed. - `.addIgnoreFile()` is removed, see the [.addIgnoreFile](#addignorefilepath) section for details. **** # Collaborators - [@whitecolor](https://github.com/whitecolor) *Alex* - [@SamyPesse](https://github.com/SamyPesse) *Samy Pessé* - [@azproduction](https://github.com/azproduction) *Mikhail Davydov* - [@TrySound](https://github.com/TrySound) *Bogdan Chadkin* - [@JanMattner](https://github.com/JanMattner) *Jan Mattner* - [@ntwb](https://github.com/ntwb) *Stephen Edgar* - [@kasperisager](https://github.com/kasperisager) *Kasper Isager* - [@sandersn](https://github.com/sandersn) *Nathan Shively-Sanders* # Javascript Error Polyfill [![Build Status](https://travis-ci.org/inf3rno/error-polyfill.png?branch=master)](https://travis-ci.org/inf3rno/error-polyfill) Implementing the [V8 Stack Trace API](https://github.com/v8/v8/wiki/Stack-Trace-API) in non-V8 environments as much as possible ## Installation ```bash npm install error-polyfill ``` ```bash bower install error-polyfill ``` ### Environment compatibility Tested on the following environments: Windows 7 - **Node.js** 9.6 - **Chrome** 64.0 - **Firefox** 58.0 - **Internet Explorer** 10.0, 11.0 - **PhantomJS** 2.1 - **Opera** 51.0 Travis - **Node.js** 8, 9 - **Chrome** - **Firefox** - **PhantomJS** The polyfill might work on other environments too due to its adaptive design. I use [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. ### Requirements ES5 support is required, without that the lib throws an Error and stops working. The ES5 features are tested by the [capability](https://github.com/inf3rno/capability) lib run time. Classes are created by the [o3](https://github.com/inf3rno/o3) lib. Utility functions are implemented in the [u3](https://github.com/inf3rno/u3) lib. ## API documentation ### Usage In this documentation I used the framework as follows: ```js require("error-polyfill"); // <- your code here ``` It is recommended to require the polyfill in your main script. ### Getting a past stack trace with `Error.getStackTrace` This static method is not part of the V8 Stack Trace API, but it is recommended to **use `Error.getStackTrace(throwable)` instead of `throwable.stack`** to get the stack trace of Error instances! Explanation: By non-V8 environments we cannot replace the default stack generation algorithm, so we need a workaround to generate the stack when somebody tries to access it. So the original stack string will be parsed and the result will be properly formatted by accessing the stack using the `Error.getStackTrace` method. Arguments and return values: - The `throwable` argument should be an `Error` (descendant) instance, but it can be an `Object` instance as well. - The return value is the generated `stack` of the `throwable` argument. Example: ```js try { theNotDefinedFunction(); } catch (error) { console.log(Error.getStackTrace(error)); // ReferenceError: theNotDefinedFunction is not defined // at ... // ... } ``` ### Capturing the present stack trace with `Error.captureStackTrace` The `Error.captureStackTrace(throwable [, terminator])` sets the present stack above the `terminator` on the `throwable`. Arguments and return values: - The `throwable` argument should be an instance of an `Error` descendant, but it can be an `Object` instance as well. It is recommended to use `Error` descendant instances instead of inline objects, because we can recognize them by type e.g. `error instanceof UserError`. - The optional `terminator` argument should be a `Function`. Only the calls before this function will be reported in the stack, so without a `terminator` argument, the last call in the stack will be the call of the `Error.captureStackTrace`. - There is no return value, the `stack` will be set on the `throwable` so you will be able to access it using `Error.getStackTrace`. The format of the stack depends on the `Error.prepareStackTrace` implementation. Example: ```js var UserError = function (message){ this.name = "UserError"; this.message = message; Error.captureStackTrace(this, this.constructor); }; UserError.prototype = Object.create(Error.prototype); function codeSmells(){ throw new UserError("What's going on?!"); } codeSmells(); // UserError: What's going on?! // at codeSmells (myModule.js:23:1) // ... ``` Limitations: By the current implementation the `terminator` can be only the `Error.captureStackTrace` caller function. This will change soon, but in certain conditions, e.g. by using strict mode (`"use strict";`) it is not possible to access the information necessary to implement this feature. You will get an empty `frames` array and a `warning` in the `Error.prepareStackTrace` when the stack parser meets with such conditions. ### Formatting the stack trace with `Error.prepareStackTrace` The `Error.prepareStackTrace(throwable, frames [, warnings])` formats the stack `frames` and returns the `stack` value for `Error.captureStackTrace` or `Error.getStackTrace`. The native implementation returns a stack string, but you can override that by setting a new function value. Arguments and return values: - The `throwable` argument is an `Error` or `Object` instance coming from the `Error.captureStackTrace` or from the creation of a new `Error` instance. Be aware that in some environments you need to throw that instance to get a parsable stack. Without that you will get only a `warning` by trying to access the stack with `Error.getStackTrace`. - The `frames` argument is an array of `Frame` instances. Each `frame` represents a function call in the stack. You can use these frames to build a stack string. To access information about individual frames you can use the following methods. - `frame.toString()` - Returns the string representation of the frame, e.g. `codeSmells (myModule.js:23:1)`. - `frame.getThis()` - **Cannot be supported.** Returns the context of the call, only V8 environments support this natively. - `frame.getTypeName()` - **Not implemented yet.** Returns the type name of the context, by the global namespace it is `Window` in Chrome. - `frame.getFunction()` - Returns the called function or `undefined` by strict mode. - `frame.getFunctionName()` - **Not implemented yet.** Returns the name of the called function. - `frame.getMethodName()` - **Not implemented yet.** Returns the method name of the called function is a method of an object. - `frame.getFileName()` - **Not implemented yet.** Returns the file name where the function was called. - `frame.getLineNumber()` - **Not implemented yet.** Returns at which line the function was called in the file. - `frame.getColumnNumber()` - **Not implemented yet.** Returns at which column the function was called in the file. This information is not always available. - `frame.getEvalOrigin()` - **Not implemented yet.** Returns the original of an `eval` call. - `frame.isTopLevel()` - **Not implemented yet.** Returns whether the function was called from the top level. - `frame.isEval()` - **Not implemented yet.** Returns whether the called function was `eval`. - `frame.isNative()` - **Not implemented yet.** Returns whether the called function was native. - `frame.isConstructor()` - **Not implemented yet.** Returns whether the called function was a constructor. - The optional `warnings` argument contains warning messages coming from the stack parser. It is not part of the V8 Stack Trace API. - The return value will be the stack you can access with `Error.getStackTrace(throwable)`. If it is an object, it is recommended to add a `toString` method, so you will be able to read it in the console. Example: ```js Error.prepareStackTrace = function (throwable, frames, warnings) { var string = ""; string += throwable.name || "Error"; string += ": " + (throwable.message || ""); if (warnings instanceof Array) for (var warningIndex in warnings) { var warning = warnings[warningIndex]; string += "\n # " + warning; } for (var frameIndex in frames) { var frame = frames[frameIndex]; string += "\n at " + frame.toString(); } return string; }; ``` ### Stack trace size limits with `Error.stackTraceLimit` **Not implemented yet.** You can set size limits on the stack trace, so you won't have any problems because of too long stack traces. Example: ```js Error.stackTraceLimit = 10; ``` ### Handling uncaught errors and rejections **Not implemented yet.** ## Differences between environments and modes Since there is no Stack Trace API standard, every browsers solves this problem differently. I try to document what I've found about these differences as detailed as possible, so it will be easier to follow the code. Overriding the `error.stack` property with custom Stack instances - by Node.js and Chrome the `Error.prepareStackTrace()` can override every `error.stack` automatically right by creation - by Firefox, Internet Explorer and Opera you cannot automatically override every `error.stack` by native errors - by PhantomJS you cannot override the `error.stack` property of native errors, it is not configurable Capturing the current stack trace - by Node.js, Chrome, Firefox and Opera the stack property is added by instantiating a native error - by Node.js and Chrome the stack creation is lazy loaded and cached, so the `Error.prepareStackTrace()` is called only by the first access - by Node.js and Chrome the current stack can be added to any object with `Error.captureStackTrace()` - by Internet Explorer the stack is created by throwing a native error - by PhantomJS the stack is created by throwing any object, but not a primitive Accessing the stack - by Node.js, Chrome, Firefox, Internet Explorer, Opera and PhantomJS you can use the `error.stack` property - by old Opera you have to use the `error.stacktrace` property to get the stack Prefixes and postfixes on the stack string - by Node.js, Chrome, Internet Explorer and Opera you have the `error.name` and the `error.message` in a `{name}: {message}` format at the beginning of the stack string - by Firefox and PhantomJS the stack string does not contain the `error.name` and the `error.message` - by Firefox you have an empty line at the end of the stack string Accessing the stack frames array - by Node.js and Chrome you can access the frame objects directly by overriding the `Error.prepareStackTrace()` - by Firefox, Internet Explorer, PhantomJS, and Opera you need to parse the stack string in order to get the frames The structure of the frame string - by Node.js and Chrome - the frame string of calling a function from a module: `thirdFn (http://localhost/myModule.js:45:29)` - the frame strings contain an ` at ` prefix, which is not present by the `frame.toString()` output, so it is added by the `stack.toString()` - by Firefox - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Internet Explorer - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45:29)` - by PhantomJS - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Opera - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45)` Accessing information by individual frames - by Node.js and Chrome the `frame.getThis()` and the `frame.getFunction()` returns `undefined` by frames originate from [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) code - by Firefox, Internet Explorer, PhantomJS, and Opera the context of the function calls is not accessible, so the `frame.getThis()` cannot be implemented - by Firefox, Internet Explorer, PhantomJS, and Opera functions are not accessible with `arguments.callee.caller` by frames originate from strict mode, so by these frames `frame.getFunction()` can return only `undefined` (this is consistent with V8 behavior) ## License MIT - 2016 Jánszky László Lajos # pbkdf2 [![NPM Package](https://img.shields.io/npm/v/pbkdf2.svg?style=flat-square)](https://www.npmjs.org/package/pbkdf2) [![Build Status](https://img.shields.io/travis/crypto-browserify/pbkdf2.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/pbkdf2) [![Dependency status](https://img.shields.io/david/crypto-browserify/pbkdf2.svg?style=flat-square)](https://david-dm.org/crypto-browserify/pbkdf2#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()` ## Usage ```js var pbkdf2 = require('pbkdf2') var derivedKey = pbkdf2.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') ... ``` For more information on the API, please see the relevant [Node documentation](https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback). For high performance, use the `async` variant (`pbkdf2.pbkdf2`), not `pbkdf2.pbkdf2Sync`, this variant has the oppurtunity to use `window.crypto.subtle` when browserified. ## Credits This module is a derivative of [cryptocoinjs/pbkdf2-sha256](https://github.com/cryptocoinjs/pbkdf2-sha256/), so thanks to [JP Richardson](https://github.com/jprichardson/) for laying the ground work. Thank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2). # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) > Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save braces ``` ## v3.0.0 Released!! See the [changelog](CHANGELOG.md) for details. ## Why use braces? Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. * **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) * **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. * **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. * **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). * **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). * [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` * [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` * [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` * [Supports escaping](#escaping) - To prevent evaluation of special characters. ## Usage The main export is a function that takes one or more brace `patterns` and `options`. ```js const braces = require('braces'); // braces(patterns[, options]); console.log(braces(['{01..05}', '{a..e}'])); //=> ['(0[1-5])', '([a-e])'] console.log(braces(['{01..05}', '{a..e}'], { expand: true })); //=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] ``` ### Brace Expansion vs. Compilation By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. **Compiled** ```js console.log(braces('a/{x,y,z}/b')); //=> ['a/(x|y|z)/b'] console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); //=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] ``` **Expanded** Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): ```js console.log(braces('a/{x,y,z}/b', { expand: true })); //=> ['a/x/b', 'a/y/b', 'a/z/b'] console.log(braces.expand('{01..10}')); //=> ['01','02','03','04','05','06','07','08','09','10'] ``` ### Lists Expand lists (like Bash "sets"): ```js console.log(braces('a/{foo,bar,baz}/*.js')); //=> ['a/(foo|bar|baz)/*.js'] console.log(braces.expand('a/{foo,bar,baz}/*.js')); //=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] ``` ### Sequences Expand ranges of characters (like Bash "sequences"): ```js console.log(braces.expand('{1..3}')); // ['1', '2', '3'] console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] // supports zero-padded ranges console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] ``` See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. ### Steppped ranges Steps, or increments, may be used with ranges: ```js console.log(braces.expand('{2..10..2}')); //=> ['2', '4', '6', '8', '10'] console.log(braces('{2..10..2}')); //=> ['(2|4|6|8|10)'] ``` When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. ### Nesting Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. **"Expanded" braces** ```js console.log(braces.expand('a{b,c,/{x,y}}/e')); //=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] console.log(braces.expand('a/{x,{1..5},y}/c')); //=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] ``` **"Optimized" braces** ```js console.log(braces('a{b,c,/{x,y}}/e')); //=> ['a(b|c|/(x|y))/e'] console.log(braces('a/{x,{1..5},y}/c')); //=> ['a/(x|([1-5])|y)/c'] ``` ### Escaping **Escaping braces** A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: ```js console.log(braces.expand('a\\{d,c,b}e')); //=> ['a{d,c,b}e'] console.log(braces.expand('a{d,c,b\\}e')); //=> ['a{d,c,b}e'] ``` **Escaping commas** Commas inside braces may also be escaped: ```js console.log(braces.expand('a{b\\,c}d')); //=> ['a{b,c}d'] console.log(braces.expand('a{d\\,c,b}e')); //=> ['ad,ce', 'abe'] ``` **Single items** Following bash conventions, a brace pattern is also not expanded when it contains a single character: ```js console.log(braces.expand('a{b}c')); //=> ['a{b}c'] ``` ## Options ### options.maxLength **Type**: `Number` **Default**: `65,536` **Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. ```js console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error ``` ### options.expand **Type**: `Boolean` **Default**: `undefined` **Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). ```js console.log(braces('a/{b,c}/d', { expand: true })); //=> [ 'a/b/d', 'a/c/d' ] ``` ### options.nodupes **Type**: `Boolean` **Default**: `undefined` **Description**: Remove duplicates from the returned array. ### options.rangeLimit **Type**: `Number` **Default**: `1000` **Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. **Examples** ```js // pattern exceeds the "rangeLimit", so it's optimized automatically console.log(braces.expand('{1..1000}')); //=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] // pattern does not exceed "rangeLimit", so it's NOT optimized console.log(braces.expand('{1..100}')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] ``` ### options.transform **Type**: `Function` **Default**: `undefined` **Description**: Customize range expansion. **Example: Transforming non-numeric values** ```js const alpha = braces.expand('x/{a..e}/y', { transform(value, index) { // When non-numeric values are passed, "value" is a character code. return 'foo/' + String.fromCharCode(value) + '-' + index; } }); console.log(alpha); //=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] ``` **Example: Transforming numeric values** ```js const numeric = braces.expand('{1..5}', { transform(value) { // when numeric values are passed, "value" is a number return 'foo/' + value * 2; } }); console.log(numeric); //=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] ``` ### options.quantifiers **Type**: `Boolean` **Default**: `undefined` **Description**: 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. **Examples** ```js const braces = require('braces'); console.log(braces('a/b{1,3}/{x,y,z}')); //=> [ 'a/b(1|3)/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); //=> [ 'a/b{1,3}/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); //=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] ``` ### options.unescape **Type**: `Boolean` **Default**: `undefined` **Description**: Strip backslashes that were used for escaping from the result. ## What is "brace expansion"? Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). In addition to "expansion", braces are also used for matching. In other words: * [brace expansion](#brace-expansion) is for generating new lists * [brace matching](#brace-matching) is for filtering existing lists <details> <summary><strong>More about brace expansion</strong> (click to expand)</summary> There are two main types of brace expansion: 1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` 2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". Here are some example brace patterns to illustrate how they work: **Sets** ``` {a,b,c} => a b c {a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 ``` **Sequences** ``` {1..9} => 1 2 3 4 5 6 7 8 9 {4..-4} => 4 3 2 1 0 -1 -2 -3 -4 {1..20..3} => 1 4 7 10 13 16 19 {a..j} => a b c d e f g h i j {j..a} => j i h g f e d c b a {a..z..3} => a d g j m p s v y ``` **Combination** Sets and sequences can be mixed together or used along with any other strings. ``` {a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar ``` The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. ## Brace matching In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. For example, the pattern `foo/{1..3}/bar` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar ``` But not: ``` baz/1/qux baz/2/qux baz/3/qux ``` Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` ## Brace matching pitfalls Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. ### tldr **"brace bombs"** * brace expansion can eat up a huge amount of processing resources * as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially * users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. ### The solution Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. ### Geometric complexity At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: ``` {1,2}{3,4} => (2X2) => 13 14 23 24 {1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 ``` But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: ``` {1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 249 257 258 259 267 268 269 347 348 349 357 358 359 367 368 369 ``` Now, imagine how this complexity grows given that each element is a n-tuple: ``` {1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) {1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) ``` Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. **More information** Interested in learning more about brace expansion? * [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) * [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) * [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) </details> ## Performance Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. ### Better algorithms Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. **The proof is in the numbers** Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs)| N/A (freezes) | | `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | | `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | | `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | | `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | | `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | | `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | | `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | | `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | | `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | | `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | | `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | | `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | | `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | | `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | | `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | | `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | ### Faster algorithms When you need expansion, braces is still much faster. _(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | | `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | | `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | | `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | | `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | | `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | | `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | | `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm benchmark ``` ### Latest results Braces is more accurate, without sacrificing performance. ```bash # range (expanded) braces x 29,040 ops/sec ±3.69% (91 runs sampled)) minimatch x 4,735 ops/sec ±1.28% (90 runs sampled) # range (optimized for regex) braces x 382,878 ops/sec ±0.56% (94 runs sampled) minimatch x 1,040 ops/sec ±0.44% (93 runs sampled) # nested ranges (expanded) braces x 19,744 ops/sec ±2.27% (92 runs sampled)) minimatch x 4,579 ops/sec ±0.50% (93 runs sampled) # nested ranges (optimized for regex) braces x 246,019 ops/sec ±2.02% (93 runs sampled) minimatch x 1,028 ops/sec ±0.39% (94 runs sampled) # set (expanded) braces x 138,641 ops/sec ±0.53% (95 runs sampled) minimatch x 219,582 ops/sec ±0.98% (94 runs sampled) # set (optimized for regex) braces x 388,408 ops/sec ±0.41% (95 runs sampled) minimatch x 44,724 ops/sec ±0.91% (89 runs sampled) # nested sets (expanded) braces x 84,966 ops/sec ±0.48% (94 runs sampled) minimatch x 140,720 ops/sec ±0.37% (95 runs sampled) # nested sets (optimized for regex) braces x 263,340 ops/sec ±2.06% (92 runs sampled) minimatch x 28,714 ops/sec ±0.40% (90 runs sampled) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 197 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | | 1 | [hemanth](https://github.com/hemanth) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ # responselike > A response-like object for mocking a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/responselike.svg?branch=master)](https://travis-ci.org/lukechilds/responselike) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/responselike/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/responselike?branch=master) [![npm](https://img.shields.io/npm/dm/responselike.svg)](https://www.npmjs.com/package/responselike) [![npm](https://img.shields.io/npm/v/responselike.svg)](https://www.npmjs.com/package/responselike) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). Useful for formatting cached responses so they can be consumed by code expecting a real response. ## Install ```shell npm install --save responselike ``` Or if you're just using for testing you'll want: ```shell npm install --save-dev responselike ``` ## Usage ```js const Response = require('responselike'); const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); response.statusCode; // 200 response.headers; // { foo: 'bar' } response.body; // <Buffer 48 69 21> response.url; // 'https://example.com' response.pipe(process.stdout); // Hi! ``` ## API ### new Response(statusCode, headers, body, url) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). #### statusCode Type: `number` HTTP response status code. #### headers Type: `object` HTTP headers object. Keys will be automatically lowercased. #### body Type: `buffer` A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. #### url Type: `string` Request URL string. ## License MIT © Luke Childs NOTE: The default branch has been renamed! master is now named main If you have a local clone, you can update it by running: ```shell git branch -m master main git fetch origin git branch -u origin/main main ``` # **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead. There are three options for implementing addons: Node-API, nan, or direct use of internal V8, libuv and Node.js libraries. Unless there is a need for direct access to functionality which is not exposed by Node-API as outlined in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) in Node.js core, use Node-API. Refer to [C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) for more information on Node-API. Node-API is an ABI stable C interface provided by Node.js for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as part of Node.js itself. It is intended to insulate native addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. The `node-addon-api` module, which is not part of Node.js, preserves the benefits of the Node-API as it consists only of inline code that depends only on the stable API provided by Node-API. As such, modules built against one version of Node.js using node-addon-api should run without having to be rebuilt with newer versions of Node.js. It is important to remember that *other* Node.js interfaces such as `libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` exclusively and build against a version of Node.js that includes an implementation of Node-API (meaning an active LTS version of Node.js) in order to benefit from ABI stability across Node.js major versions. Node.js provides an [ABI stability guide][] containing a detailed explanation of ABI stability in general, and the Node-API ABI stability guarantee in particular. As new APIs are added to Node-API, node-addon-api must be updated to provide wrappers for those new APIs. For this reason node-addon-api provides methods that allow callers to obtain the underlying Node-API handles so direct calls to Node-API and the use of the objects/methods provided by node-addon-api can be used together. For example, in order to be able to use an API for which the node-addon-api does not yet provide a wrapper. APIs exposed by node-addon-api are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the **ECMA262 Language Specification**. The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. - **[Setup](#setup)** - **[API Documentation](#api)** - **[Examples](#examples)** - **[Tests](#tests)** - **[More resource and info about native Addons](#resources)** - **[Badges](#badges)** - **[Code of Conduct](CODE_OF_CONDUCT.md)** - **[Contributors](#contributors)** - **[License](#license)** ## **Current version: 4.3.0** (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) [![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) <a name="setup"></a> node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-API version. **However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. The oldest Node.js version supported by the current version of node-addon-api is Node.js 12.x. ## Setup - [Installation and usage](doc/setup.md) - [node-gyp](doc/node-gyp.md) - [cmake-js](doc/cmake-js.md) - [Conversion tool](doc/conversion-tool.md) - [Checker tool](doc/checker-tool.md) - [Generator](doc/generator.md) - [Prebuild tools](doc/prebuild_tools.md) <a name="api"></a> ### **API Documentation** The following is the documentation for node-addon-api. - [Full Class Hierarchy](doc/hierarchy.md) - [Addon Structure](doc/addon.md) - Data Types: - [Env](doc/env.md) - [CallbackInfo](doc/callbackinfo.md) - [Reference](doc/reference.md) - [Value](doc/value.md) - [Name](doc/name.md) - [Symbol](doc/symbol.md) - [String](doc/string.md) - [Number](doc/number.md) - [Date](doc/date.md) - [BigInt](doc/bigint.md) - [Boolean](doc/boolean.md) - [External](doc/external.md) - [Object](doc/object.md) - [Array](doc/array.md) - [ObjectReference](doc/object_reference.md) - [PropertyDescriptor](doc/property_descriptor.md) - [Function](doc/function.md) - [FunctionReference](doc/function_reference.md) - [ObjectWrap](doc/object_wrap.md) - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - [Buffer](doc/buffer.md) - [ArrayBuffer](doc/array_buffer.md) - [TypedArray](doc/typed_array.md) - [TypedArrayOf](doc/typed_array_of.md) - [DataView](doc/dataview.md) - [Error Handling](doc/error_handling.md) - [Error](doc/error.md) - [TypeError](doc/type_error.md) - [RangeError](doc/range_error.md) - [Object Lifetime Management](doc/object_lifetime_management.md) - [HandleScope](doc/handle_scope.md) - [EscapableHandleScope](doc/escapable_handle_scope.md) - [Memory Management](doc/memory_management.md) - [Async Operations](doc/async_operations.md) - [AsyncWorker](doc/async_worker.md) - [AsyncContext](doc/async_context.md) - [AsyncWorker Variants](doc/async_worker_variants.md) - [Thread-safe Functions](doc/threadsafe.md) - [ThreadSafeFunction](doc/threadsafe_function.md) - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) - [Promises](doc/promises.md) - [Version management](doc/version_management.md) <a name="examples"></a> ### **Examples** Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** - **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** - **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** - **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** - **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** - **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** - **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** - **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** <a name="tests"></a> ### **Tests** To run the **node-addon-api** tests do: ``` npm install npm test ``` To avoid testing the deprecated portions of the API run ``` npm install npm test --disable-deprecated ``` To run the tests targeting a specific version of Node-API run ``` npm install export NAPI_VERSION=X npm test --NAPI_VERSION=X ``` where X is the version of Node-API you want to target. ### **Debug** To run the **node-addon-api** tests with `--debug` option: ``` npm run-script dev ``` If you want faster build, you might use the following option: ``` npm run-script dev:incremental ``` Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** ### **Benchmarks** You can run the available benchmarks using the following command: ``` npm run-script benchmark ``` See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. <a name="resources"></a> ### **More resource and info about native Addons** - **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** - **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** - **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** - **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** As node-addon-api's core mission is to expose the plain C Node-API as C++ wrappers, tools that facilitate n-api/node-addon-api providing more convenient patterns on developing a Node.js add-ons with n-api/node-addon-api can be published to NPM as standalone packages. It is also recommended to tag such packages with `node-addon-api` to provide more visibility to the community. Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). <a name="other-bindings"></a> ### **Other bindings** - **[napi-rs](https://napi.rs)** - (`Rust`) <a name="badges"></a> ### **Badges** The use of badges is recommended to indicate the minimum version of Node-API required for the module. This helps to determine which Node.js major versions are supported. Addon maintainers can consult the [Node-API support matrix][] to determine which Node.js versions provide a given Node-API version. The following badges are available: ![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) ![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) ![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) ![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) ![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) ![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) ![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) ![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) ![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) ## **Contributing** We love contributions from the community to **node-addon-api**! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. <a name="contributors"></a> ## Team members ### Active | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Chengzhong Wu | [legendecas](https://github.com/legendecas) | | Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Jim Schlight | [jschlight](https://github.com/jschlight) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | | Kevin Eady | [KevinEady](https://github.com/KevinEady) | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | ### Emeritus | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | | Jason Ginchereau | [jasongin](https://github.com/jasongin) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | | Taylor Woll | [boingoing](https://github.com/boingoing) | <a name="license"></a> Licensed under [MIT](./LICENSE.md) [ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ [Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix # Node.js releases data All data is located in `data` directory. `data/raw` contains raw data `nodejs.json` and `iojs.json`. `data/processed` contains `envs.js` with both node.js and io.js data preprocessed to be used by [Browserslist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date and optionally LTS flag. ## Installation ```bash npm install --save node-releases ``` ## Updating data ```bash npm run build ``` This is a build script which fetches data from web, processes it and saves processed data to `data/processed/envs.json`. If you want to run this steps separately you can use commands described below. ### Fetching data ```bash npm run fetch ``` This npm script will download new data to `data/raw` directory. Also it'll download Node.js release schedule into `release-schedule` folder. ### Processing data ```bash npm run process ``` This script generates `envs.json` file from raw data files and saves it to `data/processed` directory. # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # end-of-stream A node module that calls a callback when a readable/writable/duplex stream has completed or failed. npm install end-of-stream [![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream) ## Usage Simply pass a stream and a callback to the `eos`. Both legacy streams, streams2 and stream3 are supported. ``` js var eos = require('end-of-stream'); eos(readableStream, function(err) { // this will be set to the stream instance if (err) return console.log('stream had an error or closed early'); console.log('stream has ended', this === readableStream); }); eos(writableStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished', this === writableStream); }); eos(duplexStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended and finished', this === duplexStream); }); eos(duplexStream, {readable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished but might still be readable'); }); eos(duplexStream, {writable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended but might still be writable'); }); eos(readableStream, {error:false}, function(err) { // do not treat emit('error', err) as a end-of-stream }); ``` ## License MIT ## Related `end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` [![npm version][npm-image]][npm-url] [![build status][travis-image]][travis-url] # u2f-api U2F API for browsers ## API ### Support U2F has for a long time been supported in Chrome, although not with the standard `window.u2f` methods, but through a built-in extension. Nowadays, browsers seem to use `window.u2f` to expose the functionality. Supported browsers are: * Chrome, using Chrome-specific hacks * Opera, using Chrome-specific hacks Firefox, Safari and other browsers still lack U2F support. Since 0.1.0, this library supports the standard `window.u2f` methods. The library should be complemented with server-side functionality, e.g. using the [`u2f`](https://www.npmjs.com/package/u2f) package. ### Basics `u2f-api` exports two main functions and an error "enum". The main functions are `register()` and `sign()`, although since U2F isn't widely supported, the functions `isSupported()` as well as `ensureSupport()` helps you build applications which can use U2F only when the client supports it. The `register()` and `sign()` functions return *cancellable promises*, i.e. promises you can cancel manually. This helps you to ensure your code doesn't continue in success flow and by mistake accept a registration or authentification request. The returned promise has a function `cancel()` which will immediately reject the promise. #### Check or ensure support ```ts import { isSupported } from 'u2f-api' isSupported(): Promise< Boolean > // Doesn't throw/reject ``` ```ts import { ensureSupport } from 'u2f-api' ensureSupport(): Promise< void > // Throws/rejects if not supported ``` #### Register ```ts import { register } from 'u2f-api' register( registerRequests: RegisterRequest[], signRequests: SignRequest[], // optional timeout: number // optional ): Promise< RegisterResponse > ``` The `registerRequests` can be either a RegisterRequest or an array of such. The optional `signRequests` must be, unless ignored, an array of SignRequests. The optional `timeout` is in seconds, and will default to an implementation specific value, e.g. 30. #### Sign ```ts import { sign } from 'u2f-api' sign( signRequests: SignRequest[], timeout: number // optional ): Promise< SignResponse > ``` The values and interpretation of the arguments are the same as with `register( )`. #### Errors `register()` and `sign()` can return rejected promises. The rejection error is an `Error` object with a `metaData` property containing `code` and `type`. The `code` is a numerical value describing the type of the error, and `type` is the name of the error, as defined by the `ErrorCodes` enum in the "FIDO U2F Javascript API" specification. They are: ```js OK = 0 // u2f-api will never throw errors with this code OTHER_ERROR = 1 BAD_REQUEST = 2 CONFIGURATION_UNSUPPORTED = 3 DEVICE_INELIGIBLE = 4 TIMEOUT = 5 CANCELLED = -1 // Added by this library ``` ## Usage ### Loading the library The library is promisified and will use the built-in native promises of the browser, unless another promise library is injected. The following are valid ways to load the library: ```js var u2fApi = require( 'u2f-api' ); // Will use the native Promise // ... or var u2fApi = require( 'u2f-api' )( require( 'bluebird' ) ); // Will use bluebird for promises ``` ### Registering a passkey With `registerRequestsFromServer` somehow received from the server, the client code becomes: ```js u2fApi.register( registerRequestsFromServer ) .then( sendRegisterResponseToServer ) .catch( ... ); ``` ### Signing a passkey With `signRequestsFromServer` also received from the server somehow: ```js u2fApi.sign( signRequestsFromServer ) .then( sendSignResponseToServer ) .catch( ... ); ``` ### Example with checks for client support ```js u2fApi.isSupported( ) .then( function( supported ) { if ( supported ) { return u2fApi.sign( signRequestsFromServer ) .then( sendSignResponseToServer ); } else { ... // Other authentication method } } ) .catch( ... ); ``` ### Canceling As mentioned in the API section above, the returned promises from `register()` and `sign()` have a method `cancel()` which will cancel the request. This is nothing more than a helper function. ## Example implementation U2F is a *challenge-response protocol*. The server sends a `challenge` to the client, which responds with a `response`. This library is intended to be used in the client (the browser). There is another package intended for server-side: https://www.npmjs.com/package/u2f ## Common problems If you get `BAD_REQUEST`, the most common situations are that you either don't use `https` (which you must), or that the AppID doesn't match the server URI. In fact, the AppID must be exactly the base URI to your server (such as `https://your-server.com`), including the port if it isn't 443. For more information, please see https://developers.yubico.com/U2F/Libraries/Client_error_codes.html and https://developers.yubico.com/U2F/App_ID.html [npm-image]: https://img.shields.io/npm/v/u2f-api.svg [npm-url]: https://npmjs.org/package/u2f-api [travis-image]: https://img.shields.io/travis/grantila/u2f-api.svg [travis-url]: https://travis-ci.org/grantila/u2f-api # is-plain-object [![NPM version](https://img.shields.io/npm/v/is-plain-object.svg?style=flat)](https://www.npmjs.com/package/is-plain-object) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-plain-object.svg?style=flat)](https://npmjs.org/package/is-plain-object) [![NPM total downloads](https://img.shields.io/npm/dt/is-plain-object.svg?style=flat)](https://npmjs.org/package/is-plain-object) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-plain-object.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-plain-object) > Returns true if an object was created by the `Object` constructor, or Object.create(null). Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-plain-object ``` Use [isobject](https://github.com/jonschlinkert/isobject) if you only want to check if the value is an object and not an array or null. ## Usage with es modules ```js import { isPlainObject } from 'is-plain-object'; ``` or with commonjs ```js const { isPlainObject } = require('is-plain-object'); ``` **true** when created by the `Object` constructor, or Object.create(null). ```js isPlainObject(Object.create({})); //=> true isPlainObject(Object.create(Object.prototype)); //=> true isPlainObject({foo: 'bar'}); //=> true isPlainObject({}); //=> true isPlainObject(null); //=> true ``` **false** when not created by the `Object` constructor. ```js isPlainObject(1); //=> false isPlainObject(['foo', 'bar']); //=> false isPlainObject([]); //=> false isPlainObject(new Foo); //=> false isPlainObject(Object.create(null)); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-number](https://www.npmjs.com/package/is-number): Returns true if a number or string value is a finite number. Useful for regex… [more](https://github.com/jonschlinkert/is-number) | [homepage](https://github.com/jonschlinkert/is-number "Returns true if a number or string value is a finite number. Useful for regex matches, parsing, user input, etc.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 19 | [jonschlinkert](https://github.com/jonschlinkert) | | 6 | [TrySound](https://github.com/TrySound) | | 6 | [stevenvachon](https://github.com/stevenvachon) | | 3 | [onokumus](https://github.com/onokumus) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 28, 2019._ # Tools ## clang-format The clang-format checking tools is designed to check changed lines of code compared to given git-refs. ## Migration Script The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. ### How To Use To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. ``` npm install node-addon-api ``` Then run the script passing your project directory ``` node ./node_modules/node-addon-api/tools/conversion.js ./ ``` After finish, recompile and debug things that are missed by the script. ### Quick Fixes Here is the list of things that can be fixed easily. 1. Change your methods' return value to void if it doesn't return value to JavaScript. 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); ### Major Reconstructions The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as ``` [ClassName](const Napi::CallbackInfo& info); ``` and define it as ``` [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ ... } ``` This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 2. Move your original constructor code into the new constructor. Delete your original constructor. 3. In your class initialization function, associate native methods in the following way. ``` Napi::FunctionReference constructor; void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { Napi::HandleScope scope(env); Napi::Function ctor = DefineClass(env, "Canvas", { InstanceMethod<&[ClassName]::Func1>("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. # picocolors The tiniest and the fastest library for terminal output formatting with ANSI colors. ```javascript import pc from "picocolors" console.log( pc.green(`How are ${pc.italic(`you`)} doing?`) ) ``` - **No dependencies.** - **14 times** smaller and **2 times** faster than chalk. - Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. - Node.js v6+ & browsers support. Support for both CJS and ESM projects. - TypeScript type declarations included. - [`NO_COLOR`](https://no-color.org/) friendly. ## Docs Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # caniuse-lite A smaller version of caniuse-db, with only the essentials! ## Why? The full data behind [Can I use][1] is incredibly useful for any front end developer, and on the website all of the details from the database are displayed to the user. However in automated tools, [many of these fields go unused][2]; it's not a problem for server side consumption but client side, the less JavaScript that we send to the end user the better. caniuse-lite then, is a smaller dataset that keeps essential parts of the data in a compact format. It does this in multiple ways, such as converting `null` array entries into empty strings, representing support data as an integer rather than a string, and using base62 references instead of longer human-readable keys. This packed data is then reassembled (via functions exposed by this module) into a larger format which is mostly compatible with caniuse-db, and so it can be used as an almost drop-in replacement for caniuse-db for contexts where size on disk is important; for example, usage in web browsers. The API differences are very small and are detailed in the section below. ## API ```js import * as lite from 'caniuse-lite'; ``` ### `lite.agents` caniuse-db provides a full `data.json` file which contains all of the features data. Instead of this large file, caniuse-lite provides this data subset instead, which has the `browser`, `prefix`, `prefix_exceptions`, `usage_global` and `versions` keys from the original. In addition, the subset contains the `release_date` key with release dates (as timestamps) for each version: ```json { "release_date": { "6": 998870400, "7": 1161129600, "8": 1237420800, "9": 1300060800, "10": 1346716800, "11": 1381968000, "5.5": 962323200 } } ``` ### `lite.feature(js)` The `feature` method takes a file from `data/features` and converts it into something that more closely represents the `caniuse-db` format. Note that only the `title`, `stats` and `status` keys are kept from the original data. ### `lite.features` The `features` index is provided as a way to query all of the features that are listed in the `caniuse-db` dataset. Note that you will need to use the `feature` method on values from this index to get a human-readable format. ### `lite.region(js)` The `region` method takes a file from `data/regions` and converts it into something that more closely represents the `caniuse-db` format. Note that *only* the usage data is exposed here (the `data` key in the original files). ## License The data in this repo is available for use under a CC BY 4.0 license (http://creativecommons.org/licenses/by/4.0/). For attribution just mention somewhere that the source is caniuse.com. If you have any questions about using the data for your project please contact me here: http://a.deveria.com/contact [1]: http://caniuse.com/ [2]: https://github.com/Fyrd/caniuse/issues/1827 ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # Statuses [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP status utility for node. This module provides a list of status codes and messages sourced from a few different projects: * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) * The [Node.js project](https://nodejs.org/) * The [NGINX project](https://www.nginx.com/) * The [Apache HTTP Server project](https://httpd.apache.org/) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install statuses ``` ## API <!-- eslint-disable no-unused-vars --> ```js var status = require('statuses') ``` ### var code = status(Integer || String) If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. <!-- eslint-disable no-undef --> ```js status(403) // => 403 status('403') // => 403 status('forbidden') // => 403 status('Forbidden') // => 403 status(306) // throws, as it's not supported by node.js ``` ### status.STATUS_CODES Returns an object which maps status codes to status messages, in the same format as the [Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). ### status.codes Returns an array of all the status codes as `Integer`s. ### var msg = status[code] Map of `code` to `status message`. `undefined` for invalid `code`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status[404] // => 'Not Found' ``` ### var code = status[msg] Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status['not found'] // => 404 status['Not Found'] // => 404 ``` ### status.redirect[code] Returns `true` if a status code is a valid redirect status. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.redirect[200] // => undefined status.redirect[301] // => true ``` ### status.empty[code] Returns `true` if a status code expects an empty body. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.empty[200] // => undefined status.empty[204] // => true status.empty[304] // => true ``` ### status.retry[code] Returns `true` if you should retry the rest. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.retry[501] // => undefined status.retry[503] // => true ``` [npm-image]: https://img.shields.io/npm/v/statuses.svg [npm-url]: https://npmjs.org/package/statuses [node-version-image]: https://img.shields.io/node/v/statuses.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/statuses.svg [travis-url]: https://travis-ci.org/jshttp/statuses [coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg [coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master [downloads-image]: https://img.shields.io/npm/dm/statuses.svg [downloads-url]: https://npmjs.org/package/statuses # merge2 Merge multiple streams into one stream in sequence or parallel. [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Downloads][downloads-image]][downloads-url] ## Install Install with [npm](https://npmjs.org/package/merge2) ```sh npm install merge2 ``` ## Usage ```js const gulp = require('gulp') const merge2 = require('merge2') const concat = require('gulp-concat') const minifyHtml = require('gulp-minify-html') const ngtemplate = require('gulp-ngtemplate') gulp.task('app-js', function () { return merge2( gulp.src('static/src/tpl/*.html') .pipe(minifyHtml({empty: true})) .pipe(ngtemplate({ module: 'genTemplates', standalone: true }) ), gulp.src([ 'static/src/js/app.js', 'static/src/js/locale_zh-cn.js', 'static/src/js/router.js', 'static/src/js/tools.js', 'static/src/js/services.js', 'static/src/js/filters.js', 'static/src/js/directives.js', 'static/src/js/controllers.js' ]) ) .pipe(concat('app.js')) .pipe(gulp.dest('static/dist/js/')) }) ``` ```js const stream = merge2([stream1, stream2], stream3, {end: false}) //... stream.add(stream4, stream5) //.. stream.end() ``` ```js // equal to merge2([stream1, stream2], stream3) const stream = merge2() stream.add([stream1, stream2]) stream.add(stream3) ``` ```js // merge order: // 1. merge `stream1`; // 2. merge `stream2` and `stream3` in parallel after `stream1` merged; // 3. merge 'stream4' after `stream2` and `stream3` merged; const stream = merge2(stream1, [stream2, stream3], stream4) // merge order: // 1. merge `stream5` and `stream6` in parallel after `stream4` merged; // 2. merge 'stream7' after `stream5` and `stream6` merged; stream.add([stream5, stream6], stream7) ``` ```js // nest merge // equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); const streamA = merge2(stream1, stream2) const streamB = merge2(stream3, [stream4, stream5]) const stream = merge2(streamA, streamB) streamA.add(stream6) ``` ## API ```js const merge2 = require('merge2') ``` ### merge2() ### merge2(options) ### merge2(stream1, stream2, ..., streamN) ### merge2(stream1, stream2, ..., streamN, options) ### merge2(stream1, [stream2, stream3, ...], streamN, options) return a duplex stream (mergedStream). streams in array will be merged in parallel. ### mergedStream.add(stream) ### mergedStream.add(stream1, [stream2, stream3, ...], ...) return the mergedStream. ### mergedStream.on('queueDrain', function() {}) It will emit 'queueDrain' when all streams merged. If you set `end === false` in options, this event give you a notice that should add more streams to merge or end the mergedStream. #### stream *option* Type: `Readable` or `Duplex` or `Transform` stream. #### options *option* Type: `Object`. * **end** - `Boolean` - if `end === false` then mergedStream will not be auto ended, you should end by yourself. **Default:** `undefined` * **pipeError** - `Boolean` - if `pipeError === true` then mergedStream will emit `error` event from source streams. **Default:** `undefined` * **objectMode** - `Boolean` . **Default:** `true` `objectMode` and other options(`highWaterMark`, `defaultEncoding` ...) is same as Node.js `Stream`. ## License MIT © [Teambition](https://www.teambition.com) [npm-url]: https://npmjs.org/package/merge2 [npm-image]: http://img.shields.io/npm/v/merge2.svg [travis-url]: https://travis-ci.org/teambition/merge2 [travis-image]: http://img.shields.io/travis/teambition/merge2.svg [downloads-url]: https://npmjs.org/package/merge2 [downloads-image]: http://img.shields.io/npm/dm/merge2.svg?style=flat-square # is-yarn-global [![](https://img.shields.io/travis/LitoMore/is-yarn-global/master.svg)](https://travis-ci.org/LitoMore/is-yarn-global) [![](https://img.shields.io/npm/v/is-yarn-global.svg)](https://www.npmjs.com/package/is-yarn-global) [![](https://img.shields.io/npm/l/is-yarn-global.svg)](https://github.com/LitoMore/is-yarn-global/blob/master/LICENSE) [![](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) Check if installed by yarn globally without any `fs` calls ## Install ```bash $ npm install is-yarn-global ``` ## Usage Just require it in your package. ```javascript const isYarnGlobal = require('is-yarn-global'); console.log(isYarnGlobal()); ``` ## License MIT © [LitoMore](https://github.com/LitoMore) # homedir-polyfill [![NPM version](https://img.shields.io/npm/v/homedir-polyfill.svg?style=flat)](https://www.npmjs.com/package/homedir-polyfill) [![NPM monthly downloads](https://img.shields.io/npm/dm/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![NPM total downloads](https://img.shields.io/npm/dt/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![Linux Build Status](https://img.shields.io/travis/doowb/homedir-polyfill.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/homedir-polyfill) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/homedir-polyfill.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/homedir-polyfill) > Node.js os.homedir polyfill for older versions of node.js. Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save homedir-polyfill ``` ## Usage ```js var homedir = require('homedir-polyfill'); console.log(homedir()); //=> /Users/doowb ``` ## Reasoning This library is a polyfill for the [node.js os.homedir](https://nodejs.org/api/os.html#os_os_homedir) method found in modern versions of node.js. This implementation tries to follow the implementation found in `libuv` by finding the current user using the `process.geteuid()` method and the `/etc/passwd` file. This should usually work in a linux environment, but will also fallback to looking at user specific environment variables to build the user's home directory if neccessary. Since `/etc/passwd` is not available on windows platforms, this implementation will use environment variables to find the home directory. In modern versions of node.js, [os.homedir](https://nodejs.org/api/os.html#os_os_homedir) is used. ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: [parse-passwd](https://www.npmjs.com/package/parse-passwd): Parse a passwd file into a list of users. | [homepage](https://github.com/doowb/parse-passwd "Parse a passwd file into a list of users.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 19 | [doowb](https://github.com/doowb) | | 2 | [martinheidegger](https://github.com/martinheidegger) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2016 - 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on February 21, 2019._ # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC USB Library for Node.JS =============================== [![Build Status](https://github.com/node-usb/node-usb/workflows/prebuild/badge.svg)](https://github.com/node-usb/node-usb/actions) Node.JS library for communicating with USB devices in JavaScript / CoffeeScript. This is a refactoring / rewrite of Christopher Klein's [node-usb](https://github.com/schakko/node-usb). The API is not compatible (hopefully you find it an improvement). It's based entirely on libusb's asynchronous API for better efficiency, and provides a stream API for continuously streaming data or events. Installation ============ Libusb is included as a submodule. On Linux, you'll need libudev to build libusb. On Ubuntu/Debian: `sudo apt-get install build-essential libudev-dev` Then, just run npm install usb to install from npm. See the bottom of this page for instructions for building from a git checkout. ### Windows Use [Zadig](http://zadig.akeo.ie/) to install the WinUSB driver for your USB device. Otherwise you will get `LIBUSB_ERROR_NOT_SUPPORTED` when attempting to open devices. API === var usb = require('usb') usb --- Top-level object. ### usb.getDeviceList() Return a list of `Device` objects for the USB devices attached to the system. ### usb.findByIds(vid, pid) Convenience method to get the first device with the specified VID and PID, or `undefined` if no such device is present. ### usb.LIBUSB_* Constant properties from libusb ### usb.setDebugLevel(level : int) Set the libusb debug level (between 0 and 4) Device ------ Represents a USB device. ### .busNumber Integer USB device number ### .deviceAddress Integer USB device address ### .portNumbers Array containing the USB device port numbers, or `undefined` if not supported on this platform. ### .deviceDescriptor Object with properties for the fields of the device descriptor: - bLength - bDescriptorType - bcdUSB - bDeviceClass - bDeviceSubClass - bDeviceProtocol - bMaxPacketSize0 - idVendor - idProduct - bcdDevice - iManufacturer - iProduct - iSerialNumber - bNumConfigurations ### .configDescriptor Object with properties for the fields of the configuration descriptor: - bLength - bDescriptorType - wTotalLength - bNumInterfaces - bConfigurationValue - iConfiguration - bmAttributes - bMaxPower - extra (Buffer containing any extra data or additional descriptors) ### .allConfigDescriptors Contains all config descriptors of the device (same structure as .configDescriptor above) ### .parent Contains the parent of the device, such as a hub. If there is no parent this property is set to `null`. ### .open() Open the device. All methods below require the device to be open before use. ### .close() Close the device. ### .controlTransfer(bmRequestType, bRequest, wValue, wIndex, data_or_length, callback(error, data)) Perform a control transfer with `libusb_control_transfer`. Parameter `data_or_length` can be a integer length for an IN transfer, or a Buffer for an out transfer. The type must match the direction specified in the MSB of bmRequestType. The `data` parameter of the callback is always undefined for OUT transfers, or will be passed a Buffer for IN transfers. A [package is available to calculate bmRequestType](https://www.npmjs.com/package/bmrequesttype) if needed. ### .setConfiguration(id, callback(error)) Set the device configuration to something other than the default (0). To use this, first call `.open(false)` (which tells it not to auto configure), then before claiming an interface, call this method. ### .getStringDescriptor(index, callback(error, data)) Perform a control transfer to retrieve a string descriptor ### .getBosDescriptor(callback(error, bosDescriptor)) Perform a control transfer to retrieve an object with properties for the fields of the Binary Object Store descriptor: - bLength - bDescriptorType - wTotalLength - bNumDeviceCaps ### .getCapabilities(callback(error, capabilities)) Retrieve a list of Capability objects for the Binary Object Store capabilities of the device. ### .interface(interface) Return the interface with the specified interface number. ### .interfaces List of Interface objects for the interfaces of the default configuration of the device. ### .timeout Timeout in milliseconds to use for control transfers. ### .reset(callback(error)) Performs a reset of the device. Callback is called when complete. Interface --------- ### .endpoint(address) Return the InEndpoint or OutEndpoint with the specified address. ### .endpoints List of endpoints on this interface: InEndpoint and OutEndpoint objects. ### .interface Integer interface number. ### .altSetting Integer alternate setting number. ### .setAltSetting(altSetting, callback(error)) Sets the alternate setting. It updates the `interface.endpoints` array to reflect the endpoints found in the alternate setting. ### .claim() Claims the interface. This method must be called before using any endpoints of this interface. ### .release([closeEndpoints], callback(error)) Releases the interface and resets the alternate setting. Calls callback when complete. It is an error to release an interface with pending transfers. If the optional closeEndpoints parameter is true, any active endpoint streams are stopped (see `Endpoint.stopStream`), and the interface is released after the stream transfers are cancelled. Transfers submitted individually with `Endpoint.transfer` are not affected by this parameter. ### .isKernelDriverActive() Returns `false` if a kernel driver is not active; `true` if active. ### .detachKernelDriver() Detaches the kernel driver from the interface. ### .attachKernelDriver() Re-attaches the kernel driver for the interface. ### .descriptor Object with fields from the interface descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bInterfaceNumber - bAlternateSetting - bNumEndpoints - bInterfaceClass - bInterfaceSubClass - bInterfaceProtocol - iInterface - extra (Buffer containing any extra data or additional descriptors) Capability --------- ### .type Integer capability type. ### .data Buffer capability data. ### .descriptor Object with fields from the capability descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bDevCapabilityType Endpoint -------- Common base for InEndpoint and OutEndpoint, see below. ### .direction Endpoint direction: `"in"` or `"out"`. ### .transferType Endpoint type: `usb.LIBUSB_TRANSFER_TYPE_BULK`, `usb.LIBUSB_TRANSFER_TYPE_INTERRUPT`, or `usb.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS`. ### .descriptor Object with fields from the endpoint descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bEndpointAddress - bmAttributes - wMaxPacketSize - bInterval - bRefresh - bSynchAddress - extra (Buffer containing any extra data or additional descriptors) ### .timeout Sets the timeout in milliseconds for transfers on this endpoint. The default, `0`, is infinite timeout. ### .clearHalt(callback(error)) Clear the halt/stall condition for this endpoint. InEndpoint ---------- Endpoints in the IN direction (device->PC) have this type. ### .transfer(length, callback(error, data)) Perform a transfer to read data from the endpoint. If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback with all data once all packets are complete. `this` in the callback is the InEndpoint object. ### .startPoll(nTransfers=3, transferSize=maxPacketSize) Start polling the endpoint. The library will keep `nTransfers` transfers of size `transferSize` pending in the kernel at all times to ensure continuous data flow. This is handled by the libusb event thread, so it continues even if the Node v8 thread is busy. The `data` and `error` events are emitted as transfers complete. ### .stopPoll(cb) Stop polling. Further data may still be received. The `end` event is emitted and the callback is called once all transfers have completed or canceled. ### Event: data(data : Buffer) Emitted with data received by the polling transfers ### Event: error(error) Emitted when polling encounters an error. All in flight transfers will be automatically canceled and no further polling will be done. You have to wait for the `end` event before you can start polling again. ### Event: end Emitted when polling has been canceled OutEndpoint ----------- Endpoints in the OUT direction (PC->device) have this type. ### .transfer(data, callback(error)) Perform a transfer to write `data` to the endpoint. If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback once all packets are complete. `this` in the callback is the OutEndpoint object. ### Event: error(error) Emitted when the stream encounters an error. ### Event: end Emitted when the stream has been stopped and all pending requests have been completed. UsbDetection ------------ ### usb.on('attach', function(device) { ... }); Attaches a callback to plugging in a `device`. ### usb.on('detach', function(device) { ... }); Attaches a callback to unplugging a `device`. ### usb.refHotplugEvents(); Restore (re-reference) the hotplug events unreferenced by `unrefHotplugEvents()` ### usb.unrefHotplugEvents(); Listening to events will prevent the process to exit. By calling this function, hotplug events will be unreferenced by the event loop, allowing the process to exit even when listening for the `attach` and `detach` events. Development and testing ======================= To build from git: git clone --recursive https://github.com/node-usb/node-usb.git cd node-usb npm install To execute the unit tests, [CoffeeScript](http://coffeescript.org) is required. Run npm test Some tests require an [attached STM32F103 Microprocessor USB device with specific firmware](https://github.com/thegecko/node-usb-test-firmware). npm run --silent full-test npm run --silent valgrind Limitations =========== Does not support: - Configurations other than the default one - Isochronous transfers License ======= MIT Note that the compiled Node extension includes Libusb, and is thus subject to the LGPL. # fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) > Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fill-range ``` ## Usage Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. ```js const fill = require('fill-range'); // fill(from, to[, step, options]); console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 ``` **Params** * `from`: **{String|Number}** the number or letter to start with * `to`: **{String|Number}** the number or letter to end with * `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. * `options`: **{Object|Function}**: See all available [options](#options) ## Examples By default, an array of values is returned. **Alphabetical ranges** ```js console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] ``` **Numerical ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] ``` **Negative ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] ``` **Steps (increments)** ```js // numerical ranges with increments console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] // alphabetical ranges with increments console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] ``` ## Options ### options.step **Type**: `number` (formatted as a string or number) **Default**: `undefined` **Description**: The increment to use for the range. Can be used with letters or numbers. **Example(s)** ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` ### options.strictRanges **Type**: `boolean` **Default**: `false` **Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. **Example(s)** The following are all invalid: ```js fill('1.1', '2'); // decimals not supported in ranges fill('a', '2'); // incompatible range values fill(1, 10, 'foo'); // invalid "step" argument ``` ### options.stringify **Type**: `boolean` **Default**: `undefined` **Description**: Cast all returned values to strings. By default, integers are returned as numbers. **Example(s)** ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] ``` ### options.toRegex **Type**: `boolean` **Default**: `undefined` **Description**: Create a regex-compatible source string, instead of expanding values to an array. **Example(s)** ```js // alphabetical range console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' // alphabetical with step console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' // numerical range console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' // numerical range with zero padding console.log(fill('000001', '100000', { toRegex: true })); //=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' ``` ### options.transform **Type**: `function` **Default**: `undefined` **Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. **Example(s)** ```js // add zero padding console.log(fill(1, 5, value => String(value).padStart(4, '0'))); //=> ['0001', '0002', '0003', '0004', '0005'] ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 116 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [paulmillr](https://github.com/paulmillr) | | 2 | [realityking](https://github.com/realityking) | | 2 | [bluelovers](https://github.com/bluelovers) | | 1 | [edorivai](https://github.com/edorivai) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` # clone-response > Clone a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/clone-response.svg?branch=master)](https://travis-ci.org/lukechilds/clone-response) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/clone-response/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/clone-response?branch=master) [![npm](https://img.shields.io/npm/dm/clone-response.svg)](https://www.npmjs.com/package/clone-response) [![npm](https://img.shields.io/npm/v/clone-response.svg)](https://www.npmjs.com/package/clone-response) Returns a new stream and copies over all properties and methods from the original response giving you a complete duplicate. This is useful in situations where you need to consume the response stream but also want to pass an unconsumed stream somewhere else to be consumed later. ## Install ```shell npm install --save clone-response ``` ## Usage ```js const http = require('http'); const cloneResponse = require('clone-response'); http.get('http://example.com', response => { const clonedResponse = cloneResponse(response); response.pipe(process.stdout); setImmediate(() => { // The response stream has already been consumed by the time this executes, // however the cloned response stream is still available. doSomethingWithResponse(clonedResponse); }); }); ``` Please bear in mind that the process of cloning a stream consumes it. However, you can consume a stream multiple times in the same tick, therefore allowing you to create multiple clones. e.g: ```js const clone1 = cloneResponse(response); const clone2 = cloneResponse(response); // response can still be consumed in this tick but cannot be consumed if passed // into any async callbacks. clone1 and clone2 can be passed around and be // consumed in the future. ``` ## API ### cloneResponse(response) Returns a clone of the passed in response. #### response Type: `stream` A [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) to clone. ## License MIT © Luke Childs tcp-port-used ============= A simple Node.js module to check if a TCP port is currently in use. It returns a deferred promise from the q library. ## Installation npm install tcp-port-used ## Examples To check a port's state: var tcpPortUsed = require('tcp-port-used'); tcpPortUsed.check(44201, '127.0.0.1') .then(function(inUse) { console.log('Port 44201 usage: '+inUse); }, function(err) { console.error('Error on check:', err.message); }); To wait until a port on localhost is available: tcpPortUsed.waitUntilFree(44203, 500, 4000) .then(function() { console.log('Port 44203 is now free.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is available: tcpPortUsed.waitUntilFreeOnHost(44203, 'some.host.com', 500, 4000) .then(function() { console.log('Port 44203 on some.host.com is now free.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on localhost is accepting connections: tcpPortUsed.waitUntilUsed(44204, 500, 4000) .then(function() { console.log('Port 44204 is now in use.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is accepting connections: tcpPortUsed.waitUntilUsedOnHost(44204, 'some.host.com', 500, 4000) .then(function() { console.log('Port 44204 on some.host.com is now in use.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is in specific state: var inUse = true; // wait until the port is in use tcpPortUsed.waitForStatus(44204, 'some.host.com', inUse, 500, 4000) .then(function() { console.log('Port 44204 on some.host.com is now in use.'); }, function(err) { console.log('Error:', err.message); }); ## API ### check(port [, host]) Checks if a TCP port is in use by attempting to connect to the port on host. If no host is specified, the module uses '127.0.0.1' (localhost). When the promise is resolved, there is a parameter `inUse`, when true means the port is in use and false means the port is free. **Parameters:** * **Number|Object** *port* The port you are curious to see if available. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' **Returns:** **Object** A deferred promise from the q module. ### waitUntilFree(port [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the localhost socket is free. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object must contain all the parameters as properties. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilFreeOnHost(port [, host] [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the localhost socket is free. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. If the host is not defined, the modules uses the default '127.0.0.1'. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilUsed(port [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the socket is accepting connections. Will retry on an interval specified in retryTimeMs until the timeout. If the host is not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilUsedOnHost(port [, host] [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the socket is accepting connections. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. If the host is not defined the module uses the default '127.0.0.1'. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitForStatus(port, host, status [, retryTimeMs] [, timeOutMs]) Waits until the port on host matches the boolean status in terms of use. If the status is true, the promise defers until the port is in use. If the status is false the promise defers until the port is free. If the host is undefined or null, the module uses the default '127.0.0.1'. Also, if not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Boolean** *status* A boolean describing the condition to wait for in terms of "in use." True indicates wait until the port is in use. False indicates wait until the port is free. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ## License The MIT License (MIT) Copyright (c) 2013 jut-io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](http://ecma-international.org/ecma-262/6.0/#sec-keywords) and [11.6.2.2](http://ecma-international.org/ecma-262/6.0/#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](http://ecma-international.org/ecma-262/6.0/#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierNameES5(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierNameES6(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 6 section [11.6](http://ecma-international.org/ecma-262/6.0/#sec-names-and-keywords). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](http://ecma-international.org/ecma-262/6.0/#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Read This! **These files are not meant to be edited by hand.** If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. Running `gulp LKG` will then appropriately update the files in this directory. # code-block-writer [![npm version](https://badge.fury.io/js/code-block-writer.svg)](https://badge.fury.io/js/code-block-writer) [![CI](https://github.com/dsherret/code-block-writer/workflows/CI/badge.svg)](https://github.com/dsherret/code-block-writer/actions?query=workflow%3ACI) [![deno doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/code_block_writer/mod.ts) [![stable](http://badges.github.io/stability-badges/dist/stable.svg)](http://github.com/badges/stability-badges) Code writer for JavaScript and TypeScript code. With Deno: ```ts import CodeBlockWriter from "https://deno.land/x/code_block_writer/mod.ts"; ``` Or with Node: ``` npm install --save code-block-writer ``` ## Example <!-- dprint-ignore --> ```typescript import CodeBlockWriter from "https://deno.land/x/code_block_writer/mod.ts"; const writer = new CodeBlockWriter({ // optional options newLine: "\r\n", // default: "\n" indentNumberOfSpaces: 2, // default: 4 useTabs: false, // default: false useSingleQuote: true // default: false }); writer.write("class MyClass extends OtherClass").block(() => { writer.writeLine(`@MyDecorator(1, 2)`); writer.write(`myMethod(myParam: any)`).block(() => { writer.write("return this.post(").quote("myArgument").write(");"); }); }); console.log(writer.toString()); ``` Outputs (using "\r\n" for newlines): <!-- dprint-ignore --> ```js class MyClass extends OtherClass { @MyDecorator(1, 2) myMethod(myParam: any) { return this.post('myArgument'); } } ``` ## Methods - `block(block?: () => void)` - Indents all the code written within and surrounds it in braces. - `inlineBlock(block?: () => void)` - Same as block, but doesn't add a space before the first brace and doesn't add a newline at the end. - `getLength()` - Get the current number of characters. - `writeLine(text: string)` - Writes some text and adds a newline. - `newLine()` - Writes a newline. - `newLineIfLastNot()` - Writes a newline if what was written last wasn't a newline. - `blankLine()` - Writes a blank line. Does not allow consecutive blank lines. - `blankLineIfLastNot()` - Writes a blank line if what was written last wasn't a blank line. - `quote()` - Writes a quote character. - `quote(text: string)` - Writes text surrounded in quotes. - `indent(times?: number)` - Indents the current line. Optionally indents multiple times when providing a number. - `indent(block?: () => void)` - Indents a block of code. - `space(times?: number)` - Writes a space. Optionally writes multiple spaces when providing a number. - `spaceIfLastNot()` - Writes a space if the last was not a space. - `tab(times?: number)` - Writes a tab. Optionally writes multiple tabs when providing a number. - `tabIfLastNot()` - Writes a tab if the last was not a tab. - `write(text: string)` - Writes some text. - `conditionalNewLine(condition: boolean)` - Writes a newline if the condition is matched. - `conditionalBlankLine(condition: boolean)` - Writes a blank line if the condition is matched. - `conditionalWrite(condition: boolean, text: string)` - Writes if the condition is matched. - `conditionalWrite(condition: boolean, textFunc: () => string)` - Writes if the condition is matched. - `conditionalWriteLine(condition: boolean, text: string)` - Writes some text and adds a newline if the condition is matched. - `conditionalWriteLine(condition: boolean, textFunc: () => string)` - Writes some text and adds a newline if the condition is matched. - `setIndentationLevel(indentationLevel: number)` - Sets the current indentation level. - `setIndentationLevel(whitespaceText: string)` - Sets the current indentation level based on the provided whitespace text. - `withIndentationLevel(indentationLevel: number, action: () => void)` - Sets the indentation level within the provided action. - `withIndentationLevel(whitespaceText: string, action: () => void)` - Sets the indentation level based on the provided whitespace text within the action. - `getIndentationLevel()` - Gets the current indentation level. - `queueIndentationLevel(indentationLevel: number)` - Queues an indentation level to be used once a new line is written. - `queueIndentationLevel(whitespaceText: string)` - Queues an indentation level to be used once a new line is written based on the provided whitespace text. - `hangingIndent(action: () => void)` - Writes the code within the action with hanging indentation. - `hangingIndentUnlessBlock(action: () => void)` - Writes the code within the action with hanging indentation unless a block is written going from the first line to the second. - `closeComment()` - Writes text to exit a comment if in a comment. - `unsafeInsert(pos: number, text: string)` - Inserts text into the writer. This will not update the writer's state. Read more in its jsdoc. - `isInComment()` - Gets if the writer is currently in a comment. - `isAtStartOfFirstLineOfBlock()` - Gets if the writer is currently at the start of the first line of the text, block, or indentation block. - `isOnFirstLineOfBlock()` - Gets if the writer is currently on the first line of the text, block, or indentation block. - `isInString()` - Gets if the writer is currently in a string. - `isLastNewLine()` - Gets if the writer last wrote a newline. - `isLastBlankLine()` - Gets if the writer last wrote a blank line. - `isLastSpace()` - Gets if the writer last wrote a space. - `isLastTab()` - Gets if the writer last wrote a tab. - `getLastChar()` - Gets the last character written. - `endsWith(text: string)` - Gets if the writer ends with the provided text. - `iterateLastChars<T>(action: (char: string, index: number) => T | undefined): T | undefined` - Iterates over the writer's characters in reverse order, stopping once a non-null or undefined value is returned and returns that value. - `iterateLastCharCodes<T>(action: (charCode: number, index: number) => T | undefined): T | undefined` - A slightly faster version of `iterateLastChars` that doesn't allocate a string per character. - `getOptions()` - Gets the writer options. - `toString()` - Gets the string. ## Other Features - Does not indent within strings. - Escapes newlines within double and single quotes created with `.quote(text)`. ## C# Version See [CodeBlockWriterSharp](https://github.com/dsherret/CodeBlockWriterSharp). # is-core-module <sup>[![Version Badge][2]][1]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Is this specifier a node.js core module? Optionally provide a node version to check; defaults to the current node version. ## Example ```js var isCore = require('is-core-module'); var assert = require('assert'); assert(isCore('fs')); assert(!isCore('butts')); ``` ## Tests Clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-core-module [2]: https://versionbadg.es/inspect-js/is-core-module.svg [5]: https://david-dm.org/inspect-js/is-core-module.svg [6]: https://david-dm.org/inspect-js/is-core-module [7]: https://david-dm.org/inspect-js/is-core-module/dev-status.svg [8]: https://david-dm.org/inspect-js/is-core-module#info=devDependencies [11]: https://nodei.co/npm/is-core-module.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/is-core-module.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/is-core-module.svg [downloads-url]: https://npm-stat.com/charts.html?package=is-core-module [codecov-image]: https://codecov.io/gh/inspect-js/is-core-module/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/is-core-module/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/is-core-module [actions-url]: https://github.com/inspect-js/is-core-module/actions # ignore-by-default This is a package aimed at Node.js development tools. It provides a list of directories that should probably be ignored by such tools, e.g. when watching for file changes. It's used by [AVA](https://www.npmjs.com/package/ava) and [nodemon](https://www.npmjs.com/package/nodemon). [Please contribute!](./CONTRIBUTING.md) ## Installation ``` npm install ignore-by-default ``` ## Usage The `ignore-by-default` module exports a `directories()` function, which will return an array of directory names. These are the ones you should ignore. ```js // ['.git', '.sass_cache', …] const ignoredDirectories = require('ignore-by-default').directories() ``` The `dist-raw` directory contains JS sources that are distributed verbatim, not compiled nor typechecked via TS. To implement ESM support, we unfortunately must duplicate some of node's built-in functionality that is not exposed via an API. We have copy-pasted the necessary code from https://github.com/nodejs/node/tree/master/lib then modified it to suite our needs. Formatting may be intentionally bad to keep the diff as small as possible, to make it easier to merge upstream changes and understand our modifications. For example, when we need to wrap node's source code in a factory function, we will not indent the function body, to avoid whitespace changes in the diff. One obvious problem with this approach: the code has been pulled from one version of node, whereas users of ts-node run multiple versions of node. Users running node 12 may see that ts-node behaves like node 14, for example. ## `raw` directory Within the `raw` directory, we keep unmodified copies of the node source files. This allows us to use diffing tools to compare files in `raw` to those in `dist-raw`, which will highlight all of the changes we have made. Hopefully, these changes are as minimal as possible. ## Naming convention Not used consistently, but the idea is: `node-<directory>(...-<directory>)-<filename>.js` `node-internal-errors.js` -> `github.com/nodejs/node/blob/TAG/lib/internal/errors.js` So, take the path within node's `lib/` directory, and replace slashes with hyphens. In the `raw` directory, files are suffixed with the version number or revision from which they were downloaded. If they have a `stripped` suffix, this means they have large chunks of code deleted, but no other modifications. This is useful when diffing. Sometimes our `dist-raw` files only have a small part of a much larger node source file. It is easier to diff `raw/*-stripped.js` against `dist-raw/*.js`. semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # signal-exit [![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) [![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) [![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the process to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # tar-fs filesystem bindings for [tar-stream](https://github.com/mafintosh/tar-stream). ``` npm install tar-fs ``` [![build status](https://secure.travis-ci.org/mafintosh/tar-fs.png)](http://travis-ci.org/mafintosh/tar-fs) ## Usage tar-fs allows you to pack directories into tarballs and extract tarballs into directories. It doesn't gunzip for you, so if you want to extract a `.tar.gz` with this you'll need to use something like [gunzip-maybe](https://github.com/mafintosh/gunzip-maybe) in addition to this. ``` js var tar = require('tar-fs') var fs = require('fs') // packing a directory tar.pack('./my-directory').pipe(fs.createWriteStream('my-tarball.tar')) // extracting a directory fs.createReadStream('my-other-tarball.tar').pipe(tar.extract('./my-other-directory')) ``` To ignore various files when packing or extracting add a ignore function to the options. `ignore` is also an alias for `filter`. Additionally you get `header` if you use ignore while extracting. That way you could also filter by metadata. ``` js var pack = tar.pack('./my-directory', { ignore: function(name) { return path.extname(name) === '.bin' // ignore .bin files when packing } }) var extract = tar.extract('./my-other-directory', { ignore: function(name) { return path.extname(name) === '.bin' // ignore .bin files inside the tarball when extracing } }) var extractFilesDirs = tar.extract('./my-other-other-directory', { ignore: function(_, header) { // pass files & directories, ignore e.g. symlinks return header.type !== 'file' && header.type !== 'directory' } }) ``` You can also specify which entries to pack using the `entries` option ```js var pack = tar.pack('./my-directory', { entries: ['file1', 'subdir/file2'] // only the specific entries will be packed }) ``` If you want to modify the headers when packing/extracting add a map function to the options ``` js var pack = tar.pack('./my-directory', { map: function(header) { header.name = 'prefixed/'+header.name return header } }) var extract = tar.extract('./my-directory', { map: function(header) { header.name = 'another-prefix/'+header.name return header } }) ``` Similarly you can use `mapStream` incase you wanna modify the input/output file streams ``` js var pack = tar.pack('./my-directory', { mapStream: function(fileStream, header) { // NOTE: the returned stream HAS to have the same length as the input stream. // If not make sure to update the size in the header passed in here. if (path.extname(header.name) === '.js') { return fileStream.pipe(someTransform) } return fileStream; } }) var extract = tar.extract('./my-directory', { mapStream: function(fileStream, header) { if (path.extname(header.name) === '.js') { return fileStream.pipe(someTransform) } return fileStream; } }) ``` Set `options.fmode` and `options.dmode` to ensure that files/directories extracted have the corresponding modes ``` js var extract = tar.extract('./my-directory', { dmode: parseInt(555, 8), // all dirs should be readable fmode: parseInt(444, 8) // all files should be readable }) ``` It can be useful to use `dmode` and `fmode` if you are packing/unpacking tarballs between *nix/windows to ensure that all files/directories unpacked are readable. Alternatively you can set `options.readable` and/or `options.writable` to set the dmode and fmode to readable/writable. ``` js var extract = tar.extract('./my-directory', { readable: true, // all dirs and files should be readable writable: true, // all dirs and files should be writable }) ``` Set `options.strict` to `false` if you want to ignore errors due to unsupported entry types (like device files) To dereference symlinks (pack the contents of the symlink instead of the link itself) set `options.dereference` to `true`. ## Copy a directory Copying a directory with permissions and mtime intact is as simple as ``` js tar.pack('source-directory').pipe(tar.extract('dest-directory')) ``` ## Interaction with [`tar-stream`](https://github.com/mafintosh/tar-stream) Use `finalize: false` and the `finish` hook to leave the pack stream open for further entries (see [`tar-stream#pack`](https://github.com/mafintosh/tar-stream#packing)), and use `pack` to pass an existing pack stream. ``` js var mypack = tar.pack('./my-directory', { finalize: false, finish: function(sameAsMypack) { mypack.entry({name: 'generated-file.txt'}, "hello") tar.pack('./other-directory', { pack: sameAsMypack }) } }) ``` ## Performance Packing and extracting a 6.1 GB with 2496 directories and 2398 files yields the following results on my Macbook Air. [See the benchmark here](https://gist.github.com/mafintosh/8102201) * tar-fs: 34.261 seconds * [node-tar](https://github.com/isaacs/node-tar): 366.123 seconds (or 10x slower) ## License MIT # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # ansi-align > align-text with ANSI support for CLIs [![Build Status](https://travis-ci.org/nexdrew/ansi-align.svg?branch=master)](https://travis-ci.org/nexdrew/ansi-align) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/ansi-align/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/ansi-align?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) [![Greenkeeper badge](https://badges.greenkeeper.io/nexdrew/ansi-align.svg)](https://greenkeeper.io/) Easily center- or right- align a block of text, carefully ignoring ANSI escape codes. E.g. turn this: <img width="281" alt="ansi text block no alignment :(" src="https://cloud.githubusercontent.com/assets/1929625/14937509/7c3076dc-0ed7-11e6-8c16-4f6a4ccc8346.png"> Into this: <img width="278" alt="ansi text block center aligned!" src="https://cloud.githubusercontent.com/assets/1929625/14937510/7c3ca0b0-0ed7-11e6-8f0a-541ca39b6e0a.png"> ## Install ```sh npm install --save ansi-align ``` ```js var ansiAlign = require('ansi-align') ``` ## API ### `ansiAlign(text, [opts])` Align the given text per the line with the greatest [`string-width`](https://github.com/sindresorhus/string-width), returning a new string (or array). #### Arguments - `text`: required, string or array The text to align. If a string is given, it will be split using either the `opts.split` value or `'\n'` by default. If an array is given, a different array of modified strings will be returned. - `opts`: optional, object Options to change behavior, see below. #### Options - `opts.align`: string, default `'center'` The alignment mode. Use `'center'` for center-alignment, `'right'` for right-alignment, or `'left'` for left-alignment. Note that the given `text` is assumed to be left-aligned already, so specifying `align: 'left'` just returns the `text` as is (no-op). - `opts.split`: string or RegExp, default `'\n'` The separator to use when splitting the text. Only used if text is given as a string. - `opts.pad`: string, default `' '` The value used to left-pad (prepend to) lines of lesser width. Will be repeated as necessary to adjust alignment to the line with the greatest width. ### `ansiAlign.center(text)` Alias for `ansiAlign(text, { align: 'center' })`. ### `ansiAlign.right(text)` Alias for `ansiAlign(text, { align: 'right' })`. ### `ansiAlign.left(text)` Alias for `ansiAlign(text, { align: 'left' })`, which is a no-op. ## Similar Packages - [`center-align`](https://github.com/jonschlinkert/center-align): Very close to this package, except it doesn't support ANSI codes. - [`left-pad`](https://github.com/camwest/left-pad): Great for left-padding but does not support center alignment or ANSI codes. - Pretty much anything by the [chalk](https://github.com/chalk) team ## License ISC © Contributors # pretty-format Stringify any JavaScript value. - Serialize built-in JavaScript types. - Serialize application-specific data types with built-in or user-defined plugins. ## Installation ```sh $ yarn add pretty-format ``` ## Usage ```js const {format: prettyFormat} = require('pretty-format'); // CommonJS ``` ```js import {format as prettyFormat} from 'pretty-format'; // ES2015 modules ``` ```js const val = {object: {}}; val.circularReference = val; val[Symbol('foo')] = 'foo'; val.map = new Map([['prop', 'value']]); val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); /* Object { "array": Array [ -0, Infinity, NaN, ], "circularReference": [Circular], "map": Map { "prop" => "value", }, "object": Object {}, Symbol(foo): "foo", } */ ``` ## Usage with options ```js function onClick() {} console.log(prettyFormat(onClick)); /* [Function onClick] */ const options = { printFunctionName: false, }; console.log(prettyFormat(onClick, options)); /* [Function] */ ``` <!-- prettier-ignore --> | key | type | default | description | | :-------------------- | :-------- | :--------- | :------------------------------------------------------ | | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function`| `undefined`| compare function used when sorting object keys | | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions | | `escapeString` | `boolean` | `true` | escape special characters in strings | | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | | `indent` | `number` | `2` | spaces in each level of indentation | | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | `[]` | plugins to serialize application-specific data types | | `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | | `printFunctionName` | `boolean` | `true` | include or omit the name of a function | | `theme` | `object` | | colors to highlight syntax in terminal | Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors) ```js const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green', }; ``` ## Usage with plugins The `pretty-format` package provides some built-in plugins, including: - `ReactElement` for elements from `react` - `ReactTestComponent` for test objects from `react-test-renderer` ```js // CommonJS const React = require('react'); const renderer = require('react-test-renderer'); const {format: prettyFormat, plugins} = require('pretty-format'); const {ReactElement, ReactTestComponent} = plugins; ``` ```js // ES2015 modules and destructuring assignment import React from 'react'; import renderer from 'react-test-renderer'; import {plugins, format as prettyFormat} from 'pretty-format'; const {ReactElement, ReactTestComponent} = plugins; ``` ```js const onClick = () => {}; const element = React.createElement('button', {onClick}, 'Hello World'); const formatted1 = prettyFormat(element, { plugins: [ReactElement], printFunctionName: false, }); const formatted2 = prettyFormat(renderer.create(element).toJSON(), { plugins: [ReactTestComponent], printFunctionName: false, }); /* <button onClick=[Function] > Hello World </button> */ ``` ## Usage in Jest For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**. To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then: In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration. ```js import serializer from 'my-serializer-module'; expect.addSnapshotSerializer(serializer); // tests which have `expect(value).toMatchSnapshot()` assertions ``` For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file: ```json { "jest": { "snapshotSerializers": ["my-serializer-module"] } } ``` ## Writing plugins A plugin is a JavaScript object. If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either: - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later) - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method) ### test Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors: - `TypeError: Cannot read property 'whatever' of null` - `TypeError: Cannot read property 'whatever' of undefined` For example, `test` method of built-in `ReactElement` plugin: ```js const elementSymbol = Symbol.for('react.element'); const test = val => val && val.$$typeof === elementSymbol; ``` Pay attention to efficiency in `test` because `pretty-format` calls it often. ### serialize The **improved** interface is available in **version 21** or later. Write `serialize` to return a string, given the arguments: - `val` which “passed the test” - unchanging `config` object: derived from `options` - current `indentation` string: concatenate to `indent` from `config` - current `depth` number: compare to `maxDepth` from `config` - current `refs` array: find circular references in objects - `printer` callback function: serialize children ### config <!-- prettier-ignore --> | key | type | description | | :------------------ | :-------- | :------------------------------------------------------ | | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function`| compare function used when sorting object keys | | `colors` | `Object` | escape codes for colors to highlight syntax | | `escapeRegex` | `boolean` | escape special characters in regular expressions | | `escapeString` | `boolean` | escape special characters in strings | | `indent` | `string` | spaces in each level of indentation | | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on | | `min` | `boolean` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | plugins to serialize application-specific data types | | `printFunctionName` | `boolean` | include or omit the name of a function | | `spacingInner` | `strong` | spacing to separate items in a list | | `spacingOuter` | `strong` | spacing to enclose a list of items | Each property of `colors` in `config` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) Some properties in `config` are derived from `min` in `options`: - `spacingInner` and `spacingOuter` are **newline** if `min` is `false` - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true` ### Example of serialize and test This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays. ```js // We reused more code when we factored out a function for child items // that is independent of depth, name, and enclosing punctuation (see below). const SEPARATOR = ','; function serializeItems(items, config, indentation, depth, refs, printer) { if (items.length === 0) { return ''; } const indentationItems = indentation + config.indent; return ( config.spacingOuter + items .map( item => indentationItems + printer(item, config, indentationItems, depth, refs), // callback ) .join(SEPARATOR + config.spacingInner) + (config.min ? '' : SEPARATOR) + // following the last item config.spacingOuter + indentation ); } const plugin = { test(val) { return Array.isArray(val); }, serialize(array, config, indentation, depth, refs, printer) { const name = array.constructor.name; return ++depth > config.maxDepth ? '[' + name + ']' : (config.min ? '' : name + ' ') + '[' + serializeItems(array, config, indentation, depth, refs, printer) + ']'; }, }; ``` ```js const val = { filter: 'completed', items: [ { text: 'Write test', completed: true, }, { text: 'Write serialize', completed: true, }, ], }; ``` ```js console.log( prettyFormat(val, { plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { indent: 4, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { maxDepth: 1, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": [Array], } */ ``` ```js console.log( prettyFormat(val, { min: true, plugins: [plugin], }), ); /* {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]} */ ``` ### print The **original** interface is adequate for plugins: - that **do not** depend on options other than `highlight` or `min` - that **do not** depend on `depth` or `refs` in recursive traversal, and - if values either - do **not** require indentation, or - do **not** occur as children of JavaScript data structures (for example, array) Write `print` to return a string, given the arguments: - `val` which “passed the test” - current `printer(valChild)` callback function: serialize children - current `indenter(lines)` callback function: indent lines at the next level - unchanging `config` object: derived from `options` - unchanging `colors` object: derived from `options` The 3 properties of `config` are `min` in `options` and: - `spacing` and `edgeSpacing` are **newline** if `min` is `false` - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true` Each property of `colors` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) ### Example of print and test This plugin prints functions with the **number of named arguments** excluding rest argument. ```js const plugin = { print(val) { return `[Function ${val.name || 'anonymous'} ${val.length}]`; }, test(val) { return typeof val === 'function'; }, }; ``` ```js const val = { onClick(event) {}, render() {}, }; prettyFormat(val, { plugins: [plugin], }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val); /* Object { "onClick": [Function onClick], "render": [Function render], } */ ``` This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above. ```js prettyFormat(val, { plugins: [pluginOld], printFunctionName: false, }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val, { printFunctionName: false, }); /* Object { "onClick": [Function], "render": [Function], } */ ``` text-encoding-utf-8 ============== This is a **partial** polyfill for the [Encoding Living Standard](https://encoding.spec.whatwg.org/) API for the Web, allowing encoding and decoding of textual data to and from Typed Array buffers for binary data in JavaScript. This is fork of [text-encoding](https://github.com/inexorabletash/text-encoding) that **only** support **UTF-8**. Basic examples and tests are included. ### Install ### There are a few ways you can get the `text-encoding-utf-8` library. #### Node #### `text-encoding-utf-8` is on `npm`. Simply run: ```js npm install text-encoding-utf-8 ``` Or add it to your `package.json` dependencies. ### HTML Page Usage ### ```html <script src="encoding.js"></script> ``` ### API Overview ### Basic Usage ```js var uint8array = TextEncoder(encoding).encode(string); var string = TextDecoder(encoding).decode(uint8array); ``` Streaming Decode ```js var string = "", decoder = TextDecoder(encoding), buffer; while (buffer = next_chunk()) { string += decoder.decode(buffer, {stream:true}); } string += decoder.decode(); // finish the stream ``` ### Encodings ### Only `utf-8` and `UTF-8` are supported. ### Non-Standard Behavior ### Only `utf-8` and `UTF-8` are supported. ### Motivation Binary size matters, especially on a mobile phone. Safari on iOS does not support TextDecoder or TextEncoder. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # `react-is` This package allows you to test arbitrary values and see if they're a particular React element type. ## Installation ```sh # Yarn yarn add react-is # NPM npm install react-is ``` ## Usage ### Determining if a Component is Valid ```js import React from "react"; import * as ReactIs from "react-is"; class ClassComponent extends React.Component { render() { return React.createElement("div"); } } const FunctionComponent = () => React.createElement("div"); const ForwardRefComponent = React.forwardRef((props, ref) => React.createElement(Component, { forwardedRef: ref, ...props }) ); const Context = React.createContext(false); ReactIs.isValidElementType("div"); // true ReactIs.isValidElementType(ClassComponent); // true ReactIs.isValidElementType(FunctionComponent); // true ReactIs.isValidElementType(ForwardRefComponent); // true ReactIs.isValidElementType(Context.Provider); // true ReactIs.isValidElementType(Context.Consumer); // true ReactIs.isValidElementType(React.createFactory("div")); // true ``` ### Determining an Element's Type #### Context ```js import React from "react"; import * as ReactIs from 'react-is'; const ThemeContext = React.createContext("blue"); ReactIs.isContextConsumer(<ThemeContext.Consumer />); // true ReactIs.isContextProvider(<ThemeContext.Provider />); // true ReactIs.typeOf(<ThemeContext.Provider />) === ReactIs.ContextProvider; // true ReactIs.typeOf(<ThemeContext.Consumer />) === ReactIs.ContextConsumer; // true ``` #### Element ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isElement(<div />); // true ReactIs.typeOf(<div />) === ReactIs.Element; // true ``` #### Fragment ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isFragment(<></>); // true ReactIs.typeOf(<></>) === ReactIs.Fragment; // true ``` #### Portal ```js import React from "react"; import ReactDOM from "react-dom"; import * as ReactIs from 'react-is'; const div = document.createElement("div"); const portal = ReactDOM.createPortal(<div />, div); ReactIs.isPortal(portal); // true ReactIs.typeOf(portal) === ReactIs.Portal; // true ``` #### StrictMode ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isStrictMode(<React.StrictMode />); // true ReactIs.typeOf(<React.StrictMode />) === ReactIs.StrictMode; // true ``` semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` # run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg [travis-url]: https://travis-ci.org/feross/run-parallel [npm-image]: https://img.shields.io/npm/v/run-parallel.svg [npm-url]: https://npmjs.org/package/run-parallel [downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg [downloads-url]: https://npmjs.org/package/run-parallel [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Run an array of functions in parallel ![parallel](https://raw.githubusercontent.com/feross/run-parallel/master/img.png) [![Sauce Test Status](https://saucelabs.com/browser-matrix/run-parallel.svg)](https://saucelabs.com/u/run-parallel) ### install ``` npm install run-parallel ``` ### usage #### parallel(tasks, [callback]) Run the `tasks` array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main `callback` is immediately called with the value of the error. Once the `tasks` have completed, the results are passed to the final `callback` as an array. It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling the results. ##### arguments - `tasks` - An array or object containing functions to run. Each function is passed a `callback(err, result)` which it must call on completion with an error `err` (which can be `null`) and an optional `result` value. - `callback(err, results)` - An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. ##### example ```js var parallel = require('run-parallel') parallel([ function (callback) { setTimeout(function () { callback(null, 'one') }, 200) }, function (callback) { setTimeout(function () { callback(null, 'two') }, 100) } ], // optional callback function (err, results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }) ``` This module is basically equavalent to [`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's handy to just have the one function you need instead of the kitchen sink. Modularity! Especially handy if you're serving to the browser and need to reduce your javascript bundle size. Works great in the browser with [browserify](http://browserify.org/)! ### see also - [run-auto](https://github.com/feross/run-auto) - [run-parallel-limit](https://github.com/feross/run-parallel-limit) - [run-series](https://github.com/feross/run-series) - [run-waterfall](https://github.com/feross/run-waterfall) ### license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). node-bindings ============= ### Helper module for loading your native module's `.node` file This is a helper module for authors of Node.js native addon modules. It is basically the "swiss army knife" of `require()`ing your native module's `.node` file. Throughout the course of Node's native addon history, addons have ended up being compiled in a variety of different places, depending on which build tool and which version of node was used. To make matters worse, now the `gyp` build tool can produce either a __Release__ or __Debug__ build, each being built into different locations. This module checks _all_ the possible locations that a native addon would be built at, and returns the first one that loads successfully. Installation ------------ Install with `npm`: ``` bash $ npm install --save bindings ``` Or add it to the `"dependencies"` section of your `package.json` file. Example ------- `require()`ing the proper bindings file for the current node version, platform and architecture is as simple as: ``` js var bindings = require('bindings')('binding.node') // Use your bindings defined in your C files bindings.your_c_function() ``` Nice Error Output ----------------- When the `.node` file could not be loaded, `node-bindings` throws an Error with a nice error message telling you exactly what was tried. You can also check the `err.tries` Array property. ``` Error: Could not load the bindings file. Tried: → /Users/nrajlich/ref/build/binding.node → /Users/nrajlich/ref/build/Debug/binding.node → /Users/nrajlich/ref/build/Release/binding.node → /Users/nrajlich/ref/out/Debug/binding.node → /Users/nrajlich/ref/Debug/binding.node → /Users/nrajlich/ref/out/Release/binding.node → /Users/nrajlich/ref/Release/binding.node → /Users/nrajlich/ref/build/default/binding.node → /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13) at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47) at Module._compile (module.js:449:26) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) ... ``` The searching for the `.node` file will originate from the first directory in which has a `package.json` file is found. License ------- (The MIT License) Copyright (c) 2012 Nathan Rajlich &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # near-api-js [![Build Status](https://travis-ci.com/near/near-api-js.svg?branch=master)](https://travis-ci.com/near/near-api-js) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-api-js) A JavaScript/TypeScript library for development of DApps on the NEAR platform # Documentation [Read the TypeDoc API documentation](https://near.github.io/near-api-js/) --- # Examples ## [Quick Reference](https://github.com/near/near-api-js/blob/master/examples/quick-reference.md) _(Cheat sheet / quick reference)_ ## [Cookbook](https://github.com/near/near-api-js/blob/master/examples/cookbook/README.md) _(Common use cases / more complex examples)_ --- # Contribute to this library 1. Install dependencies yarn 2. Run continuous build with: yarn build -- -w # Publish Prepare `dist` version by running: yarn dist When publishing to npm use [np](https://github.com/sindresorhus/np). --- # Integration Test Start the node by following instructions from [nearcore](https://github.com/nearprotocol/nearcore), then yarn test Tests use sample contract from `near-hello` npm package, see https://github.com/nearprotocol/near-hello # Update error schema Follow next steps: 1. [Change hash for the commit with errors in the nearcore](https://github.com/near/near-api-js/blob/master/gen_error_types.js#L7-L9) 2. Fetch new schema: `node fetch_error_schema.js` 3. `yarn build` to update `lib/**.js` files # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # ripemd160 [![NPM Package](https://img.shields.io/npm/v/ripemd160.svg?style=flat-square)](https://www.npmjs.org/package/ripemd160) [![Build Status](https://img.shields.io/travis/crypto-browserify/ripemd160.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/ripemd160) [![Dependency status](https://img.shields.io/david/crypto-browserify/ripemd160.svg?style=flat-square)](https://david-dm.org/crypto-browserify/ripemd160#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `ripemd160` on pure JavaScript. ## Example ```js var RIPEMD160 = require('ripemd160') console.log(new RIPEMD160().update('42').digest('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 var ripemd160stream = new RIPEMD160() ripemd160stream.end('42') console.log(ripemd160stream.read().toString('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 ``` ## LICENSE MIT Node.js - jsonfile ================ Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._ [![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile) [![build status](https://secure.travis-ci.org/jprichardson/node-jsonfile.svg)](http://travis-ci.org/jprichardson/node-jsonfile) [![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master) <a href="https://github.com/feross/standard"><img src="https://cdn.rawgit.com/feross/standard/master/sticker.svg" alt="Standard JavaScript" width="100"></a> Why? ---- Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying. Installation ------------ npm install --save jsonfile API --- * [`readFile(filename, [options], callback)`](#readfilefilename-options-callback) * [`readFileSync(filename, [options])`](#readfilesyncfilename-options) * [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback) * [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options) ---- ### readFile(filename, [options], callback) `options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). - `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback. If `false`, returns `null` for the object. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' jsonfile.readFile(file, function (err, obj) { if (err) console.error(err) console.dir(obj) }) ``` You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' jsonfile.readFile(file) .then(obj => console.dir(obj)) .catch(error => console.error(error)) ``` ---- ### readFileSync(filename, [options]) `options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). - `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' console.dir(jsonfile.readFileSync(file)) ``` ---- ### writeFile(filename, obj, [options], callback) `options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, function (err) { if (err) console.error(err) }) ``` Or use with promises as follows: ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj) .then(res => { console.log('Write complete') }) .catch(error => console.error(error)) ``` **formatting with spaces:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) { if (err) console.error(err) }) ``` **overriding EOL:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) { if (err) console.error(err) }) ``` **disabling the EOL at the end of file:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) { if (err) console.log(err) }) ``` **appending to an existing JSON file:** You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this. ```js const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) { if (err) console.error(err) }) ``` ---- ### writeFileSync(filename, obj, [options]) `options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end. ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj) ``` **formatting with spaces:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2 }) ``` **overriding EOL:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' }) ``` **disabling the EOL at the end of file:** ```js const jsonfile = require('jsonfile') const file = '/tmp/data.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false }) ``` **appending to an existing JSON file:** You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this. ```js const jsonfile = require('jsonfile') const file = '/tmp/mayAlreadyExistedData.json' const obj = { name: 'JP' } jsonfile.writeFileSync(file, obj, { flag: 'a' }) ``` License ------- (MIT License) Copyright 2012-2016, JP Richardson <[email protected]> ## Follow Redirects Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript const { http, https } = require('follow-redirects'); http.get('http://bit.ly/900913', response => { response.on('data', chunk => { console.log(chunk); }); }).on('error', err => { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript const request = https.request({ host: 'bitly.com', path: '/UHfDGO', }, response => { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); request.end(); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript const followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript const url = require('url'); const { http, https } = require('follow-redirects'); const options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; options.beforeRedirect = (options, response, request) => { // Use this to adjust the request options upon redirecting, // to inspect the latest response headers, // or to cancel the request by throwing an error // response.headers = the redirect response headers // response.statusCode = the redirect response code (eg. 301, 307, etc.) // request.url = the requested URL that resulted in a redirect // request.headers = the headers in the request that resulted in a redirect // request.method = the method of the request that resulted in a redirect if (options.hostname === "example.com") { options.auth = "user:password"; } }; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript const { http, https } = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browser Usage Due to the way the browser works, the `http` and `https` browser equivalents perform redirects by default. By requiring `follow-redirects` this way: ```javascript const http = require('follow-redirects/http'); const https = require('follow-redirects/https'); ``` you can easily tell webpack and friends to replace `follow-redirect` by the built-in versions: ```json { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - [Ruben Verborgh](https://ruben.verborgh.org/) - [Olivier Lalonde](mailto:[email protected]) - [James Talmage](mailto:[email protected]) ## License [MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE) # readable-stream ***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) ```bash npm install --save readable-stream ``` ***Node-core streams for userland*** This package is a mirror of the Streams2 and Streams3 implementations in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;[email protected]&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;[email protected]&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;[email protected]&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; # expand-template > Expand placeholders in a template string. [![npm](https://img.shields.io/npm/v/expand-template.svg)](https://www.npmjs.com/package/expand-template) ![Node version](https://img.shields.io/node/v/expand-template.svg) [![Build Status](https://travis-ci.org/ralphtheninja/expand-template.svg?branch=master)](https://travis-ci.org/ralphtheninja/expand-template) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) ## Install ``` $ npm i expand-template -S ``` ## Usage Default functionality expands templates using `{}` as separators for string placeholders. ```js var expand = require('expand-template')() var template = '{foo}/{foo}/{bar}/{bar}' console.log(expand(template, { foo: 'BAR', bar: 'FOO' })) // -> BAR/BAR/FOO/FOO ``` Custom separators: ```js var expand = require('expand-template')({ sep: '[]' }) var template = '[foo]/[foo]/[bar]/[bar]' console.log(expand(template, { foo: 'BAR', bar: 'FOO' })) // -> BAR/BAR/FOO/FOO ``` ## License All code, unless stated otherwise, is dual-licensed under [`WTFPL`](http://www.wtfpl.net/txt/copying/) and [`MIT`](https://opensource.org/licenses/MIT). # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. <img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png"> ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Node.js: fs-extra ================= `fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`. [![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) [![License](https://img.shields.io/npm/l/fs-extra.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE) [![build status](https://img.shields.io/github/workflow/status/jprichardson/node-fs-extra/Node.js%20CI/master)](https://github.com/jprichardson/node-fs-extra/actions/workflows/ci.yml?query=branch%3Amaster) [![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) Why? ---- I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects. Installation ------------ npm install fs-extra Usage ----- `fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed. You don't ever need to include the original `fs` module again: ```js const fs = require('fs') // this is no longer necessary ``` you can now do this: ```js const fs = require('fs-extra') ``` or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want to name your `fs` variable `fse` like so: ```js const fse = require('fs-extra') ``` you can also keep both, but it's redundant: ```js const fs = require('fs') const fse = require('fs-extra') ``` Sync vs Async vs Async/Await ------------- Most methods are async by default. All async methods will return a promise if the callback isn't passed. Sync methods on the other hand will throw if an error occurs. Also Async/Await will throw an error if one occurs. Example: ```js const fs = require('fs-extra') // Async with promises: fs.copy('/tmp/myfile', '/tmp/mynewfile') .then(() => console.log('success!')) .catch(err => console.error(err)) // Async with callbacks: fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { if (err) return console.error(err) console.log('success!') }) // Sync: try { fs.copySync('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } // Async/Await: async function copyFiles () { try { await fs.copy('/tmp/myfile', '/tmp/mynewfile') console.log('success!') } catch (err) { console.error(err) } } copyFiles() ``` Methods ------- ### Async - [copy](docs/copy.md) - [emptyDir](docs/emptyDir.md) - [ensureFile](docs/ensureFile.md) - [ensureDir](docs/ensureDir.md) - [ensureLink](docs/ensureLink.md) - [ensureSymlink](docs/ensureSymlink.md) - [mkdirp](docs/ensureDir.md) - [mkdirs](docs/ensureDir.md) - [move](docs/move.md) - [outputFile](docs/outputFile.md) - [outputJson](docs/outputJson.md) - [pathExists](docs/pathExists.md) - [readJson](docs/readJson.md) - [remove](docs/remove.md) - [writeJson](docs/writeJson.md) ### Sync - [copySync](docs/copy-sync.md) - [emptyDirSync](docs/emptyDir-sync.md) - [ensureFileSync](docs/ensureFile-sync.md) - [ensureDirSync](docs/ensureDir-sync.md) - [ensureLinkSync](docs/ensureLink-sync.md) - [ensureSymlinkSync](docs/ensureSymlink-sync.md) - [mkdirpSync](docs/ensureDir-sync.md) - [mkdirsSync](docs/ensureDir-sync.md) - [moveSync](docs/move-sync.md) - [outputFileSync](docs/outputFile-sync.md) - [outputJsonSync](docs/outputJson-sync.md) - [pathExistsSync](docs/pathExists-sync.md) - [readJsonSync](docs/readJson-sync.md) - [removeSync](docs/remove-sync.md) - [writeJsonSync](docs/writeJson-sync.md) **NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md) ### What happened to `walk()` and `walkSync()`? They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync). Third Party ----------- ### CLI [fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts. ### TypeScript If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra ### File / Directory Watching If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar). ### Obtain Filesystem (Devices, Partitions) Information [fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system. ### Misc. - [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug). - [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls. Hacking on fs-extra ------------------- Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you, you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`. [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) What's needed? - First, take a look at existing issues. Those are probably going to be where the priority lies. - More tests for edge cases. Specifically on different platforms. There can never be enough tests. - Improve test coverage. Note: If you make any big changes, **you should definitely file an issue for discussion first.** ### Running the Test Suite fs-extra contains hundreds of tests. - `npm run lint`: runs the linter ([standard](http://standardjs.com/)) - `npm run unit`: runs the unit tests - `npm test`: runs both the linter and the tests ### Windows If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7 However, I didn't have much luck doing this. Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows. I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command: net use z: "\\vmware-host\Shared Folders" I can then navigate to my `fs-extra` directory and run the tests. Naming ------ I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here: * https://github.com/jprichardson/node-fs-extra/issues/2 * https://github.com/flatiron/utile/issues/11 * https://github.com/ryanmcgrath/wrench-js/issues/29 * https://github.com/substack/node-mkdirp/issues/17 First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes. For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc. We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`? My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too. So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`. Credit ------ `fs-extra` wouldn't be possible without using the modules from the following authors: - [Isaac Shlueter](https://github.com/isaacs) - [Charlie McConnel](https://github.com/avianflu) - [James Halliday](https://github.com/substack) - [Andrew Kelley](https://github.com/andrewrk) License ------- Licensed under MIT Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson) [1]: http://nodejs.org/docs/latest/api/fs.html [jsonfile]: https://github.com/jprichardson/node-jsonfile # tar-stream tar-stream is a streaming tar parser and generator and nothing else. It is streams2 and operates purely using streams which means you can easily extract/parse tarballs without ever hitting the file system. Note that you still need to gunzip your data if you have a `.tar.gz`. We recommend using [gunzip-maybe](https://github.com/mafintosh/gunzip-maybe) in conjunction with this. ``` npm install tar-stream ``` [![build status](https://secure.travis-ci.org/mafintosh/tar-stream.png)](http://travis-ci.org/mafintosh/tar-stream) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) ## Usage tar-stream exposes two streams, [pack](https://github.com/mafintosh/tar-stream#packing) which creates tarballs and [extract](https://github.com/mafintosh/tar-stream#extracting) which extracts tarballs. To [modify an existing tarball](https://github.com/mafintosh/tar-stream#modifying-existing-tarballs) use both. It implementes USTAR with additional support for pax extended headers. It should be compatible with all popular tar distributions out there (gnutar, bsdtar etc) ## Related If you want to pack/unpack directories on the file system check out [tar-fs](https://github.com/mafintosh/tar-fs) which provides file system bindings to this module. ## Packing To create a pack stream use `tar.pack()` and call `pack.entry(header, [callback])` to add tar entries. ``` js var tar = require('tar-stream') var pack = tar.pack() // pack is a streams2 stream // add a file called my-test.txt with the content "Hello World!" pack.entry({ name: 'my-test.txt' }, 'Hello World!') // add a file called my-stream-test.txt from a stream var entry = pack.entry({ name: 'my-stream-test.txt', size: 11 }, function(err) { // the stream was added // no more entries pack.finalize() }) entry.write('hello') entry.write(' ') entry.write('world') entry.end() // pipe the pack stream somewhere pack.pipe(process.stdout) ``` ## Extracting To extract a stream use `tar.extract()` and listen for `extract.on('entry', (header, stream, next) )` ``` js var extract = tar.extract() extract.on('entry', function(header, stream, next) { // header is the tar header // stream is the content body (might be an empty stream) // call next when you are done with this entry stream.on('end', function() { next() // ready for next entry }) stream.resume() // just auto drain the stream }) extract.on('finish', function() { // all entries read }) pack.pipe(extract) ``` The tar archive is streamed sequentially, meaning you **must** drain each entry's stream as you get them or else the main extract stream will receive backpressure and stop reading. ## Headers The header object using in `entry` should contain the following properties. Most of these values can be found by stat'ing a file. ``` js { name: 'path/to/this/entry.txt', size: 1314, // entry size. defaults to 0 mode: 0o644, // entry mode. defaults to to 0o755 for dirs and 0o644 otherwise mtime: new Date(), // last modified date for entry. defaults to now. type: 'file', // type of entry. defaults to file. can be: // file | link | symlink | directory | block-device // character-device | fifo | contiguous-file linkname: 'path', // linked file name uid: 0, // uid of entry owner. defaults to 0 gid: 0, // gid of entry owner. defaults to 0 uname: 'maf', // uname of entry owner. defaults to null gname: 'staff', // gname of entry owner. defaults to null devmajor: 0, // device major version. defaults to 0 devminor: 0 // device minor version. defaults to 0 } ``` ## Modifying existing tarballs Using tar-stream it is easy to rewrite paths / change modes etc in an existing tarball. ``` js var extract = tar.extract() var pack = tar.pack() var path = require('path') extract.on('entry', function(header, stream, callback) { // let's prefix all names with 'tmp' header.name = path.join('tmp', header.name) // write the new entry to the pack stream stream.pipe(pack.entry(header, callback)) }) extract.on('finish', function() { // all entries done - lets finalize it pack.finalize() }) // pipe the old tarball to the extractor oldTarballStream.pipe(extract) // pipe the new tarball the another stream pack.pipe(newTarballStream) ``` ## Saving tarball to fs ``` js var fs = require('fs') var tar = require('tar-stream') var pack = tar.pack() // pack is a streams2 stream var path = 'YourTarBall.tar' var yourTarball = fs.createWriteStream(path) // add a file called YourFile.txt with the content "Hello World!" pack.entry({name: 'YourFile.txt'}, 'Hello World!', function (err) { if (err) throw err pack.finalize() }) // pipe the pack stream to your file pack.pipe(yourTarball) yourTarball.on('close', function () { console.log(path + ' has been written') fs.stat(path, function(err, stats) { if (err) throw err console.log(stats) console.log('Got file info successfully!') }) }) ``` ## Performance [See tar-fs for a performance comparison with node-tar](https://github.com/mafintosh/tar-fs/blob/master/README.md#performance) # License MIT # MD5 [![build status](https://secure.travis-ci.org/pvorb/node-md5.png)](http://travis-ci.org/pvorb/node-md5) [![info badge](https://img.shields.io/npm/dt/md5.svg)](http://npm-stat.com/charts.html?package=md5) a JavaScript function for hashing messages with MD5. node-md5 is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial <a href="https://tracking.gitads.io/?repo=node-md5"><img src="https://images.gitads.io/node-md5" alt="GitAds"/></a> ## Installation You can use this package on the server side as well as the client side. ### [Node.js](http://nodejs.org/): ~~~ npm install md5 ~~~ ## API ~~~ javascript md5(message) ~~~ * `message` -- `String`, `Buffer`, `Array` or `Uint8Array` * returns `String` ## Usage ~~~ javascript var md5 = require('md5'); console.log(md5('message')); ~~~ This will print the following ~~~ 78e731027d8fd50ed642340b7c9a63b3 ~~~ It supports buffers, too ~~~ javascript var fs = require('fs'); var md5 = require('md5'); fs.readFile('example.txt', function(err, buf) { console.log(md5(buf)); }); ~~~ ## Versions Before version 2.0.0 there were two packages called md5 on npm, one lowercase, one uppercase (the one you're looking at). As of version 2.0.0, all new versions of this module will go to lowercase [md5](https://www.npmjs.com/package/md5) on npm. To use the correct version, users of this module will have to change their code from `require('MD5')` to `require('md5')` if they want to use versions >= 2.0.0. ## Bugs and Issues If you encounter any bugs or issues, feel free to open an issue at [github](https://github.com/pvorb/node-md5/issues). ## Credits This package is based on the work of Jeff Mott, who did a pure JS implementation of the MD5 algorithm that was published by Ronald L. Rivest in 1991. I needed a npm package of the algorithm, so I used Jeff’s implementation for this package. The original implementation can be found in the [CryptoJS](http://code.google.com/p/crypto-js/) project. ## License ~~~ Copyright © 2011-2015, Paul Vorbach. Copyright © 2009, Jeff Mott. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name Crypto-JS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ~~~ # NEAR CLI (command line interface) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-cli) NEAR CLI is a Node.js application that relies on [`near-api-js`](https://github.com/near/near-api-js) to connect to and interact with the NEAR blockchain. Create accounts, access keys, sign & send transactions with this versatile command line interface tool. **Note:** Node.js version 10+ is required to run NEAR CLI. ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Overview _Click on a command for more information and examples._ | Command | Description | | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **ACCESS KEYS** | | | [`near login`](#near-login) | stores a full access key locally using [NEAR Wallet](https://wallet.testnet.near.org/) | | [`near keys`](#near-keys) | displays all access keys and their details for a given account | | [`near generate-key`](#near-generate-key) | generates a local key pair **or** shows public key & [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) | | [`near add-key`](#near-add-key) | adds a new access key to an account | | [`near delete-key`](#near-delete-key) | deletes an access key from an account | | **ACCOUNTS** | | | [`near create-account`](#near-create-account) | creates an account | | [`near state`](#near-state) | shows general details of an account | | [`near keys`](#near-keys) | displays all access keys for a given account | | [`near send`](#near-send) | sends tokens from one account to another | | [`near delete`](#near-delete) | deletes an account and transfers remaining balance to a beneficiary account | | **CONTRACTS** | | | [`near deploy`](#near-deploy) | deploys a smart contract to the NEAR blockchain | | [`near dev-deploy`](#near-dev-deploy) | creates a development account and deploys a contract to it _(`testnet` only)_ | | [`near call`](#near-call) | makes a contract call which can invoke `change` _or_ `view` methods | | [`near view`](#near-view) | makes a contract call which can **only** invoke a `view` method | | **TRANSACTIONS** | | | [`near tx-status`](#near-tx-status) | queries a transaction's status by `txHash` | | **VALIDATORS** | | | [`near validators current`](#near-validators-current) | displays current [epoch](http://docs.near.org/docs/concepts/epoch) validator pool details | | [`near validators next`](#near-validators-next) | displays validator details for the next [epoch](http://docs.near.org/docs/concepts/epoch) | | [`near proposals`](#near-proposals) | displays validator proposals for the [epoch](http://docs.near.org/docs/concepts/epoch) _after_ next | | **JS-SDK** | | | [`near js`](#near-js) | Work with JS contract enclave | | **REPL** | | | [`near repl`](#near-repl) | launches an interactive connection to the NEAR blockchain ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) | | | can also run a JS/TS file which exports an async main function that takes a [context](./context/index.d.ts) object | [ [**OPTIONS**](#options) ] > For EVM support see [Project Aurora's](https://aurora.dev) [`aurora-cli`](https://github.com/aurora-is-near/aurora-cli). --- ## Setup ### Installation > Make sure you have a current version of `npm` and `NodeJS` installed. #### Mac and Linux 1. Install `npm` and `node` using a package manager like `nvm` as sometimes there are issues using Ledger due to how OS X handles node packages related to USB devices. [[click here]](https://nodejs.org/en/download/package-manager/) 2. Ensure you have installed Node version 12 or above. 3. Install `near-cli` globally by running: ```bash npm install -g near-cli ``` #### Windows > For Windows users, we recommend using Windows Subsystem for Linux (`WSL`). 1. Install `WSL` [[click here]](https://docs.microsoft.com/en-us/windows/wsl/install-manual#downloading-distros) 2. Install `npm` [[click here]](https://www.npmjs.com/get-npm) 3. Install ` Node.js` [ [ click here ]](https://nodejs.org/en/download/package-manager/) 4. Change `npm` default directory [ [ click here ] ](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally#manually-change-npms-default-directory) - This is to avoid any permission issues with `WSL` 5. Open `WSL` and install `near-cli` globally by running: ```bash npm install -g near-cli ``` --- ### Network selection > The default network for `near-cli` is `testnet`. - You can change the network by prepending an environment variable to your command. ```bash NEAR_ENV=betanet near send ... ``` - Alternatively, you can set up a global environment variable by running: ```bash export NEAR_ENV=mainnet ``` --- ### Custom RPC server selection You can set custom RPC server URL by setting this env variables: ```bash NEAR_CLI_MAINNET_RPC_SERVER_URL NEAR_CLI_TESTNET_RPC_SERVER_URL NEAR_CLI_BETANET_RPC_SERVER_URL NEAR_CLI_GUILDNET_RPC_SERVER_URL NEAR_CLI_LOCALNET_RPC_SERVER_URL NEAR_CLI_SHARDNET_RPC_SERVER_URL NEAR_CLI_CI_RPC_SERVER_URL ``` Clear them in case you want to get back to the default RPC server. Example: ```bash export NEAR_CLI_TESTNET_RPC_SERVER_URL=<put_your_rpc_server_url_here> ``` --- ### RPC server API Keys Some RPC servers may require that you provide a valid API key to use them. You can set `x-api-key` for a server by running the next command: ```bash near set-api-key <rpc-server-url> <api-key> ``` This API Key will be saved in a config and used for each command you execute with this RPC URL. --- ## Access Keys ### `near login` > locally stores a full access key of an account you created with [NEAR Wallet](https://wallet.testnet.near.org/). - arguments: `none` - options: `default` **Example:** ```bash near login ``` #### Access Key Location: - Once complete you will now have your Access Key stored locally in a hidden directory called `.near-credentials` - This directory is located at the root of your `HOME` directory: - `~/.near-credentials` _(MAC / Linux)_ - `C:\Users\YOUR_ACCOUNT\.near-credentials` _(Windows)_ - Inside `.near-credentials`, access keys are organized in network subdirectories: - `default` _for `testnet`_ - `betanet` - `mainnet` - These network subdirectories contain `.JSON` objects with an: - `account_id` - `private_key` - `public_key` **Example:** ```json { "account_id": "example-acct.testnet", "public_key": "ed25519:7ns2AZVaG8XZrFrgRw7g8qhgddNTN64Zkz7Eo8JBnV5g", "private_key": "ed25519:4Ijd3vNUmdWJ4L922BxcsGN1aDrdpvUHEgqLQAUSLmL7S2qE9tYR9fqL6DqabGGDxCSHkKwdaAGNcHJ2Sfd" } ``` --- ### `near keys` > Displays all access keys for a given account. - arguments: `accountId` - options: `default` **Example:** ```bash near keys client.chainlink.testnet ``` <details> <summary> <strong>Example Response</strong> </summary> <p> ``` Keys for account client.chainlink.testnet [ { public_key: 'ed25519:4wrVrZbHrurMYgkcyusfvSJGLburmaw7m3gmCApxgvY4', access_key: { nonce: 97, permission: 'FullAccess' } }, { public_key: 'ed25519:H9k5eiU4xXS3M4z8HzKJSLaZdqGdGwBG49o7orNC4eZW', access_key: { nonce: 88, permission: { FunctionCall: { allowance: '18483247987345065500000000', receiver_id: 'client.chainlink.testnet', method_names: [ 'get_token_price', [length]: 1 ] } } } }, [length]: 2 ] ``` </p> </details> --- ### `near generate-key` > Creates a key pair locally in `.near-credentials` **or** displays public key from Ledger or seed phrase. - arguments: `accountId` or `none` - options: `--useLedgerKey`, `--seedPhrase`, or `--seedPath` **Note:** There are several ways to use `generate-key` that return very different results. Please reference the examples below for further details. --- #### 1) `near generate-key` > Creates a key pair locally in `.near-credentials` with an [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) as the accountId. _(hash representation of the public key)_ ```bash near generate-key ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Key pair with ed25519:33Vn9VtNEtWQPPd1f4jf5HzJ5weLcvGHU8oz7o5UnPqy public key for an account "1e5b1346bdb4fc5ccd465f6757a9082a84bcacfd396e7d80b0c726252fe8b3e8" ``` </p> </details> --- #### 2) `near generate-key accountId` > Creates a key pair locally in `.near-credentials` with an `accountId` that you specify. **Note:** This does NOT create an account with this name, and will overwrite an existing `.json` file with the same name. ```bash near generate-key example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Key pair with ed25519:CcH3oMEFg8tpJLekyvF7Wp49G81K3QLhGbaWEFwtCjht public key for an account "example.testnet" ``` </p> </details> --- #### 3a) `near generate-key --useLedgerKey` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) using the default HD path (`"44'/397'/0'/0'/1'"`) ```bash near generate-key --useLedgerKey ``` You should then see the following prompt to confirm this request on your Ledger device: Make sure to connect your Ledger and open NEAR app Waiting for confirmation on Ledger... After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wyeRvKIWv61NjmQZEkWTMzAYgdfx6oSeB2 Implicit account: 42c320xc20739fd9a6bqf2f89z61rd14efe5d3de234199bc771235a4bb8b0e1 ``` </p> </details> --- #### 3b) `near generate-key --useLedgerKey="HD path you specify"` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) using a custom HD path. ```bash near generate-key --useLedgerKey="44'/397'/0'/0'/2'" ``` You should then see the following prompt to confirm this request on your Ledger device: Make sure to connect your Ledger and open NEAR app Waiting for confirmation on Ledger... After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wye3dfa32rDjmQZEkWTMzAYgCX6oSeB2 Implicit account: 42c320xc20739ASD9a6bqf2Dsaf289z61rd14efe5d3de23213789009afDsd5bb8b0e1 ``` </p> </details> --- #### 4a) `near generate-key --seedPhrase="your seed phrase"` > Uses a seed phrase to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) ```bash near generate-key --seedPhrase="cow moon right send now cool dense quark pretty see light after" ``` <details> <summary><strong>Example Response</strong></summary> <p> Key pair with ed25519:GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi public key for an account "e9fa50ac20522987a87e566fcd6febdc97bd35c8c489999ca8aff465c56969c3" </p> </details> --- #### 4b) `near generate-key accountId --seedPhrase="your seed phrase"` > Uses a seed phrase to display a public key **without** the [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts). ```bash near generate-key example.testnet --seedPhrase="cow moon right send now cool dense quark pretty see light after" ``` <details> <summary><strong>Example Response</strong></summary> <p> Key pair with ed25519:GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi public key for an account "example.testnet" </p> </details> --- ### `near add-key` > Adds an either a **full access** or **function access** key to a given account. **Note:** You will use an _existing_ full access key for the account you would like to add a _new_ key to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) #### 1) add a `full access` key - arguments: `accountId` `publicKey` **Example:** ```bash near add-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> Adding full access key = Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S to example-acct.testnet. Transaction Id EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg </p> </details> #### 2) add a `function access` key - arguments: `accountId` `publicKey` `--contract-id` - options: `--method-names` `--allowance` > `accountId` is the account you are adding the key to > > `--contract-id` is the contract you are allowing methods to be called on > > `--method-names` are optional and if omitted, all methods of the `--contract-id` can be called. > > `--allowance` is the amount of Ⓝ the key is allowed to spend on gas fees _only_. If omitted then key will only be able to call view methods. **Note:** Each transaction made with this key will have gas fees deducted from the initial allowance and once it runs out a new key must be issued. **Example:** ```bash near add-key example-acct.testnet GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi --contract-id example-contract.testnet --method-names example_method --allowance 30000000000 ``` <details> <summary><strong>Example Response</strong></summary> <p> Adding function call access key = GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi to example-acct.testnet. Transaction Id H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r </p> </details> --- ### `near delete-key` > Deletes an existing key for a given account. - arguments: `accountId` `publicKey` - options: `default` **Note:** You will need separate full access key for the account you would like to delete a key from. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near delete-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> Transaction Id 4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT </p> </details> --- ## Accounts ### `near create-account` > Creates an account using a `--masterAccount` that will pay for the account's creation and any initial balance. - arguments: `accountId` `--masterAccount` - options: `--initialBalance` **Note:** You will only be able to create subaccounts of the `--masterAccount` unless the name of the new account is ≥ 32 characters. **Example**: ```bash near create-account 12345678901234567890123456789012 --masterAccount example-acct.testnet ``` **Subaccount example:** ```bash near create-account sub-acct.example-acct.testnet --masterAccount example-acct.testnet ``` **Example using `--initialBalance`:** ```bash near create-account sub-acct2.example-acct.testnet --masterAccount example-acct.testnet --initialBalance 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> Saving key to '/HOME_DIR/.near-credentials/default/sub-acct2.example-acct.testnet.json' Account sub-acct2.example-acct.testnet for network "default" was created. </p> </details> --- ### `near state` > Shows details of an account's state. - arguments: `accountId` - options: `default` **Example:** ```bash near state example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json { "amount": "99999999303364037168535000", "locked": "0", "code_hash": "G1PCjeQbvbUsJ8piXNb7Yg6dn3mfivDQN7QkvsVuMt4e", "storage_usage": 53528, "storage_paid_at": 0, "block_height": 21577354, "block_hash": "AWu1mrT3eMJLjqyhNHvMKrrbahN6DqcNxXanB5UH1RjB", "formattedAmount": "99.999999303364037168535" } ``` </p> </details> --- ### `near send` > Sends NEAR tokens (Ⓝ) from one account to another. - arguments: `senderId` `receiverId` `amount` - options: `default` **Note:** You will need a full access key for the sending account. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near send sender.testnet receiver.testnet 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> Sending 10 NEAR to receiver.testnet from sender.testnet Transaction Id BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN </p> </details> --- ### `near delete` > Deletes an account and transfers remaining balance to a beneficiary account. - arguments: `accountId` `beneficiaryId` - options: `default` **Example:** ```bash near delete sub-acct2.example-acct.testnet example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> Deleting account. Account id: sub-acct2.example-acct.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, beneficiary: example-acct.testnet Transaction Id 4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX Account sub-acct2.example-acct.testnet for network "default" was deleted. </p> </details> --- ## Contracts ### `near deploy` > Deploys a smart contract to a given accountId. - arguments: `accountId` `.wasmFile` - options: `initFunction` `initArgs` `initGas` `initDeposit` **Note:** You will need a full access key for the account you are deploying the contract to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near deploy --accountId example-contract.testnet --wasmFile out/example.wasm ``` **Initialize Example:** ```bash near deploy --accountId example-contract.testnet --wasmFile out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}' ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: main.wasm Transaction Id G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt Done deploying to example-contract.testnet </p> </details> ### `near dev-deploy` > Creates a development account and deploys a smart contract to it. No access keys needed. **_(`testnet` only)_** - options: `wasmFile`, `initFunction`, `initArgs`, `initGas`, `initDeposit`, `initialBalance`, `force` **Example:** ```bash near dev-deploy --wasmFile out/example.wasm ``` **Initialize Example:** ```bash near dev-deploy --wasmFile out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}' ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: dev-1603749005325-6432576, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/main.wasm Transaction Id 5nixQT87KeN3eZFX7zwBLUAKSY4nyjhwzLF27SWWKkAp To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/5nixQT87KeN3eZFX7zwBLUAKSY4nyjhwzLF27SWWKkAp Done deploying to dev-1603749005325-6432576 </p> </details> --- ### `near call` > makes a contract call which can modify _or_ view state. **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `contractName` `method_name` `{ args }` `--accountId` - options: `--gas` `--deposit` **Example:** ```bash near call guest-book.testnet addMessage '{"text": "Aloha"}' --account-id example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call: guest-book.testnet.addMessage({"text": "Aloha"}) Transaction Id FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK '' </p> </details> --- ### `near view` > Makes a contract call which can **only** view state. _(Call is free of charge)_ - arguments: `contractName` `method_name` `{ args }` - options: `default` **Example:** ```bash near view guest-book.testnet getMessages '{}' ``` <details> <summary><strong>Example Response</strong></summary> <p> View call: guest-book.testnet.getMessages({}) [ { premium: false, sender: 'waverlymaven.testnet', text: 'TGIF' }, { premium: true, sender: 'waverlymaven.testnet', text: 'Hello from New York 🌈' }, { premium: false, sender: 'fhr.testnet', text: 'Hi' }, { premium: true, sender: 'eugenethedream', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'hello' }, { premium: true, sender: 'dongri.testnet', text: 'hey' }, { premium: false, sender: 'hirokihori.testnet', text: 'hello' }, { premium: true, sender: 'eugenethedream', text: 'hello' }, { premium: false, sender: 'example-acct.testnet', text: 'Aloha' }, [length]: 10 ] </p> </details> --- ## NEAR EVM Contracts ### `near evm-view` > Makes an EVM contract call which can **only** view state. _(Call is free of charge)_ - arguments: `evmAccount` `contractName` `methodName` `[arguments]` `--abi` `--accountId` - options: `default` **Example:** ```bash near evm-view evm 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521 getAdopters '[]' --abi /path/to/contract/abi/Adoption.json --accountId test.near ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json [ "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0xCBdA96B3F2B8eb962f97AE50C3852CA976740e2B", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000" ] ``` </p> </details> --- ### `near evm-call (deprecated)` > makes an EVM contract call which can modify _or_ view state. **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `evmAccount` `contractName` `methodName` `[arguments]` `--abi` `--accountId` - options: `default` (`--gas` and `--deposit` coming soon…) **Example:** ```bash near evm-call evm 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521 adopt '["6"]' --abi /path/to/contract/abi/Adoption.json --accountId test.near ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call inside evm EVM: 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521.adopt() with args [ '6' ] </p> </details> --- ### `near evm-dev-init` > Used for running EVM tests — creates a given number of test accounts on the desired network using a master NEAR account - arguments: `accountId` - options: `numAccounts` ```bash NEAR_ENV=betanet near evm-dev-init you.betanet 3 ``` The above will create 3 subaccounts of `you.betanet`. This is useful for tests that require multiple accounts, for instance, sending fungible tokens back and forth. If the `3` value were to be omitted, it would use the default of 5. --- ## Transactions ### `near tx-status` > Queries transaction status by hash and accountId. - arguments: `txHash` `--accountId` - options: `default` **Example:** ```bash near tx-status FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK --accountId guest-book.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json Transaction guest-book.testnet:FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK { status: { SuccessValue: '' }, transaction: { signer_id: 'example-acct.testnet', public_key: 'ed25519:AXZZKnp6ZcWXyRNdy8FztYrniKf1qt6YZw6mCCReXrDB', nonce: 20, receiver_id: 'guest-book.testnet', actions: [ { FunctionCall: { method_name: 'addMessage', args: 'eyJ0ZXh0IjoiQWxvaGEifQ==', gas: 300000000000000, deposit: '0' } }, [length]: 1 ], signature: 'ed25519:5S6nZXPU72nzgAsTQLmAFfdVSykdKHWhtPMb5U7duacfPdUjrj8ipJxuRiWkZ4yDodvDNt92wcHLJxGLsyNEsZNB', hash: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK' }, transaction_outcome: { proof: [ [length]: 0 ], block_hash: '6nsjvzt6C52SSuJ8UvfaXTsdrUwcx8JtHfnUj8XjdKy1', id: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK', outcome: { logs: [ [length]: 0 ], receipt_ids: [ '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', [length]: 1 ], gas_burnt: 2427979134284, tokens_burnt: '242797913428400000000', executor_id: 'example-acct.testnet', status: { SuccessReceiptId: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU' } } }, receipts_outcome: [ { proof: [ [length]: 0 ], block_hash: 'At6QMrBuFQYgEPAh6fuRBmrTAe9hXTY1NzAB5VxTH1J2', id: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', outcome: { logs: [ [length]: 0 ], receipt_ids: [ 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', [length]: 1 ], gas_burnt: 3559403233496, tokens_burnt: '355940323349600000000', executor_id: 'guest-book.testnet', status: { SuccessValue: '' } } }, { proof: [ [length]: 0 ], block_hash: 'J7KjpMPzAqE7iX82FAQT3qERDs6UR1EAqBLPJXBzoLCk', id: 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', outcome: { logs: [ [length]: 0 ], receipt_ids: [ [length]: 0 ], gas_burnt: 0, tokens_burnt: '0', executor_id: 'example-acct.testnet', status: { SuccessValue: '' } } }, [length]: 2 ] } ``` </p> </details> --- ## Validators ### `near validators current` > Displays details of current validators. > > - amount staked > - number of seats > - percentage of uptime > - expected block production > - blocks actually produced - arguments: `current` - options: `default` **Example:** ```bash near validators current ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near validators current ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Validators (total: 49, seat price: 1,976,588): .--------------------------------------------------------------------------------------------------------------------. | Validator Id | Stake | Seats | % Online | Blocks produced | Blocks expected | |----------------------------------------------|------------|---------|----------|-----------------|-----------------| | cryptium.poolv1.near | 13,945,727 | 7 | 100% | 1143 | 1143 | | astro-stakers.poolv1.near | 11,660,189 | 5 | 100% | 817 | 817 | | blockdaemon.poolv1.near | 11,542,867 | 5 | 76.74% | 627 | 817 | | zavodil.poolv1.near | 11,183,187 | 5 | 100% | 818 | 818 | | bisontrails.poolv1.near | 10,291,696 | 5 | 99.38% | 810 | 815 | | dokiacapital.poolv1.near | 7,906,352 | 3 | 99.54% | 650 | 653 | | chorusone.poolv1.near | 7,480,508 | 3 | 100% | 490 | 490 | | figment.poolv1.near | 6,931,070 | 3 | 100% | 489 | 489 | | stardust.poolv1.near | 6,401,678 | 3 | 100% | 491 | 491 | | anonymous.poolv1.near | 6,291,821 | 3 | 97.55% | 479 | 491 | | d1.poolv1.near | 6,265,109 | 3 | 100% | 491 | 491 | | near8888.poolv1.near | 6,202,968 | 3 | 99.38% | 486 | 489 | | rekt.poolv1.near | 5,950,212 | 3 | 100% | 490 | 490 | | epic.poolv1.near | 5,639,256 | 2 | 100% | 326 | 326 | | fresh.poolv1.near | 5,460,410 | 2 | 100% | 327 | 327 | | buildlinks.poolv1.near | 4,838,398 | 2 | 99.38% | 325 | 327 | | jubi.poolv1.near | 4,805,921 | 2 | 100% | 326 | 326 | | openshards.poolv1.near | 4,644,553 | 2 | 100% | 326 | 326 | | jazza.poolv1.near | 4,563,432 | 2 | 100% | 327 | 327 | | northernlights.poolv1.near | 4,467,978 | 2 | 99.39% | 326 | 328 | | inotel.poolv1.near | 4,427,152 | 2 | 100% | 327 | 327 | | baziliknear.poolv1.near | 4,261,142 | 2 | 100% | 328 | 328 | | stakesabai.poolv1.near | 4,242,618 | 2 | 100% | 326 | 326 | | everstake.poolv1.near | 4,234,552 | 2 | 100% | 327 | 327 | | stakin.poolv1.near | 4,071,704 | 2 | 100% | 327 | 327 | | certusone.poolv1.near | 3,734,505 | 1 | 100% | 164 | 164 | | lux.poolv1.near | 3,705,394 | 1 | 100% | 163 | 163 | | staked.poolv1.near | 3,683,365 | 1 | 100% | 164 | 164 | | lunanova.poolv1.near | 3,597,231 | 1 | 100% | 163 | 163 | | appload.poolv1.near | 3,133,163 | 1 | 100% | 163 | 163 | | smart-stake.poolv1.near | 3,095,711 | 1 | 100% | 164 | 164 | | artemis.poolv1.near | 3,009,462 | 1 | 99.39% | 163 | 164 | | moonlet.poolv1.near | 2,790,296 | 1 | 100% | 163 | 163 | | nearfans.poolv1.near | 2,771,137 | 1 | 100% | 163 | 163 | | nodeasy.poolv1.near | 2,692,745 | 1 | 99.39% | 163 | 164 | | erm.poolv1.near | 2,653,524 | 1 | 100% | 164 | 164 | | zkv_staketosupportprivacy.poolv1.near | 2,548,343 | 1 | 99.39% | 163 | 164 | | dsrvlabs.poolv1.near | 2,542,925 | 1 | 100% | 164 | 164 | | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 | 1 | 100% | 163 | 163 | | electric.poolv1.near | 2,400,532 | 1 | 99.39% | 163 | 164 | | sparkpool.poolv1.near | 2,378,191 | 1 | 100% | 163 | 163 | | hashquark.poolv1.near | 2,376,424 | 1 | 100% | 164 | 164 | | masternode24.poolv1.near | 2,355,634 | 1 | 100% | 164 | 164 | | sharpdarts.poolv1.near | 2,332,398 | 1 | 99.38% | 162 | 163 | | fish.poolv1.near | 2,315,249 | 1 | 100% | 163 | 163 | | ashert.poolv1.near | 2,103,327 | 1 | 97.56% | 160 | 164 | | 01node.poolv1.near | 2,058,200 | 1 | 100% | 163 | 163 | | finoa.poolv1.near | 2,012,304 | 1 | 100% | 163 | 163 | | majlovesreg.poolv1.near | 2,005,032 | 1 | 100% | 164 | 164 | '--------------------------------------------------------------------------------------------------------------------' ``` </p> </details> --- ### `near validators next` > Displays details for the next round of validators. > > - total number of seats available > - seat price > - amount staked > - number of seats assigned per validator - arguments: `next` - options: `default` **Example:** ```bash near validators next ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near validators next ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Next validators (total: 49, seat price: 1,983,932): .----------------------------------------------------------------------------------------------. | Status | Validator | Stake | Seats | |----------|----------------------------------------------|--------------------------|---------| | Rewarded | cryptium.poolv1.near | 13,945,727 -> 14,048,816 | 7 | | Rewarded | astro-stakers.poolv1.near | 11,660,189 -> 11,704,904 | 5 | | Rewarded | blockdaemon.poolv1.near | 11,542,867 -> 11,545,942 | 5 | | Rewarded | zavodil.poolv1.near | 11,183,187 -> 11,204,123 | 5 | | Rewarded | bisontrails.poolv1.near | 10,291,696 -> 10,297,923 | 5 | | Rewarded | dokiacapital.poolv1.near | 7,906,352 -> 8,097,275 | 4 | | Rewarded | chorusone.poolv1.near | 7,480,508 -> 7,500,576 | 3 | | Rewarded | figment.poolv1.near | 6,931,070 -> 6,932,916 | 3 | | Rewarded | stardust.poolv1.near | 6,401,678 -> 6,449,363 | 3 | | Rewarded | anonymous.poolv1.near | 6,291,821 -> 6,293,497 | 3 | | Rewarded | d1.poolv1.near | 6,265,109 -> 6,266,777 | 3 | | Rewarded | near8888.poolv1.near | 6,202,968 -> 6,204,620 | 3 | | Rewarded | rekt.poolv1.near | 5,950,212 -> 5,951,797 | 2 | | Rewarded | epic.poolv1.near | 5,639,256 -> 5,640,758 | 2 | | Rewarded | fresh.poolv1.near | 5,460,410 -> 5,461,811 | 2 | | Rewarded | buildlinks.poolv1.near | 4,838,398 -> 4,839,686 | 2 | | Rewarded | jubi.poolv1.near | 4,805,921 -> 4,807,201 | 2 | | Rewarded | openshards.poolv1.near | 4,644,553 -> 4,776,692 | 2 | | Rewarded | jazza.poolv1.near | 4,563,432 -> 4,564,648 | 2 | | Rewarded | northernlights.poolv1.near | 4,467,978 -> 4,469,168 | 2 | | Rewarded | inotel.poolv1.near | 4,427,152 -> 4,428,331 | 2 | | Rewarded | baziliknear.poolv1.near | 4,261,142 -> 4,290,338 | 2 | | Rewarded | stakesabai.poolv1.near | 4,242,618 -> 4,243,748 | 2 | | Rewarded | everstake.poolv1.near | 4,234,552 -> 4,235,679 | 2 | | Rewarded | stakin.poolv1.near | 4,071,704 -> 4,072,773 | 2 | | Rewarded | certusone.poolv1.near | 3,734,505 -> 3,735,500 | 1 | | Rewarded | lux.poolv1.near | 3,705,394 -> 3,716,381 | 1 | | Rewarded | staked.poolv1.near | 3,683,365 -> 3,684,346 | 1 | | Rewarded | lunanova.poolv1.near | 3,597,231 -> 3,597,836 | 1 | | Rewarded | appload.poolv1.near | 3,133,163 -> 3,152,302 | 1 | | Rewarded | smart-stake.poolv1.near | 3,095,711 -> 3,096,509 | 1 | | Rewarded | artemis.poolv1.near | 3,009,462 -> 3,010,265 | 1 | | Rewarded | moonlet.poolv1.near | 2,790,296 -> 2,948,565 | 1 | | Rewarded | nearfans.poolv1.near | 2,771,137 -> 2,771,875 | 1 | | Rewarded | nodeasy.poolv1.near | 2,692,745 -> 2,693,463 | 1 | | Rewarded | erm.poolv1.near | 2,653,524 -> 2,654,231 | 1 | | Rewarded | dsrvlabs.poolv1.near | 2,542,925 -> 2,571,865 | 1 | | Rewarded | zkv_staketosupportprivacy.poolv1.near | 2,548,343 -> 2,549,022 | 1 | | Rewarded | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 -> 2,493,787 | 1 | | Rewarded | masternode24.poolv1.near | 2,355,634 -> 2,456,226 | 1 | | Rewarded | fish.poolv1.near | 2,315,249 -> 2,415,831 | 1 | | Rewarded | electric.poolv1.near | 2,400,532 -> 2,401,172 | 1 | | Rewarded | sparkpool.poolv1.near | 2,378,191 -> 2,378,824 | 1 | | Rewarded | hashquark.poolv1.near | 2,376,424 -> 2,377,057 | 1 | | Rewarded | sharpdarts.poolv1.near | 2,332,398 -> 2,332,948 | 1 | | Rewarded | ashert.poolv1.near | 2,103,327 -> 2,103,887 | 1 | | Rewarded | 01node.poolv1.near | 2,058,200 -> 2,058,760 | 1 | | Rewarded | finoa.poolv1.near | 2,012,304 -> 2,015,808 | 1 | | Rewarded | majlovesreg.poolv1.near | 2,005,032 -> 2,005,566 | 1 | '----------------------------------------------------------------------------------------------' ``` </p> </details> --- ### `near proposals` > Displays validator proposals for [epoch](http://docs.near.org/docs/concepts/epoch) after next. > > - expected seat price > - status of proposals > - previous amount staked and new amount that _will_ be staked > - amount of seats assigned per validator - arguments: `none` - options: `default` **Example:** ```bash near proposals ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near proposals ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Proposals for the epoch after next (new: 51, passing: 49, expected seat price = 1,983,932) .--------------------------------------------------------------------------------------------------------. | Status | Validator | Stake => New Stake | Seats | |--------------------|----------------------------------------------|--------------------------|---------| | Proposal(Accepted) | cryptium.poolv1.near | 13,945,727 => 14,041,766 | 7 | | Proposal(Accepted) | astro-stakers.poolv1.near | 11,660,189 => 11,705,673 | 5 | | Proposal(Accepted) | blockdaemon.poolv1.near | 11,542,867 => 11,545,942 | 5 | | Proposal(Accepted) | zavodil.poolv1.near | 11,183,187 => 11,207,805 | 5 | | Proposal(Accepted) | bisontrails.poolv1.near | 10,291,696 => 10,300,978 | 5 | | Proposal(Accepted) | dokiacapital.poolv1.near | 7,906,352 => 8,097,275 | 4 | | Proposal(Accepted) | chorusone.poolv1.near | 7,480,508 => 7,568,268 | 3 | | Proposal(Accepted) | figment.poolv1.near | 6,931,070 => 6,932,916 | 3 | | Proposal(Accepted) | stardust.poolv1.near | 6,401,678 => 6,449,363 | 3 | | Proposal(Accepted) | anonymous.poolv1.near | 6,291,821 => 6,293,497 | 3 | | Proposal(Accepted) | d1.poolv1.near | 6,265,109 => 6,266,777 | 3 | | Proposal(Accepted) | near8888.poolv1.near | 6,202,968 => 6,204,620 | 3 | | Proposal(Accepted) | rekt.poolv1.near | 5,950,212 => 5,951,797 | 2 | | Proposal(Accepted) | epic.poolv1.near | 5,639,256 => 5,640,758 | 2 | | Proposal(Accepted) | fresh.poolv1.near | 5,460,410 => 5,461,811 | 2 | | Proposal(Accepted) | buildlinks.poolv1.near | 4,838,398 => 4,839,686 | 2 | | Proposal(Accepted) | jubi.poolv1.near | 4,805,921 => 4,807,201 | 2 | | Proposal(Accepted) | openshards.poolv1.near | 4,644,553 => 4,776,692 | 2 | | Proposal(Accepted) | jazza.poolv1.near | 4,563,432 => 4,564,648 | 2 | | Proposal(Accepted) | northernlights.poolv1.near | 4,467,978 => 4,469,168 | 2 | | Proposal(Accepted) | inotel.poolv1.near | 4,427,152 => 4,428,331 | 2 | | Proposal(Accepted) | baziliknear.poolv1.near | 4,261,142 => 4,290,891 | 2 | | Proposal(Accepted) | stakesabai.poolv1.near | 4,242,618 => 4,243,748 | 2 | | Proposal(Accepted) | everstake.poolv1.near | 4,234,552 => 4,235,679 | 2 | | Proposal(Accepted) | stakin.poolv1.near | 4,071,704 => 4,072,773 | 2 | | Proposal(Accepted) | certusone.poolv1.near | 3,734,505 => 3,735,500 | 1 | | Proposal(Accepted) | lux.poolv1.near | 3,705,394 => 3,716,381 | 1 | | Proposal(Accepted) | staked.poolv1.near | 3,683,365 => 3,684,346 | 1 | | Proposal(Accepted) | lunanova.poolv1.near | 3,597,231 => 3,597,836 | 1 | | Proposal(Accepted) | appload.poolv1.near | 3,133,163 => 3,152,302 | 1 | | Proposal(Accepted) | smart-stake.poolv1.near | 3,095,711 => 3,096,509 | 1 | | Proposal(Accepted) | artemis.poolv1.near | 3,009,462 => 3,010,265 | 1 | | Proposal(Accepted) | moonlet.poolv1.near | 2,790,296 => 2,948,565 | 1 | | Proposal(Accepted) | nearfans.poolv1.near | 2,771,137 => 2,771,875 | 1 | | Proposal(Accepted) | nodeasy.poolv1.near | 2,692,745 => 2,693,463 | 1 | | Proposal(Accepted) | erm.poolv1.near | 2,653,524 => 2,654,231 | 1 | | Proposal(Accepted) | dsrvlabs.poolv1.near | 2,542,925 => 2,571,865 | 1 | | Proposal(Accepted) | zkv_staketosupportprivacy.poolv1.near | 2,548,343 => 2,549,022 | 1 | | Proposal(Accepted) | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 => 2,493,787 | 1 | | Proposal(Accepted) | masternode24.poolv1.near | 2,355,634 => 2,456,226 | 1 | | Proposal(Accepted) | fish.poolv1.near | 2,315,249 => 2,415,831 | 1 | | Proposal(Accepted) | electric.poolv1.near | 2,400,532 => 2,401,172 | 1 | | Proposal(Accepted) | sparkpool.poolv1.near | 2,378,191 => 2,378,824 | 1 | | Proposal(Accepted) | hashquark.poolv1.near | 2,376,424 => 2,377,057 | 1 | | Proposal(Accepted) | sharpdarts.poolv1.near | 2,332,398 => 2,332,948 | 1 | | Proposal(Accepted) | ashert.poolv1.near | 2,103,327 => 2,103,887 | 1 | | Proposal(Accepted) | 01node.poolv1.near | 2,058,200 => 2,059,314 | 1 | | Proposal(Accepted) | finoa.poolv1.near | 2,012,304 => 2,015,808 | 1 | | Proposal(Accepted) | majlovesreg.poolv1.near | 2,005,032 => 2,005,566 | 1 | | Proposal(Declined) | huobipool.poolv1.near | 1,666,976 | 0 | | Proposal(Declined) | hb436_pool.poolv1.near | 500,030 | 0 | '--------------------------------------------------------------------------------------------------------' ``` </p> </details> --- ## JS Contracts Enclave ### `near js` You can use `near js <command> <args>` to be able to interact with JS enclaved contracts. Run `near js --help` for instructions. An optional `--jsvm <accountId>` argument can be supplied to the following `js` subcommands to point to a different JSVM enclave contract. The default is set to `jsvm.testnet` and `jsvm.near` respectively for testnet and mainnet. Note that anything changing state in the enclave will require a deposit to maintain storage of either the contract bytes or the state of the contract itself. ### `near js deploy` > Deploys a smart contract to a given accountId on the JSVM enclave. - arguments: `accountId`, `base64File`, `deposit` - options: `jsvm` **Note:** You will need a full access key for the account you are deploying the contract to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near deploy --accountId example-contract.testnet --base64File out/example.base64 --deposit 0.1 ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/example.base64, JSVM: jsvm.testnet Transaction Id 4Nxsszgh2LaXPZph37peZKDqPZeJEErPih6n4jWcGDEB To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4Nxsszgh2LaXPZph37peZKDqPZeJEErPih6n4jWcGDEB Done deploying to example-contract.testnet </p> </details> ### `near js dev-deploy` > Creates a development account and deploys a smart contract to the enclave associated to the dev-account. No access keys needed. **_(`testnet` only)_** - arguments: `base64File` `deposit` - options: `jsvm` **Example:** ```bash near js dev-deploy --base64File out/example.base64 --deposit 0.1 ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: dev-1653005231830-15694723179173, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/example.base64, JSVM: jsvm.testnet Transaction Id FTVd4TKzy9mrmWvok6qHaoX68cVZnUJp2VqUgH6Y446n To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FTVd4TKzy9mrmWvok6qHaoX68cVZnUJp2VqUgH6Y446n Done deploying to dev-1653005231830-15694723179173 </p> </details> ### `near js call` > makes a contract call which can modify _or_ view state into the JSVM enclase **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `contractName` `methodName` `{ args }` `--accountId` `--deposit` - options: `--gas` `--jsvm` **Example:** ```bash near js call dev-1653005231830-15694723179173 set_status '["hello world"]' --deposit 0.1 --account-id dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call in JSVM[jsvm.testnet]: dev-1653005231830-15694723179173.set_status(["hello world"]) with attached 0.1 NEAR Receipts: 5QUuNwSYrDcEPKuSnU7fKN7YCGfXmdmZR9m3zUSTek7P, 3YU4eFhqBruc4z8KKLZr1U1oY31A6Bfks45GLA2rq5GS Log [jsvm.testnet]: dev-1653005231830-15694723179173 set_status with message hello world Transaction Id sP8s9REgK9YcZzkudyccg8R968zYWDVGCNv4wxeZsUe To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/sP8s9REgK9YcZzkudyccg8R968zYWDVGCNv4wxeZsUe '' </p> </details> ### `near js view` > Makes a contract call which can **only** view state. _(Call is free of charge and does not require deposit)_ - arguments: `contractName` `method_name` `{ args }` - options: `jsvm` **Example:** ```bash near js view dev-1653005231830-15694723179173 get_status '["dev-1653005231830-15694723179173"]' --accountId dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> View call in JSVM[jsvm.testnet]: dev-1653005231830-15694723179173.get_status(["dev-1653005231830-15694723179173"]) Log [jsvm.testnet]: get_status for account_id dev-1653005231830-15694723179173 'hello world' </p> </details> ### `near js remove` > Removes the contract on the JS enclase and refunds all the deposit to the actual account. - arguments: `accountId` - options: `jsvm` ```bash near js remove --accountId dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> Removing contract from enclave. Account id: dev-1653005231830-15694723179173, JSVM: jsvm.testnet Transaction Id FGSfvoWmhS1fWb6ckpPMYvc7seNaGQ5MU7iSrY43ZWiG To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FGSfvoWmhS1fWb6ckpPMYvc7seNaGQ5MU7iSrY43ZWiG </p> </details> ## REPL ### `near repl` > Launches NEAR [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) _(an interactive JavaScript programming invironment)_ connected to NEAR. - arguments: `none` - options: `--accountId`, `--script` To launch, run: ```bash near repl ``` - You will then be shown a prompt `>` and can begin interacting with NEAR. - Try typing the following into your prompt that converts NEAR (Ⓝ) into yoctoNEAR (10^-24): ```bash nearAPI.utils.format.parseNearAmount('1000') ``` > You can also use an `--accountId` with `near repl`. The `script` argument allows you to pass the path to a javascript/typescript file that exports a `main` function taking a [`Context`](./context/index.d.ts) as an argument. Anything passed after `--` is passed to the script as the `argv` argument. Note: you will need to add `near-cli` as a dependency in order to import the types. e.g. ```ts import { Context } from "near-cli/context"; ``` **Example:** ```bash near repl --accountId example-acct.testnet ``` - Then try console logging `account` after the `>` prompt. ```bash console.log(account) ``` Or in a JS files ```js module.exports.main = async function main({account, near, nearAPI, argv}) { console.log(account); } ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json Account { accessKeyByPublicKeyCache: {}, connection: Connection { networkId: 'default', provider: JsonRpcProvider { connection: [Object] }, signer: InMemorySigner { keyStore: [MergeKeyStore] } }, accountId: 'example-acct.testnet', _ready: Promise { undefined }, _state: { amount: '98786165075093615800000000', locked: '0', code_hash: '11111111111111111111111111111111', storage_usage: 741, storage_paid_at: 0, block_height: 21661252, block_hash: 'HbAj25dTzP3ssYjNRHov9BQ72UxpHGVqZK1mZwGdGNbo' } } ``` </p> </details> > You can also get a private key's public key. - First, declare a `privateKey` variable: ```js const myPrivateKey = "3fKM9Rr7LHyzhhzmmedXLvc59rayfh1oUYS3VfUcxwpAFQZtdx1G9aTY6i8hG9mQtYoycTEFTBtatgNKHRtYamrS"; ``` - Then run: ```js nearAPI.KeyPair.fromString(myPrivateKey).publicKey.toString(); ``` With NEAR REPL you have complete access to [`near-api-js`](https://github.com/near/near-api-js) to help you develop on the NEAR platform. --- ## Options | Option | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `--help` | Show help [boolean] | | `--version` | Show version number [boolean] | | `--nodeUrl, --node_url` | NEAR node URL [string] [default: "https://rpc.testnet.near.org"] | | `--networkId, --network_id`| NEAR network ID, allows using different keys based on network [string] [default: "testnet"] | | `--helperUrl` | NEAR contract helper URL [string] | | `--keyPath` | Path to master account key [string] | | `--accountId, --account_id`| Unique identifier for the account [string] | | `--useLedgerKey` | Use Ledger for signing with given HD key path [string] [default: "44'/397'/0'/0'/1'"] | | `--seedPhrase` | Seed phrase mnemonic [string] | | `--seedPath` | HD path derivation [string] [default: "m/44'/397'/0'"] | | `--walletUrl` | Website for NEAR Wallet [string] | | `--contractName` | Account name of contract [string] | | `--masterAccount` | Master account used when creating new accounts [string] | | `--helperAccount` | Expected top-level account for a network [string] | | `-v, --verbose` | Prints out verbose output [boolean] [default: false] | |`-f, --force` | Forcefully execute the desired action even if it is unsafe to do so [boolean] [default: false]| > Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a> ## License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # is-error <!-- [![build status][build-png]][build] [![Coverage Status][cover-png]][cover] [![Davis Dependency status][dep-png]][dep] --> <!-- [![NPM][npm-png]][npm] --> Detect whether a value is an error ## Example ```js var isError = require("is-error"); console.log(isError(new Error('hi'))) // true console.log(isError({ message: 'hi' })) // false ``` ## Docs ### `var bool = isError(maybeErr)` ```hs is-error := (maybeErr: Any) => Boolean ``` `isError` returns a boolean. it will detect whether the argument is an error or not. ## Installation `npm install is-error` ## Tests `npm test` ## Contributors - Raynos ## MIT Licensed [build-png]: https://secure.travis-ci.org/Raynos/is-error.png [build]: https://travis-ci.org/Raynos/is-error [cover-png]: https://coveralls.io/repos/Raynos/is-error/badge.png [cover]: https://coveralls.io/r/Raynos/is-error [dep-png]: https://david-dm.org/Raynos/is-error.png [dep]: https://david-dm.org/Raynos/is-error [npm-png]: https://nodei.co/npm/is-error.png?stars&downloads [npm]: https://nodei.co/npm/is-error # BIP39 [![Build Status](https://travis-ci.org/bitcoinjs/bip39.png?branch=master)](https://travis-ci.org/bitcoinjs/bip39) [![NPM](https://img.shields.io/npm/v/bip39.svg)](https://www.npmjs.org/package/bip39) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) JavaScript implementation of [Bitcoin BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki): Mnemonic code for generating deterministic keys ## Reminder for developers ***Please remember to allow recovery from mnemonic phrases that have invalid checksums (or that you don't have the wordlist)*** When a checksum is invalid, warn the user that the phrase is not something generated by your app, and ask if they would like to use it anyway. This way, your app only needs to hold the wordlists for your supported languages, but you can recover phrases made by other apps in other languages. However, there should be other checks in place, such as checking to make sure the user is inputting 12 words or more separated by a space. ie. `phrase.trim().split(/\s+/g).length >= 12` ## Removing wordlists from webpack/browserify Browserify/Webpack bundles can get very large if you include all the wordlists, so you can now exclude wordlists to make your bundle lighter. For example, if we want to exclude all wordlists besides chinese_simplified, you could build using the browserify command below. ```bash $ browserify -r bip39 -s bip39 \ --exclude=./wordlists/english.json \ --exclude=./wordlists/japanese.json \ --exclude=./wordlists/spanish.json \ --exclude=./wordlists/italian.json \ --exclude=./wordlists/french.json \ --exclude=./wordlists/korean.json \ --exclude=./wordlists/chinese_traditional.json \ > bip39.browser.js ``` This will create a bundle that only contains the chinese_simplified wordlist, and it will be the default wordlist for all calls without explicit wordlists. You can also do this in Webpack using the `IgnorePlugin`. Here is an example of excluding all non-English wordlists ```javascript ... plugins: [ new webpack.IgnorePlugin(/^\.\/(?!english)/, /bip39\/src\/wordlists$/), ], ... ``` This is how it will look in the browser console. ```javascript > bip39.entropyToMnemonic('00000000000000000000000000000000') "的 的 的 的 的 的 的 的 的 的 的 在" > bip39.wordlists.chinese_simplified Array(2048) [ "的", "一", "是", "在", "不", "了", "有", "和", "人", "这", … ] > bip39.wordlists.english undefined > bip39.wordlists.japanese undefined > bip39.wordlists.spanish undefined > bip39.wordlists.italian undefined > bip39.wordlists.french undefined > bip39.wordlists.korean undefined > bip39.wordlists.chinese_traditional undefined ``` For a list of supported wordlists check the wordlists folder. The name of the json file (minus the extension) is the name of the key to access the wordlist. You can also change the default wordlist at runtime if you dislike the wordlist you were given as default. ```javascript > bip39.entropyToMnemonic('00000000000000000000000000000fff') "あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あまい ろんり" > bip39.setDefaultWordlist('italian') undefined > bip39.entropyToMnemonic('00000000000000000000000000000fff') "abaco abaco abaco abaco abaco abaco abaco abaco abaco abaco aforisma zibetto" ``` ## Installation ``` bash npm install bip39 ``` ## Examples ``` js // Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 128-bits of entropy const mnemonic = bip39.generateMnemonic() // => 'seed sock milk update focus rotate barely fade car face mechanic mercy' bip39.mnemonicToSeedSync('basket actual').toString('hex') // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeedSync('basket actual') // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> // mnemonicToSeed has an synchronous version // mnemonicToSeedSync is less performance oriented bip39.mnemonicToSeed('basket actual').then(console.log) // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> bip39.mnemonicToSeed('basket actual').then(bytes => bytes.toString('hex')).then(console.log) // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeedSync('basket actual', 'a password') // => <Buffer 46 16 a4 4f 2c 90 b9 69 02 14 b8 fd 43 5b b4 14 62 43 de 10 7b 30 87 59 0a 3b b8 d3 1b 2f 3a ef ab 1d 4b 52 6d 21 e5 0a 04 02 3d 7a d0 66 43 ea 68 3b ... > bip39.validateMnemonic(mnemonic) // => true bip39.validateMnemonic('basket actual') // => false ``` ``` js const bip39 = require('bip39') // defaults to BIP39 English word list // uses HEX strings for entropy const mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000') // => abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about // reversible bip39.mnemonicToEntropy(mnemonic) // => '00000000000000000000000000000000' ``` # ncp - Asynchronous recursive file & directory copying [![Build Status](https://secure.travis-ci.org/AvianFlu/ncp.png)](http://travis-ci.org/AvianFlu/ncp) Think `cp -r`, but pure node, and asynchronous. `ncp` can be used both as a CLI tool and programmatically. ## Command Line usage Usage is simple: `ncp [source] [dest] [--limit=concurrency limit] [--filter=filter] --stopOnErr` The 'filter' is a Regular Expression - matched files will be copied. The 'concurrency limit' is an integer that represents how many pending file system requests `ncp` has at a time. 'stoponerr' is a boolean flag that will tell `ncp` to stop immediately if any errors arise, rather than attempting to continue while logging errors. The default behavior is to complete as many copies as possible, logging errors along the way. If there are no errors, `ncp` will output `done.` when complete. If there are errors, the error messages will be logged to `stdout` and to `./ncp-debug.log`, and the copy operation will attempt to continue. ## Programmatic usage Programmatic usage of `ncp` is just as simple. The only argument to the completion callback is a possible error. ```javascript var ncp = require('ncp').ncp; ncp.limit = 16; ncp(source, destination, function (err) { if (err) { return console.error(err); } console.log('done!'); }); ``` You can also call ncp like `ncp(source, destination, options, callback)`. `options` should be a dictionary. Currently, such options are available: * `options.filter` - a `RegExp` instance, against which each file name is tested to determine whether to copy it or not, or a function taking single parameter: copied file name, returning `true` or `false`, determining whether to copy file or not. * `options.transform` - a function: `function (read, write) { read.pipe(write) }` used to apply streaming transforms while copying. * `options.clobber` - boolean=true. if set to false, `ncp` will not overwrite destination files that already exist. * `options.dereference` - boolean=false. If set to true, `ncp` will follow symbolic links. For example, a symlink in the source tree pointing to a regular file will become a regular file in the destination tree. Broken symlinks will result in errors. * `options.stopOnErr` - boolean=false. If set to true, `ncp` will behave like `cp -r`, and stop on the first error it encounters. By default, `ncp` continues copying, logging all errors and returning an array. * `options.errs` - stream. If `options.stopOnErr` is `false`, a stream can be provided, and errors will be written to this stream. Please open an issue if any bugs arise. As always, I accept (working) pull requests, and refunds are available at `/dev/null`. # to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ``` <details> <summary><strong>What does this do?</strong></summary> <br> This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('to-regex-range'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). <br> </details> <details> <summary><strong>Why use this library?</strong></summary> <br> ### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once <br> </details> ## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | | `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | | `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | | `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | | `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | | `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | | `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | | `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | | `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | | `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | | `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | | `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | | `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | | `toRegexRange(5, 5)` | `5` | _8μs_ | | `toRegexRange(5, 6)` | `5\|6` | _11μs_ | | `toRegexRange(1, 2)` | `1\|2` | _6μs_ | | `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | | `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | | `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | | `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | | `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | | `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | | `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | | `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [doowb](https://github.com/doowb) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Current Status whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). ## API ### The `URL` Constructor The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. node-fetch ========== [![npm version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![coverage status][codecov-image]][codecov-url] [![install size][install-size-image]][install-size-url] [![Discord][discord-image]][discord-url] A light-weight module that brings `window.fetch` to Node.js (We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) [![Backers][opencollective-image]][opencollective-url] <!-- TOC --> - [Motivation](#motivation) - [Features](#features) - [Difference from client-side fetch](#difference-from-client-side-fetch) - [Installation](#installation) - [Loading and configuring the module](#loading-and-configuring-the-module) - [Common Usage](#common-usage) - [Plain text or HTML](#plain-text-or-html) - [JSON](#json) - [Simple Post](#simple-post) - [Post with JSON](#post-with-json) - [Post with form parameters](#post-with-form-parameters) - [Handling exceptions](#handling-exceptions) - [Handling client and server errors](#handling-client-and-server-errors) - [Advanced Usage](#advanced-usage) - [Streams](#streams) - [Buffer](#buffer) - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) - [Extract Set-Cookie Header](#extract-set-cookie-header) - [Post data using a file stream](#post-data-using-a-file-stream) - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) - [API](#api) - [fetch(url[, options])](#fetchurl-options) - [Options](#options) - [Class: Request](#class-request) - [Class: Response](#class-response) - [Class: Headers](#class-headers) - [Interface: Body](#interface-body) - [Class: FetchError](#class-fetcherror) - [License](#license) - [Acknowledgement](#acknowledgement) <!-- /TOC --> ## Motivation Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). ## Features - Stay consistent with `window.fetch` API. - Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. - Use native promise but allow substituting it with [insert your favorite promise library]. - Use native Node streams for body on both request and response. - Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. - Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. ## Difference from client-side fetch - See [Known Differences](LIMITS.md) for details. - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. - Pull requests are welcomed too! ## Installation Current stable release (`2.x`) ```sh $ npm install node-fetch ``` ## Loading and configuring the module We suggest you load the module via `require` until the stabilization of ES modules in node: ```js const fetch = require('node-fetch'); ``` If you are using a Promise library other than native, set it through `fetch.Promise`: ```js const Bluebird = require('bluebird'); fetch.Promise = Bluebird; ``` ## Common Usage NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. #### Plain text or HTML ```js fetch('https://github.com/') .then(res => res.text()) .then(body => console.log(body)); ``` #### JSON ```js fetch('https://api.github.com/users/github') .then(res => res.json()) .then(json => console.log(json)); ``` #### Simple Post ```js fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) .then(res => res.json()) // expecting a json response .then(json => console.log(json)); ``` #### Post with JSON ```js const body = { a: 1 }; fetch('https://httpbin.org/post', { method: 'post', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' }, }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form parameters `URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: ```js const { URLSearchParams } = require('url'); const params = new URLSearchParams(); params.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: params }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Handling exceptions NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. ```js fetch('https://domain.invalid/') .catch(err => console.error(err)); ``` #### Handling client and server errors It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: ```js function checkStatus(res) { if (res.ok) { // res.status >= 200 && res.status < 300 return res; } else { throw MyCustomError(res.statusText); } } fetch('https://httpbin.org/status/400') .then(checkStatus) .then(res => console.log('will not get here...')) ``` ## Advanced Usage #### Streams The "Node.js way" is to use streams when possible: ```js fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => { const dest = fs.createWriteStream('./octocat.png'); res.body.pipe(dest); }); ``` #### Buffer If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) ```js const fileType = require('file-type'); fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => res.buffer()) .then(buffer => fileType(buffer)) .then(type => { /* ... */ }); ``` #### Accessing Headers and other Meta data ```js fetch('https://github.com/') .then(res => { console.log(res.ok); console.log(res.status); console.log(res.statusText); console.log(res.headers.raw()); console.log(res.headers.get('content-type')); }); ``` #### Extract Set-Cookie Header Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. ```js fetch(url).then(res => { // returns an array of values, instead of a string of comma-separated values console.log(res.headers.raw()['set-cookie']); }); ``` #### Post data using a file stream ```js const { createReadStream } = require('fs'); const stream = createReadStream('input.txt'); fetch('https://httpbin.org/post', { method: 'POST', body: stream }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form-data (detect multipart) ```js const FormData = require('form-data'); const form = new FormData(); form.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: form }) .then(res => res.json()) .then(json => console.log(json)); // OR, using custom headers // NOTE: getHeaders() is non-standard API const form = new FormData(); form.append('a', 1); const options = { method: 'POST', body: form, headers: form.getHeaders() } fetch('https://httpbin.org/post', options) .then(res => res.json()) .then(json => console.log(json)); ``` #### Request cancellation with AbortSignal > NOTE: You may cancel streamed requests only on Node >= v8.0.0 You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). An example of timing out a request after 150ms could be achieved as the following: ```js import AbortController from 'abort-controller'; const controller = new AbortController(); const timeout = setTimeout( () => { controller.abort(); }, 150, ); fetch(url, { signal: controller.signal }) .then(res => res.json()) .then( data => { useData(data) }, err => { if (err.name === 'AbortError') { // request was aborted } }, ) .finally(() => { clearTimeout(timeout); }); ``` See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. ## API ### fetch(url[, options]) - `url` A string representing the URL for fetching - `options` [Options](#fetch-options) for the HTTP(S) request - Returns: <code>Promise&lt;[Response](#class-response)&gt;</code> Perform an HTTP(S) fetch. `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. <a id="fetch-options"></a> ### Options The default values are shown after each option key. ```js { // These properties are part of the Fetch Standard method: 'GET', headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect signal: null, // pass an instance of AbortSignal to optionally abort requests // The following properties are node-fetch extensions follow: 20, // maximum redirect count. 0 to not follow redirect timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. compress: true, // support gzip/deflate content encoding. false to disable size: 0, // maximum response body size in bytes. 0 to disable agent: null // http(s).Agent instance or function that returns an instance (see below) } ``` ##### Default Headers If no values are set, the following request headers will be sent automatically: Header | Value ------------------- | -------------------------------------------------------- `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ `Accept` | `*/*` `Connection` | `close` _(when no `options.agent` is present)_ `Content-Length` | _(automatically calculated, if possible)_ `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ `User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` Note: when `body` is a `Stream`, `Content-Length` is not set automatically. ##### Custom Agent The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: - Support self-signed certificate - Use only IPv4 or IPv6 - Custom DNS Lookup See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. ```js const httpAgent = new http.Agent({ keepAlive: true }); const httpsAgent = new https.Agent({ keepAlive: true }); const options = { agent: function (_parsedURL) { if (_parsedURL.protocol == 'http:') { return httpAgent; } else { return httpsAgent; } } } ``` <a id="class-request"></a> ### Class: Request An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. Due to the nature of Node.js, the following properties are not implemented at this moment: - `type` - `destination` - `referrer` - `referrerPolicy` - `mode` - `credentials` - `cache` - `integrity` - `keepalive` The following node-fetch extension properties are provided: - `follow` - `compress` - `counter` - `agent` See [options](#fetch-options) for exact meaning of these extensions. #### new Request(input[, options]) <small>*(spec-compliant)*</small> - `input` A string representing a URL, or another `Request` (which will be cloned) - `options` [Options][#fetch-options] for the HTTP(S) request Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. <a id="class-response"></a> ### Class: Response An HTTP(S) response. This class implements the [Body](#iface-body) interface. The following properties are not implemented in node-fetch at this moment: - `Response.error()` - `Response.redirect()` - `type` - `trailer` #### new Response([body[, options]]) <small>*(spec-compliant)*</small> - `body` A `String` or [`Readable` stream][node-readable] - `options` A [`ResponseInit`][response-init] options dictionary Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. #### response.ok <small>*(spec-compliant)*</small> Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. #### response.redirected <small>*(spec-compliant)*</small> Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. <a id="class-headers"></a> ### Class: Headers This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. #### new Headers([init]) <small>*(spec-compliant)*</small> - `init` Optional argument to pre-fill the `Headers` object Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. ```js // Example adapted from https://fetch.spec.whatwg.org/#example-headers-class const meta = { 'Content-Type': 'text/xml', 'Breaking-Bad': '<3' }; const headers = new Headers(meta); // The above is equivalent to const meta = [ [ 'Content-Type', 'text/xml' ], [ 'Breaking-Bad', '<3' ] ]; const headers = new Headers(meta); // You can in fact use any iterable objects, like a Map or even another Headers const meta = new Map(); meta.set('Content-Type', 'text/xml'); meta.set('Breaking-Bad', '<3'); const headers = new Headers(meta); const copyOfHeaders = new Headers(headers); ``` <a id="iface-body"></a> ### Interface: Body `Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. The following methods are not yet implemented in node-fetch at this moment: - `formData()` #### body.body <small>*(deviation from spec)*</small> * Node.js [`Readable` stream][node-readable] Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. #### body.bodyUsed <small>*(spec-compliant)*</small> * `Boolean` A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. #### body.arrayBuffer() #### body.blob() #### body.json() #### body.text() <small>*(spec-compliant)*</small> * Returns: <code>Promise</code> Consume the body and return a promise that will resolve to one of these formats. #### body.buffer() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;Buffer&gt;</code> Consume the body and return a promise that will resolve to a Buffer. #### body.textConverted() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;String&gt;</code> Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. (This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) <a id="class-fetcherror"></a> ### Class: FetchError <small>*(node-fetch extension)*</small> An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. <a id="class-aborterror"></a> ### Class: AbortError <small>*(node-fetch extension)*</small> An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. ## Acknowledgement Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. `node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). ## License MIT [npm-image]: https://flat.badgen.net/npm/v/node-fetch [npm-url]: https://www.npmjs.com/package/node-fetch [travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch [travis-url]: https://travis-ci.org/bitinn/node-fetch [codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master [codecov-url]: https://codecov.io/gh/bitinn/node-fetch [install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch [install-size-url]: https://packagephobia.now.sh/result?p=node-fetch [discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square [discord-url]: https://discord.gg/Zxbndcm [opencollective-image]: https://opencollective.com/node-fetch/backers.svg [opencollective-url]: https://opencollective.com/node-fetch [whatwg-fetch]: https://fetch.spec.whatwg.org/ [response-init]: https://fetch.spec.whatwg.org/#responseinit [node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams [mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers [LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md [ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md [UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md # http-errors [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][node-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] Create HTTP errors for Express, Koa, Connect, etc. with ease. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install http-errors ``` ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ## API This is the current API, currently extracted from Koa and subject to change. ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ### createError([status], [message], [properties]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ### createError([status], [error], [properties]) Extend the given `error` object with `createError.HttpError` properties. This will not alter the inheritance of the given `error` object, and the modified `error` object is the return value. <!-- eslint-disable no-redeclare --> ```js fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` - `status` - the status code as a number - `error` - the error object to extend - `properties` - custom properties to attach to the object ### createError.isHttpError(val) Determine if the provided `val` is an `HttpError`. This will return `true` if the error inherits from the `HttpError` constructor of this module or matches the "duck type" for an error this module creates. All outputs from the `createError` factory will return `true` for this function, including if an non-`HttpError` was passed into the factory. ### new createError\[code || name\](\[msg]\)) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. #### List of all constructors |Status Code|Constructor Name | |-----------|-----------------------------| |400 |BadRequest | |401 |Unauthorized | |402 |PaymentRequired | |403 |Forbidden | |404 |NotFound | |405 |MethodNotAllowed | |406 |NotAcceptable | |407 |ProxyAuthenticationRequired | |408 |RequestTimeout | |409 |Conflict | |410 |Gone | |411 |LengthRequired | |412 |PreconditionFailed | |413 |PayloadTooLarge | |414 |URITooLong | |415 |UnsupportedMediaType | |416 |RangeNotSatisfiable | |417 |ExpectationFailed | |418 |ImATeapot | |421 |MisdirectedRequest | |422 |UnprocessableEntity | |423 |Locked | |424 |FailedDependency | |425 |UnorderedCollection | |426 |UpgradeRequired | |428 |PreconditionRequired | |429 |TooManyRequests | |431 |RequestHeaderFieldsTooLarge | |451 |UnavailableForLegalReasons | |500 |InternalServerError | |501 |NotImplemented | |502 |BadGateway | |503 |ServiceUnavailable | |504 |GatewayTimeout | |505 |HTTPVersionNotSupported | |506 |VariantAlsoNegotiates | |507 |InsufficientStorage | |508 |LoopDetected | |509 |BandwidthLimitExceeded | |510 |NotExtended | |511 |NetworkAuthenticationRequired| ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci [ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master [coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master [node-image]: https://badgen.net/npm/node/http-errors [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/http-errors [npm-url]: https://npmjs.org/package/http-errors [npm-version-image]: https://badgen.net/npm/v/http-errors [travis-image]: https://badgen.net/travis/jshttp/http-errors/master [travis-url]: https://travis-ci.org/jshttp/http-errors # bip39-light A lightweight fork of [bitcoinjs/bip39](https://github.com/bitcoinjs/bip39). Only english wordlist and removed some dependendecies. JavaScript implementation of [Bitcoin BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki): Mnemonic code for generating deterministic keys ## Reminder for developers ***Please remember to allow recovery from mnemonic phrases that have invalid checksums (or that you don't have the wordlist)*** When a checksum is invalid, warn the user that the phrase is not something generated by your app, and ask if they would like to use it anyway. This way, your app only needs to hold the wordlists for your supported languages, but you can recover phrases made by other apps in other languages. However, there should be other checks in place, such as checking to make sure the user is inputting 12 words or more separated by a space. ie. `phrase.trim().split(/\s+/g).length >= 12` ## Examples ``` js // Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 128-bits of entropy var mnemonic = bip39.generateMnemonic() // => 'seed sock milk update focus rotate barely fade car face mechanic mercy' bip39.mnemonicToSeedHex('basket actual') // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeed('basket actual') // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> bip39.validateMnemonic(mnemonic) // => true bip39.validateMnemonic('basket actual') // => false ``` ``` js var bip39 = require('bip39-light') // defaults to BIP39 English word list // uses HEX strings for entropy var mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000') // => abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about // reversible bip39.mnemonicToEntropy(mnemonic) // => '00000000000000000000000000000000' ``` <h1 align="center">Picomatch</h1> <p align="center"> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/v/picomatch.svg" alt="version"> </a> <a href="https://github.com/micromatch/picomatch/actions?workflow=Tests"> <img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status"> </a> <a href="https://coveralls.io/github/micromatch/picomatch"> <img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status"> </a> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br> <em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em> </p> <br> <br> ## Why picomatch? * **Lightweight** - No dependencies * **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. * **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) * **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) * **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. * **Well tested** - Thousands of unit tests See the [library comparison](#library-comparisons) to other libraries. <br> <br> ## Table of Contents <details><summary> Click to expand </summary> - [Install](#install) - [Usage](#usage) - [API](#api) * [picomatch](#picomatch) * [.test](#test) * [.matchBase](#matchbase) * [.isMatch](#ismatch) * [.parse](#parse) * [.scan](#scan) * [.compileRe](#compilere) * [.makeRe](#makere) * [.toRegex](#toregex) - [Options](#options) * [Picomatch options](#picomatch-options) * [Scan Options](#scan-options) * [Options Examples](#options-examples) - [Globbing features](#globbing-features) * [Basic globbing](#basic-globbing) * [Advanced globbing](#advanced-globbing) * [Braces](#braces) * [Matching special characters as literals](#matching-special-characters-as-literals) - [Library Comparisons](#library-comparisons) - [Benchmarks](#benchmarks) - [Philosophies](#philosophies) - [About](#about) * [Author](#author) * [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ </details> <br> <br> ## Install Install with [npm](https://www.npmjs.com/): ```sh npm install --save picomatch ``` <br> ## Usage The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. ```js const pm = require('picomatch'); const isMatch = pm('*.js'); console.log(isMatch('abcd')); //=> false console.log(isMatch('a.js')); //=> true console.log(isMatch('a.md')); //=> false console.log(isMatch('a/b.js')); //=> false ``` <br> ## API ### [picomatch](lib/picomatch.js#L32) Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. **Params** * `globs` **{String|Array}**: One or more glob patterns. * `options` **{Object=}** * `returns` **{Function=}**: Returns a matcher function. **Example** ```js const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.test](lib/picomatch.js#L117) Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. **Params** * `input` **{String}**: String to test. * `regex` **{RegExp}** * `returns` **{Object}**: Returns an object with matching info. **Example** ```js const picomatch = require('picomatch'); // picomatch.test(input, regex[, options]); console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` ### [.matchBase](lib/picomatch.js#L161) Match the basename of a filepath. **Params** * `input` **{String}**: String to test. * `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). * `returns` **{Boolean}** **Example** ```js const picomatch = require('picomatch'); // picomatch.matchBase(input, glob[, options]); console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true ``` ### [.isMatch](lib/picomatch.js#L183) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * **{String|Array}**: str The string to test. * **{String|Array}**: patterns One or more glob patterns to use for matching. * **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const picomatch = require('picomatch'); // picomatch.isMatch(string, patterns[, options]); console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(picomatch.isMatch('a.a', 'b.*')); //=> false ``` ### [.parse](lib/picomatch.js#L199) Parse a glob pattern to create the source string for a regular expression. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. **Example** ```js const picomatch = require('picomatch'); const result = picomatch.parse(pattern[, options]); ``` ### [.scan](lib/picomatch.js#L231) Scan a glob pattern to separate the pattern into segments. **Params** * `input` **{String}**: Glob pattern to scan. * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const picomatch = require('picomatch'); // picomatch.scan(input[, options]); const result = picomatch.scan('!./foo/*.js'); console.log(result); { prefix: '!./', input: '!./foo/*.js', start: 3, base: 'foo', glob: '*.js', isBrace: false, isBracket: false, isGlob: true, isExtglob: false, isGlobstar: false, negated: true } ``` ### [.compileRe](lib/picomatch.js#L245) Compile a regular expression from the `state` object returned by the [parse()](#parse) method. **Params** * `state` **{Object}** * `options` **{Object}** * `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. * `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * `returns` **{RegExp}** ### [.makeRe](lib/picomatch.js#L286) Create a regular expression from a parsed glob pattern. **Params** * `state` **{String}**: The object returned from the `.parse` method. * `options` **{Object}** * `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const picomatch = require('picomatch'); const state = picomatch.parse('*.js'); // picomatch.compileRe(state[, options]); console.log(picomatch.compileRe(state)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` ### [.toRegex](lib/picomatch.js#L321) Create a regular expression from the given regex source string. **Params** * `source` **{String}**: Regular expression source string. * `options` **{Object}** * `returns` **{RegExp}** **Example** ```js const picomatch = require('picomatch'); // picomatch.toRegex(source[, options]); const { output } = picomatch.parse('*.js'); console.log(picomatch.toRegex(output)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` <br> ## Options ### Picomatch options The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | | `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. ### Scan Options In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | | `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | **Example** ```js const picomatch = require('picomatch'); const result = picomatch.scan('!./foo/*.js', { tokens: true }); console.log(result); // { // prefix: '!./', // input: '!./foo/*.js', // start: 3, // base: 'foo', // glob: '*.js', // isBrace: false, // isBracket: false, // isGlob: true, // isExtglob: false, // isGlobstar: false, // negated: true, // maxDepth: 2, // tokens: [ // { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, // { value: 'foo', depth: 1, isGlob: false }, // { value: '*.js', depth: 1, isGlob: true } // ], // slashes: [ 2, 6 ], // parts: [ 'foo', '*.js' ] // } ``` <br> ### Options Examples #### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a folder ```js const fill = require('fill-range'); const regex = pm.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex); //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` #### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')); //=> true ``` #### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onMatch }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` <br> <br> ## Globbing features * [Basic globbing](#basic-globbing) (Wildcard matching) * [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) ### Basic globbing | **Character** | **Description** | | --- | --- | | `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | | `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | | `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | | `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | #### Matching behavior vs. Bash Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: * Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. * Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. <br> ### Advanced globbing * [extglobs](#extglobs) * [POSIX brackets](#posix-brackets) * [Braces](#brace-expansion) #### Extglobs | **Pattern** | **Description** | | --- | --- | | `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | | `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | | `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | | `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | | `!(pattern)` | Match _anything but_ `pattern` | **Examples** ```js const pm = require('picomatch'); // *(pattern) matches ZERO or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // +(pattern) matches ONE or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // supports multiple extglobs console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false // supports nested extglobs console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true ``` #### POSIX brackets POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. **Enable POSIX bracket support** ```js console.log(pm.makeRe('[[:word:]]+', { posix: true })); //=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ ``` **Supported POSIX classes** The following named POSIX bracket expressions are supported: * `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` * `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. * `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. * `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. * `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. * `[:digit:]` - Numerical digits, equivalent to `[0-9]`. * `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. * `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. * `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. * `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. * `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. * `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. * `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. * `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. ### Braces Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. ### Matching special characters as literals If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: **Special Characters** Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. To match any of the following characters as literals: `$^*+?()[] Examples: ```js console.log(pm.makeRe('foo/bar \\(1\\)')); console.log(pm.makeRe('foo/bar \\(1\\)')); ``` <br> <br> ## Library Comparisons The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). | **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | | --- | --- | --- | --- | --- | --- | --- | --- | | Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | | Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | | Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | | Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | | Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | | Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | | Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | | File system operations | - | - | - | - | - | - | - | <br> <br> ## Benchmarks Performance comparison of picomatch and minimatch. ``` # .makeRe star picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) # .makeRe star; dot=true picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) # .makeRe globstar picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) # .makeRe globstars picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) # .makeRe with leading star picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) # .makeRe - basic braces picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) ``` <br> <br> ## Philosophies The goal of this library is to be blazing fast, without compromising on accuracy. **Accuracy** The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. **Performance** Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. <br> <br> ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # queue-microtask [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [ci-image]: https://img.shields.io/github/workflow/status/feross/queue-microtask/ci/master [ci-url]: https://github.com/feross/queue-microtask/actions [npm-image]: https://img.shields.io/npm/v/queue-microtask.svg [npm-url]: https://npmjs.org/package/queue-microtask [downloads-image]: https://img.shields.io/npm/dm/queue-microtask.svg [downloads-url]: https://npmjs.org/package/queue-microtask [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### fast, tiny [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) shim for modern engines - Use [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) in all modern JS engines. - No dependencies. Less than 10 lines. No shims or complicated fallbacks. - Optimal performance in all modern environments - Uses `queueMicrotask` in modern environments - Fallback to `Promise.resolve().then(fn)` in Node.js 10 and earlier, and old browsers (same performance as `queueMicrotask`) ## install ``` npm install queue-microtask ``` ## usage ```js const queueMicrotask = require('queue-microtask') queueMicrotask(() => { /* this will run soon */ }) ``` ## What is `queueMicrotask` and why would one use it? The `queueMicrotask` function is a WHATWG standard. It queues a microtask to be executed prior to control returning to the event loop. A microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the event loop. The code `queueMicrotask(fn)` is equivalent to the code `Promise.resolve().then(fn)`. It is also very similar to [`process.nextTick(fn)`](https://nodejs.org/api/process.html#process_process_nexttick_callback_args) in Node. Using microtasks lets code run without interfering with any other, potentially higher priority, code that is pending, but before the JS engine regains control over the execution context. See the [spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing) or [Node documentation](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback) for more information. ## Who is this package for? This package allows you to use `queueMicrotask` safely in all modern JS engines. Use it if you prioritize small JS bundle size over support for old browsers. If you just need to support Node 12 and later, use `queueMicrotask` directly. If you need to support all versions of Node, use this package. ## Why not use `process.nextTick`? In Node, `queueMicrotask` and `process.nextTick` are [essentially equivalent](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback), though there are [subtle differences](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks) that don't matter in most situations. You can think of `queueMicrotask` as a standardized version of `process.nextTick` that works in the browser. No need to rely on your browser bundler to shim `process` for the browser environment. ## Why not use `setTimeout(fn, 0)`? This approach is the most compatible, but it has problems. Modern browsers throttle timers severely, so `setTimeout(…, 0)` usually takes at least 4ms to run. Furthermore, the throttling gets even worse if the page is backgrounded. If you have many `setTimeout` calls, then this can severely limit the performance of your program. ## Why not use a microtask library like [`immediate`](https://www.npmjs.com/package/immediate) or [`asap`](https://www.npmjs.com/package/asap)? These packages are great! However, if you prioritize small JS bundle size over optimal performance in old browsers then you may want to consider this package. This package (`queue-microtask`) is four times smaller than `immediate`, twice as small as `asap`, and twice as small as using `process.nextTick` and letting the browser bundler shim it automatically. Note: This package throws an exception in JS environments which lack `Promise` support -- which are usually very old browsers and Node.js versions. Since the `queueMicrotask` API is supported in Node.js, Chrome, Firefox, Safari, Opera, and Edge, **the vast majority of users will get optimal performance**. Any JS environment with `Promise`, which is almost all of them, also get optimal performance. If you need support for JS environments which lack `Promise` support, use one of the alternative packages. ## What is a shim? > In computer programming, a shim is a library that transparently intercepts API calls and changes the arguments passed, handles the operation itself or redirects the operation elsewhere. – [Wikipedia](https://en.wikipedia.org/wiki/Shim_(computing)) This package could also be described as a "ponyfill". > A ponyfill is almost the same as a polyfill, but not quite. Instead of patching functionality for older browsers, a ponyfill provides that functionality as a standalone module you can use. – [PonyFoo](https://ponyfoo.com/articles/polyfills-or-ponyfills) ## API ### `queueMicrotask(fn)` The `queueMicrotask()` method queues a microtask. The `fn` argument is a function to be executed after all pending tasks have completed but before yielding control to the browser's event loop. ## license MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org). # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # gensync This module allows for developers to write common code that can share implementation details, hiding whether an underlying request happens synchronously or asynchronously. This is in contrast with many current Node APIs which explicitly implement the same API twice, once with calls to synchronous functions, and once with asynchronous functions. Take for example `fs.readFile` and `fs.readFileSync`, if you're writing an API that loads a file and then performs a synchronous operation on the data, it can be frustrating to maintain two parallel functions. ## Example ```js const fs = require("fs"); const gensync = require("gensync"); const readFile = gensync({ sync: fs.readFileSync, errback: fs.readFile, }); const myOperation = gensync(function* (filename) { const code = yield* readFile(filename, "utf8"); return "// some custom prefix\n" + code; }); // Load and add the prefix synchronously: const result = myOperation.sync("./some-file.js"); // Load and add the prefix asynchronously with promises: myOperation.async("./some-file.js").then(result => { }); // Load and add the prefix asynchronously with promises: myOperation.errback("./some-file.js", (err, result) => { }); ``` This could even be exposed as your official API by doing ```js // Using the common 'Sync' suffix for sync functions, and 'Async' suffix for // promise-returning versions. exports.myOperationSync = myOperation.sync; exports.myOperationAsync = myOperation.async; exports.myOperation = myOperation.errback; ``` or potentially expose one of the async versions as the default, with a `.sync` property on the function to expose the synchronous version. ```js module.exports = myOperation.errback; module.exports.sync = myOperation.sync; ```` ## API ### gensync(generatorFnOrOptions) Returns a function that can be "await"-ed in another `gensync` generator function, or executed via * `.sync(...args)` - Returns the computed value, or throws. * `.async(...args)` - Returns a promise for the computed value. * `.errback(...args, (err, result) => {})` - Calls the callback with the computed value, or error. #### Passed a generator Wraps the generator to populate the `.sync`/`.async`/`.errback` helpers above to allow for evaluation of the generator for the final value. ##### Example ```js const readFile = function* () { return 42; }; const readFileAndMore = gensync(function* (){ const val = yield* readFile(); return 42 + val; }); // In general cases const code = readFileAndMore.sync("./file.js", "utf8"); readFileAndMore.async("./file.js", "utf8").then(code => {}) readFileAndMore.errback("./file.js", "utf8", (err, code) => {}); // In a generator being called indirectly with .sync/.async/.errback const code = yield* readFileAndMore("./file.js", "utf8"); ``` #### Passed an options object * `opts.sync` Example: `(...args) => 4` A function that will be called when `.sync()` is called on the `gensync()` result, or when the result is passed to `yield*` in another generator that is being run synchronously. Also called for `.async()` calls if no async handlers are provided. * `opts.async` Example: `async (...args) => 4` A function that will be called when `.async()` or `.errback()` is called on the `gensync()` result, or when the result is passed to `yield*` in another generator that is being run asynchronously. * `opts.errback` Example: `(...args, cb) => cb(null, 4)` A function that will be called when `.async()` or `.errback()` is called on the `gensync()` result, or when the result is passed to `yield*` in another generator that is being run asynchronously. This option allows for simpler compatibility with many existing Node APIs, and also avoids introducing the extra even loop turns that promises introduce to access the result value. * `opts.name` Example: `"readFile"` A string name to apply to the returned function. If no value is provided, the name of `errback`/`async`/`sync` functions will be used, with any `Sync` or `Async` suffix stripped off. If the callback is simply named with ES6 inference (same name as the options property), the name is ignored. * `opts.arity` Example: `4` A number for the length to set on the returned function. If no value is provided, the length will be carried over from the `sync` function's `length` value. ##### Example ```js const readFile = gensync({ sync: fs.readFileSync, errback: fs.readFile, }); const code = readFile.sync("./file.js", "utf8"); readFile.async("./file.js", "utf8").then(code => {}) readFile.errback("./file.js", "utf8", (err, code) => {}); ``` ### gensync.all(iterable) `Promise.all`-like combinator that works with an iterable of generator objects that could be passed to `yield*` within a gensync generator. #### Example ```js const loadFiles = gensync(function* () { return yield* gensync.all([ readFile("./one.js"), readFile("./two.js"), readFile("./three.js"), ]); }); ``` ### gensync.race(iterable) `Promise.race`-like combinator that works with an iterable of generator objects that could be passed to `yield*` within a gensync generator. #### Example ```js const loadFiles = gensync(function* () { return yield* gensync.race([ readFile("./one.js"), readFile("./two.js"), readFile("./three.js"), ]); }); ``` semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` # WebIDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a WebIDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). ## Status All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't Use This Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. # debug [![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. <img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png"> ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Usage in child processes Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. For example: ```javascript worker = fork(WORKER_WRAP_PATH, [workerPath], { stdio: [ /* stdin: */ 0, /* stdout: */ 'pipe', /* stderr: */ 'pipe', 'ipc', ], env: Object.assign({}, process.env, { DEBUG_COLORS: 1 // without this settings, colors won't be shown }), }); worker.stderr.pipe(process.stderr, { end: false }); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne - Josh Junon ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # parse-passwd [![NPM version](https://img.shields.io/npm/v/parse-passwd.svg?style=flat)](https://www.npmjs.com/package/parse-passwd) [![NPM downloads](https://img.shields.io/npm/dm/parse-passwd.svg?style=flat)](https://npmjs.org/package/parse-passwd) [![Linux Build Status](https://img.shields.io/travis/doowb/parse-passwd.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/parse-passwd) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/parse-passwd.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/parse-passwd) > Parse a passwd file into a list of users. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save parse-passwd ``` ## Usage ```js var parse = require('parse-passwd'); ``` ## API **Example** ```js // assuming '/etc/passwd' contains: // doowb:*:123:123:Brian Woodward:/Users/doowb:/bin/bash console.log(parse(fs.readFileSync('/etc/passwd', 'utf8'))); //=> [ //=> { //=> username: 'doowb', //=> password: '*', //=> uid: '123', //=> gid: '123', //=> gecos: 'Brian Woodward', //=> homedir: '/Users/doowb', //=> shell: '/bin/bash' //=> } //=> ] ``` **Params** * `content` **{String}**: Content of a passwd file to parse. * `returns` **{Array}**: Array of user objects parsed from the content. ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for avice on opening issues, pull requests, and coding standards. ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Brian Woodward** * [github/doowb](https://github.com/doowb) * [twitter/doowb](http://twitter.com/doowb) ### License Copyright © 2016, [Brian Woodward](https://github.com/doowb). Released under the [MIT license](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 19, 2016._ # simple-get [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [ci-image]: https://img.shields.io/github/workflow/status/feross/simple-get/ci/master [ci-url]: https://github.com/feross/simple-get/actions [npm-image]: https://img.shields.io/npm/v/simple-get.svg [npm-url]: https://npmjs.org/package/simple-get [downloads-image]: https://img.shields.io/npm/dm/simple-get.svg [downloads-url]: https://npmjs.org/package/simple-get [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Simplest way to make http get requests ## features This module is the lightest possible wrapper on top of node.js `http`, but supporting these essential features: - follows redirects - automatically handles gzip/deflate responses - supports HTTPS - supports specifying a timeout - supports convenience `url` key so there's no need to use `url.parse` on the url when specifying options - composes well with npm packages for features like cookies, proxies, form data, & OAuth All this in < 100 lines of code. ## install ``` npm install simple-get ``` ## usage Note, all these examples also work in the browser with [browserify](http://browserify.org/). ### simple GET request Doesn't get easier than this: ```js const get = require('simple-get') get('http://example.com', function (err, res) { if (err) throw err console.log(res.statusCode) // 200 res.pipe(process.stdout) // `res` is a stream }) ``` ### even simpler GET request If you just want the data, and don't want to deal with streams: ```js const get = require('simple-get') get.concat('http://example.com', function (err, res, data) { if (err) throw err console.log(res.statusCode) // 200 console.log(data) // Buffer('this is the server response') }) ``` ### POST, PUT, PATCH, HEAD, DELETE support For `POST`, call `get.post` or use option `{ method: 'POST' }`. ```js const get = require('simple-get') const opts = { url: 'http://example.com', body: 'this is the POST body' } get.post(opts, function (err, res) { if (err) throw err res.pipe(process.stdout) // `res` is a stream }) ``` #### A more complex example: ```js const get = require('simple-get') get({ url: 'http://example.com', method: 'POST', body: 'this is the POST body', // simple-get accepts all options that node.js `http` accepts // See: http://nodejs.org/api/http.html#http_http_request_options_callback headers: { 'user-agent': 'my cool app' } }, function (err, res) { if (err) throw err // All properties/methods from http.IncomingResponse are available, // even if a gunzip/inflate transform stream was returned. // See: http://nodejs.org/api/http.html#http_http_incomingmessage res.setTimeout(10000) console.log(res.headers) res.on('data', function (chunk) { // `chunk` is the decoded response, after it's been gunzipped or inflated // (if applicable) console.log('got a chunk of the response: ' + chunk) })) }) ``` ### JSON You can serialize/deserialize request and response with JSON: ```js const get = require('simple-get') const opts = { method: 'POST', url: 'http://example.com', body: { key: 'value' }, json: true } get.concat(opts, function (err, res, data) { if (err) throw err console.log(data.key) // `data` is an object }) ``` ### Timeout You can set a timeout (in milliseconds) on the request with the `timeout` option. If the request takes longer than `timeout` to complete, then the entire request will fail with an `Error`. ```js const get = require('simple-get') const opts = { url: 'http://example.com', timeout: 2000 // 2 second timeout } get(opts, function (err, res) {}) ``` ### One Quick Tip It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. ```js const get = require('simple-get') const pkg = require('./package.json') get('http://example.com', { headers: { 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)` } }) ``` ### Proxies You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies: ```js const get = require('simple-get') const tunnel = require('tunnel') const opts = { url: 'http://example.com', agent: tunnel.httpOverHttp({ proxy: { host: 'localhost' } }) } get(opts, function (err, res) {}) ``` ### Cookies You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request: ```js const get = require('simple-get') const cookie = require('cookie') const opts = { url: 'http://example.com', headers: { cookie: cookie.serialize('foo', 'bar') } } get(opts, function (err, res) {}) ``` ### Form data You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data: ```js const fs = require('fs') const get = require('simple-get') const FormData = require('form-data') const form = new FormData() form.append('my_file', fs.createReadStream('/foo/bar.jpg')) const opts = { url: 'http://example.com', body: form } get.post(opts, function (err, res) {}) ``` #### Or, include `application/x-www-form-urlencoded` form data manually: ```js const get = require('simple-get') const opts = { url: 'http://example.com', form: { key: 'value' } } get.post(opts, function (err, res) {}) ``` ### Specifically disallowing redirects ```js const get = require('simple-get') const opts = { url: 'http://example.com/will-redirect-elsewhere', followRedirects: false } // res.statusCode will be 301, no error thrown get(opts, function (err, res) {}) ``` ### Basic Auth ```js const user = 'someuser' const pass = 'pa$$word' const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64') get('http://example.com', { headers: { authorization: `Basic ${encodedAuth}` } }) ``` ### OAuth You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request: ```js const get = require('simple-get') const crypto = require('crypto') const OAuth = require('oauth-1.0a') const oauth = OAuth({ consumer: { key: process.env.CONSUMER_KEY, secret: process.env.CONSUMER_SECRET }, signature_method: 'HMAC-SHA1', hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64') }) const token = { key: process.env.ACCESS_TOKEN, secret: process.env.ACCESS_TOKEN_SECRET } const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' const opts = { url: url, headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)), json: true } get(opts, function (err, res) {}) ``` ### Throttle requests You can use [limiter](https://github.com/jhurliman/node-rate-limiter) to throttle requests. This is useful when calling an API that is rate limited. ```js const simpleGet = require('simple-get') const RateLimiter = require('limiter').RateLimiter const limiter = new RateLimiter(1, 'second') const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb)) get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb)) var opts = { url: 'http://example.com' } get.concat(opts, processResult) get.concat(opts, processResult) function processResult (err, res, data) { if (err) throw err console.log(data.toString()) } ``` ## license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). # Platform.js v1.3.5 A platform detection library that works on nearly all JavaScript platforms. ## Disclaimer Platform.js is for informational purposes only & **not** intended as a substitution for feature detection/inference checks. ## Documentation * [doc/README.md](https://github.com/bestiejs/platform.js/blob/master/doc/README.md#readme) * [wiki/Changelog](https://github.com/bestiejs/platform.js/wiki/Changelog) * [wiki/Roadmap](https://github.com/bestiejs/platform.js/wiki/Roadmap) * [platform.js demo](https://bestiejs.github.io/platform.js/) (See also [whatsmyua.info](https://www.whatsmyua.info/) for comparisons between platform.js and other platform detection libraries) ## Installation In a browser: ```html <script src="platform.js"></script> ``` In an AMD loader: ```js require(['platform'], function(platform) {/*…*/}); ``` Using npm: ```shell $ npm i --save platform ``` In Node.js: ```js var platform = require('platform'); ``` Usage example: ```js // on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition platform.name; // 'IE' platform.version; // '10.0' platform.layout; // 'Trident' platform.os; // 'Windows Server 2008 R2 / 7 x64' platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64' // or on an iPad platform.name; // 'Safari' platform.version; // '5.1' platform.product; // 'iPad' platform.manufacturer; // 'Apple' platform.layout; // 'WebKit' platform.os; // 'iOS 5.0' platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)' // or parsing a given UA string var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52'); info.name; // 'Opera' info.version; // '11.52' info.layout; // 'Presto' info.os; // 'Mac OS X 10.7.2' info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2' ``` ## Support Tested in Chrome 82-83, Firefox 77-78, IE 11, Edge 82-83, Safari 12-13, Node.js 4-14, & PhantomJS 2.1.1. ## BestieJS Platform.js is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5+ precedents, unit testing, & plenty of documentation. # universalify [![Travis branch](https://img.shields.io/travis/RyanZim/universalify/master.svg)](https://travis-ci.org/RyanZim/universalify) ![Coveralls github branch](https://img.shields.io/coveralls/github/RyanZim/universalify/master.svg) ![npm](https://img.shields.io/npm/dm/universalify.svg) ![npm](https://img.shields.io/npm/l/universalify.svg) Make a callback- or promise-based function support both promises and callbacks. Uses the native promise implementation. ## Installation ```bash npm install universalify ``` ## API ### `universalify.fromCallback(fn)` Takes a callback-based function to universalify, and returns the universalified function. Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once. ```js function callbackFn (n, cb) { setTimeout(() => cb(null, n), 15) } const fn = universalify.fromCallback(callbackFn) // Works with Promises: fn('Hello World!') .then(result => console.log(result)) // -> Hello World! .catch(error => console.error(error)) // Works with Callbacks: fn('Hi!', (error, result) => { if (error) return console.error(error) console.log(result) // -> Hi! }) ``` ### `universalify.fromPromise(fn)` Takes a promise-based function to universalify, and returns the universalified function. Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned. ```js function promiseFn (n) { return new Promise(resolve => { setTimeout(() => resolve(n), 15) }) } const fn = universalify.fromPromise(promiseFn) // Works with Promises: fn('Hello World!') .then(result => console.log(result)) // -> Hello World! .catch(error => console.error(error)) // Works with Callbacks: fn('Hi!', (error, result) => { if (error) return console.error(error) console.log(result) // -> Hi! }) ``` ## License MIT # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # sha.js [![NPM Package](https://img.shields.io/npm/v/sha.js.svg?style=flat-square)](https://www.npmjs.org/package/sha.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/sha.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/sha.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/sha.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/sha.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `SHA` on pure JavaScript. ```js var shajs = require('sha.js') console.log(shajs('sha256').update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 console.log(new shajs.sha256().update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 var sha256stream = shajs('sha256') sha256stream.end('42') console.log(sha256stream.read().toString('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 ``` ## supported hashes `sha.js` currently implements: - SHA (SHA-0) -- **legacy, do not use in new systems** - SHA-1 -- **legacy, do not use in new systems** - SHA-224 - SHA-256 - SHA-384 - SHA-512 ## Not an actual stream Note, this doesn't actually implement a stream, but wrapping this in a stream is trivial. It does update incrementally, so you can hash things larger than RAM, as it uses a constant amount of memory (except when using base64 or utf8 encoding, see code comments). ## Acknowledgements This work is derived from Paul Johnston's [A JavaScript implementation of the Secure Hash Algorithm](http://pajhome.org.uk/crypt/md5/sha1.html). ## LICENSE [MIT](LICENSE) # reusify [![npm version][npm-badge]][npm-url] [![Build Status][travis-badge]][travis-url] [![Coverage Status][coveralls-badge]][coveralls-url] Reuse your objects and functions for maximum speed. This technique will make any function run ~10% faster. You call your functions a lot, and it adds up quickly in hot code paths. ``` $ node benchmarks/createNoCodeFunction.js Total time 53133 Total iterations 100000000 Iteration/s 1882069.5236482036 $ node benchmarks/reuseNoCodeFunction.js Total time 50617 Total iterations 100000000 Iteration/s 1975620.838848608 ``` The above benchmark uses fibonacci to simulate a real high-cpu load. The actual numbers might differ for your use case, but the difference should not. The benchmark was taken using Node v6.10.0. This library was extracted from [fastparallel](http://npm.im/fastparallel). ## Example ```js var reusify = require('reusify') var fib = require('reusify/benchmarks/fib') var instance = reusify(MyObject) // get an object from the cache, // or creates a new one when cache is empty var obj = instance.get() // set the state obj.num = 100 obj.func() // reset the state. // if the state contains any external object // do not use delete operator (it is slow) // prefer set them to null obj.num = 0 // store an object in the cache instance.release(obj) function MyObject () { // you need to define this property // so V8 can compile MyObject into an // hidden class this.next = null this.num = 0 var that = this // this function is never reallocated, // so it can be optimized by V8 this.func = function () { if (null) { // do nothing } else { // calculates fibonacci fib(that.num) } } } ``` The above example was intended for synchronous code, let's see async: ```js var reusify = require('reusify') var instance = reusify(MyObject) for (var i = 0; i < 100; i++) { getData(i, console.log) } function getData (value, cb) { var obj = instance.get() obj.value = value obj.cb = cb obj.run() } function MyObject () { this.next = null this.value = null var that = this this.run = function () { asyncOperation(that.value, that.handle) } this.handle = function (err, result) { that.cb(err, result) that.value = null that.cb = null instance.release(that) } } ``` Also note how in the above examples, the code, that consumes an istance of `MyObject`, reset the state to initial condition, just before storing it in the cache. That's needed so that every subsequent request for an instance from the cache, could get a clean instance. ## Why It is faster because V8 doesn't have to collect all the functions you create. On a short-lived benchmark, it is as fast as creating the nested function, but on a longer time frame it creates less pressure on the garbage collector. ## Other examples If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). ## Acknowledgements Thanks to [Trevor Norris](https://github.com/trevnorris) for getting me down the rabbit hole of performance, and thanks to [Mathias Buss](http://github.com/mafintosh) for suggesting me to share this trick. ## License MIT [npm-badge]: https://badge.fury.io/js/reusify.svg [npm-url]: https://badge.fury.io/js/reusify [travis-badge]: https://api.travis-ci.org/mcollina/reusify.svg [travis-url]: https://travis-ci.org/mcollina/reusify [coveralls-badge]: https://coveralls.io/repos/mcollina/reusify/badge.svg?branch=master&service=github [coveralls-url]: https://coveralls.io/github/mcollina/reusify?branch=master ## HIDAPI library for Windows, Linux, FreeBSD and macOS | CI instance | Status | |----------------------|--------| | `macOS master` | [![Build Status](https://travis-ci.org/libusb/hidapi.svg?branch=master)](https://travis-ci.org/libusb/hidapi) | | `Windows master` | [![Build status](https://ci.appveyor.com/api/projects/status/r482aevuigmi86rk/branch/master?svg=true)](https://ci.appveyor.com/project/Youw/hidapi/branch/master) | | `Linux/BSD, last build (branch/PR)` | [![builds.sr.ht status](https://builds.sr.ht/~qbicz/hidapi.svg)](https://builds.sr.ht/~qbicz/hidapi?) | HIDAPI is a multi-platform library which allows an application to interface with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and macOS. HIDAPI can be either built as a shared library (`.so`, `.dll` or `.dylib`) or can be embedded directly into a target application by adding a single source file (per platform) and a single header. HIDAPI library was originally developed by Alan Ott ([signal11](https://github.com/signal11)). It was moved to [libusb/hidapi](https://github.com/libusb/hidapi) on June 4th, 2019, in order to merge important bugfixes and continue development of the library. ## Table of Contents * [About](#about) * [What Does the API Look Like?](#what-does-the-api-look-like) * [License](#license) * [Download](#download) * [Build Instructions](#build-instructions) * [Prerequisites](#prerequisites) * [Linux](#linux) * [FreeBSD](#freebsd) * [Mac](#mac) * [Windows](#windows) * [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) * [Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) * [Building on Windows](#building-on-windows) * [Cross Compiling](#cross-compiling) * [Prerequisites](#prerequisites-1) * [Building HIDAPI](#building-hidapi) ## About HIDAPI has five back-ends: * Windows (using `hid.dll`) * Linux/hidraw (using the Kernel's hidraw driver) * Linux/libusb (using libusb-1.0) * FreeBSD (using libusb-1.0) * Mac (using IOHidManager) On Linux, either the hidraw or the libusb back-end can be used. There are tradeoffs, and the functionality supported is slightly different. __Linux/hidraw__ (`linux/hid.c`): This back-end uses the hidraw interface in the Linux kernel, and supports both USB and Bluetooth HID devices. It requires kernel version at least 2.6.39 to build. In addition, it will only communicate with devices which have hidraw nodes associated with them. Keyboards, mice, and some other devices which are blacklisted from having hidraw nodes will not work. Fortunately, for nearly all the uses of hidraw, this is not a problem. __Linux/FreeBSD/libusb__ (`libusb/hid.c`): This back-end uses libusb-1.0 to communicate directly to a USB device. This back-end will of course not work with Bluetooth devices. HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses Fox Toolkit <http://www.fox-toolkit.org>. It will build on every platform which HIDAPI supports. Since it relies on a 3rd party library, building it is optional but recommended because it is so useful when debugging hardware. ## What Does the API Look Like? The API provides the most commonly used HID functions including sending and receiving of input, output, and feature reports. The sample program, which communicates with a heavily hacked up version of the Microchip USB Generic HID sample looks like this (with error checking removed for simplicity): **Warning: Only run the code you understand, and only when it conforms to the device spec. Writing data at random to your HID devices can break them.** ```c #ifdef WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "hidapi.h" #define MAX_STR 255 int main(int argc, char* argv[]) { int res; unsigned char buf[65]; wchar_t wstr[MAX_STR]; hid_device *handle; int i; // Initialize the hidapi library res = hid_init(); // Open the device using the VID, PID, // and optionally the Serial number. handle = hid_open(0x4d8, 0x3f, NULL); // Read the Manufacturer String res = hid_get_manufacturer_string(handle, wstr, MAX_STR); wprintf(L"Manufacturer String: %s\n", wstr); // Read the Product String res = hid_get_product_string(handle, wstr, MAX_STR); wprintf(L"Product String: %s\n", wstr); // Read the Serial Number String res = hid_get_serial_number_string(handle, wstr, MAX_STR); wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr); // Read Indexed String 1 res = hid_get_indexed_string(handle, 1, wstr, MAX_STR); wprintf(L"Indexed String 1: %s\n", wstr); // Toggle LED (cmd 0x80). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = 0x80; res = hid_write(handle, buf, 65); // Request state (cmd 0x81). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = 0x81; res = hid_write(handle, buf, 65); // Read requested state res = hid_read(handle, buf, 65); // Print out the returned buffer. for (i = 0; i < 4; i++) printf("buf[%d]: %d\n", i, buf[i]); // Close the device hid_close(handle); // Finalize the hidapi library res = hid_exit(); return 0; } ``` You can also use [hidtest/test.c](hidtest/test.c) as a starting point for your applications. ## License HIDAPI may be used by one of three licenses as outlined in [LICENSE.txt](LICENSE.txt). ## Download HIDAPI can be downloaded from GitHub ```sh git clone git://github.com/libusb/hidapi.git ``` ## Build Instructions This section is long. Don't be put off by this. It's not long because it's complicated to build HIDAPI; it's quite the opposite. This section is long because of the flexibility of HIDAPI and the large number of ways in which it can be built and used. You will likely pick a single build method. HIDAPI can be built in several different ways. If you elect to build a shared library, you will need to build it from the HIDAPI source distribution. If you choose instead to embed HIDAPI directly into your application, you can skip the building and look at the provided platform Makefiles for guidance. These platform Makefiles are located in `linux/`, `libusb/`, `mac/` and `windows/` and are called `Makefile-manual`. In addition, Visual Studio projects are provided. Even if you're going to embed HIDAPI into your project, it is still beneficial to build the example programs. ### Prerequisites: #### Linux: On Linux, you will need to install development packages for libudev, libusb and optionally Fox-toolkit (for the test GUI). On Debian/Ubuntu systems these can be installed by running: ```sh sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev ``` If you downloaded the source directly from the git repository (using git clone), you'll need Autotools: ```sh sudo apt-get install autotools-dev autoconf automake libtool ``` #### FreeBSD: On FreeBSD you will need to install GNU make, libiconv, and optionally Fox-Toolkit (for the test GUI). This is done by running the following: ```sh pkg_add -r gmake libiconv fox16 ``` If you downloaded the source directly from the git repository (using git clone), you'll need Autotools: ```sh pkg_add -r autotools ``` #### Mac: On Mac, you will need to install Fox-Toolkit if you wish to build the Test GUI. There are two ways to do this, and each has a slight complication. Which method you use depends on your use case. If you wish to build the Test GUI just for your own testing on your own computer, then the easiest method is to install Fox-Toolkit using ports: ```sh sudo port install fox ``` If you wish to build the TestGUI app bundle to redistribute to others, you will need to install Fox-toolkit from source. This is because the version of fox that gets installed using ports uses the ports X11 libraries which are not compatible with the Apple X11 libraries. If you install Fox with ports and then try to distribute your built app bundle, it will simply fail to run on other systems. To install Fox-Toolkit manually, download the source package from <http://www.fox-toolkit.org>, extract it, and run the following from within the extracted source: ```sh ./configure && make && make install ``` #### Windows: On Windows, if you want to build the test GUI, you will need to get the `hidapi-externals.zip` package from the download site. This contains pre-built binaries for Fox-toolkit. Extract `hidapi-externals.zip` just outside of hidapi, so that hidapi-externals and hidapi are on the same level, as shown: ``` Parent_Folder | +hidapi +hidapi-externals ``` Again, this step is not required if you do not wish to build the test GUI. ### Building HIDAPI into a shared library on Unix Platforms: On Unix-like systems such as Linux, FreeBSD, macOS, and even Windows, using MinGW or Cygwin, the easiest way to build a standard system-installed shared library is to use the GNU Autotools build system. If you checked out the source from the git repository, run the following: ```sh ./bootstrap ./configure make make install # as root, or using sudo ``` If you downloaded a source package (i.e.: if you did not run git clone), you can skip the `./bootstrap` step. `./configure` can take several arguments which control the build. The two most likely to be used are: ```sh --enable-testgui Enable build of the Test GUI. This requires Fox toolkit to be installed. Instructions for installing Fox-Toolkit on each platform are in the Prerequisites section above. --prefix=/usr Specify where you want the output headers and libraries to be installed. The example above will put the headers in /usr/include and the binaries in /usr/lib. The default is to install into /usr/local which is fine on most systems. ``` ### Building the manual way on Unix platforms: Manual Makefiles are provided mostly to give the user and idea what it takes to build a program which embeds HIDAPI directly inside of it. These should really be used as examples only. If you want to build a system-wide shared library, use the Autotools method described above. To build HIDAPI using the manual Makefiles, change to the directory of your platform and run make. For example, on Linux run: ```sh cd linux/ make -f Makefile-manual ``` To build the Test GUI using the manual makefiles: ```sh cd testgui/ make -f Makefile-manual ``` ### Building on Windows: To build the HIDAPI DLL on Windows using Visual Studio, build the `.sln` file in the `windows/` directory. To build the Test GUI on windows using Visual Studio, build the `.sln` file in the `testgui/` directory. To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions in the section [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) above. Note that building the Test GUI with MinGW or Cygwin will require the Windows procedure in the [Prerequisites](#prerequisites-1) section above (i.e.: `hidapi-externals.zip`). To build HIDAPI using MinGW using the Manual Makefiles, see the section [Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) above. HIDAPI can also be built using the Windows DDK (now also called the Windows Driver Kit or WDK). This method was originally required for the HIDAPI build but not anymore. However, some users still prefer this method. It is not as well supported anymore but should still work. Patches are welcome if it does not. To build using the DDK: 1. Install the Windows Driver Kit (WDK) from Microsoft. 2. From the Start menu, in the Windows Driver Kits folder, select Build Environments, then your operating system, then the x86 Free Build Environment (or one that is appropriate for your system). 3. From the console, change directory to the `windows/ddk_build/` directory, which is part of the HIDAPI distribution. 4. Type build. 5. You can find the output files (DLL and LIB) in a subdirectory created by the build system which is appropriate for your environment. On Windows XP, this directory is `objfre_wxp_x86/i386`. ## Cross Compiling This section talks about cross compiling HIDAPI for Linux using Autotools. This is useful for using HIDAPI on embedded Linux targets. These instructions assume the most raw kind of embedded Linux build, where all prerequisites will need to be built first. This process will of course vary based on your embedded Linux build system if you are using one, such as OpenEmbedded or Buildroot. For the purpose of this section, it will be assumed that the following environment variables are exported. ```sh $ export STAGING=$HOME/out $ export HOST=arm-linux ``` `STAGING` and `HOST` can be modified to suit your setup. ### Prerequisites Note that the build of libudev is the very basic configuration. Build libusb. From the libusb source directory, run: ```sh ./configure --host=$HOST --prefix=$STAGING make make install ``` Build libudev. From the libudev source directory, run: ```sh ./configure --disable-gudev --disable-introspection --disable-hwdb \ --host=$HOST --prefix=$STAGING make make install ``` ### Building HIDAPI Build HIDAPI: ``` PKG_CONFIG_DIR= \ PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \ PKG_CONFIG_SYSROOT_DIR=$STAGING \ ./configure --host=$HOST --prefix=$STAGING ``` # http2-wrapper > HTTP/2 client, just with the familiar `https` API [![Node CI](https://github.com/szmarczak/http2-wrapper/workflows/Node%20CI/badge.svg)](https://github.com/szmarczak/http2-wrapper/actions) [![codecov](https://codecov.io/gh/szmarczak/http2-wrapper/branch/master/graph/badge.svg)](https://codecov.io/gh/szmarczak/http2-wrapper) [![npm](https://img.shields.io/npm/dm/http2-wrapper.svg)](https://www.npmjs.com/package/http2-wrapper) [![install size](https://packagephobia.now.sh/badge?p=http2-wrapper)](https://packagephobia.now.sh/result?p=http2-wrapper) This package was created to support HTTP/2 without the need to rewrite your code.<br> I recommend adapting to the [`http2`](https://nodejs.org/api/http2.html) module if possible - it's much simpler to use and has many cool features! **Tip**: `http2-wrapper` is very useful when you rely on other modules that use the HTTP/1 API and you want to support HTTP/2. **Pro Tip**: While the native `http2` doesn't have agents yet, you can use `http2-wrapper` Agents and still operate on the native HTTP/2 streams. ## Installation > `$ npm install http2-wrapper`<br> > `$ yarn add http2-wrapper` ## Usage ```js const http2 = require('http2-wrapper'); const options = { hostname: 'nghttp2.org', protocol: 'https:', path: '/httpbin/post', method: 'POST', headers: { 'content-length': 6 } }; const request = http2.request(options, response => { console.log('statusCode:', response.statusCode); console.log('headers:', response.headers); const body = []; response.on('data', chunk => { body.push(chunk); }); response.on('end', () => { console.log('body:', Buffer.concat(body).toString()); }); }); request.on('error', console.error); request.write('123'); request.end('456'); // statusCode: 200 // headers: [Object: null prototype] { // ':status': 200, // date: 'Fri, 27 Sep 2019 19:45:46 GMT', // 'content-type': 'application/json', // 'access-control-allow-origin': '*', // 'access-control-allow-credentials': 'true', // 'content-length': '239', // 'x-backend-header-rtt': '0.002516', // 'strict-transport-security': 'max-age=31536000', // server: 'nghttpx', // via: '1.1 nghttpx', // 'alt-svc': 'h3-23=":4433"; ma=3600', // 'x-frame-options': 'SAMEORIGIN', // 'x-xss-protection': '1; mode=block', // 'x-content-type-options': 'nosniff' // } // body: { // "args": {}, // "data": "123456", // "files": {}, // "form": {}, // "headers": { // "Content-Length": "6", // "Host": "nghttp2.org" // }, // "json": 123456, // "origin": "xxx.xxx.xxx.xxx", // "url": "https://nghttp2.org/httpbin/post" // } ``` ## API **Note:** The `session` option was renamed to `tlsSession` for better readability. ### http2.auto(url, options, callback) Performs [ALPN](https://nodejs.org/api/tls.html#tls_alpn_and_sni) negotiation. Returns a Promise giving proper `ClientRequest` instance (depending on the ALPN). **Note**: The `agent` option represents an object with `http`, `https` and `http2` properties. ```js const http2 = require('http2-wrapper'); const options = { hostname: 'httpbin.org', protocol: 'http:', // Note the `http:` protocol here path: '/post', method: 'POST', headers: { 'content-length': 6 } }; (async () => { try { const request = await http2.auto(options, response => { console.log('statusCode:', response.statusCode); console.log('headers:', response.headers); const body = []; response.on('data', chunk => body.push(chunk)); response.on('end', () => { console.log('body:', Buffer.concat(body).toString()); }); }); request.on('error', console.error); request.write('123'); request.end('456'); } catch (error) { console.error(error); } })(); // statusCode: 200 // headers: { connection: 'close', // server: 'gunicorn/19.9.0', // date: 'Sat, 15 Dec 2018 18:19:32 GMT', // 'content-type': 'application/json', // 'content-length': '259', // 'access-control-allow-origin': '*', // 'access-control-allow-credentials': 'true', // via: '1.1 vegur' } // body: { // "args": {}, // "data": "123456", // "files": {}, // "form": {}, // "headers": { // "Connection": "close", // "Content-Length": "6", // "Host": "httpbin.org" // }, // "json": 123456, // "origin": "xxx.xxx.xxx.xxx", // "url": "http://httpbin.org/post" // } ``` ### http2.auto.protocolCache An instance of [`quick-lru`](https://github.com/sindresorhus/quick-lru) used for ALPN cache. There is a maximum of 100 entries. You can modify the limit through `protocolCache.maxSize` - note that the change will be visible globally. ### http2.request(url, options, callback) Same as [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback). ##### options.h2session Type: `Http2Session`<br> The session used to make the actual request. If none provided, it will use `options.agent`. ### http2.get(url, options, callback) Same as [`https.get`](https://nodejs.org/api/https.html#https_https_get_options_callback). ### new http2.ClientRequest(url, options, callback) Same as [`https.ClientRequest`](https://nodejs.org/api/https.html#https_class_https_clientrequest). ### new http2.IncomingMessage(socket) Same as [`https.IncomingMessage`](https://nodejs.org/api/https.html#https_class_https_incomingmessage). ### new http2.Agent(options) **Note:** this is **not** compatible with the classic `http.Agent`. Usage example: ```js const http2 = require('http2-wrapper'); class MyAgent extends http2.Agent { createConnection(origin, options) { console.log(`Connecting to ${http2.Agent.normalizeOrigin(origin)}`); return http2.Agent.connect(origin, options); } } http2.get({ hostname: 'google.com', agent: new MyAgent() }, res => { res.on('data', chunk => console.log(`Received chunk of ${chunk.length} bytes`)); }); ``` #### options Each option is assigned to each `Agent` instance and can be changed later. ##### timeout Type: `number`<br> Default: `60000` If there's no activity after `timeout` milliseconds, the session will be closed. ##### maxSessions Type: `number`<br> Default: `Infinity` The maximum amount of sessions in total. ##### maxFreeSessions Type: `number`<br> Default: `10` The maximum amount of free sessions in total. This only applies to sessions with no pending requests. **Note:** It is possible that the amount will be exceeded when sessions have at least 1 pending request. ##### maxCachedTlsSessions Type: `number`<br> Default: `100` The maximum amount of cached TLS sessions. #### Agent.normalizeOrigin(url) Returns a string representing the origin of the URL. #### agent.settings Type: `object`<br> Default: `{enablePush: false}` [Settings](https://nodejs.org/api/http2.html#http2_settings_object) used by the current agent instance. #### agent.normalizeOptions([options](https://github.com/szmarczak/http2-wrapper/blob/master/source/agent.js)) Returns a string representing normalized options. ```js Agent.normalizeOptions({servername: 'example.com'}); // => ':example.com' ``` #### agent.getSession(origin, options) ##### [origin](https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener) Type: `string` `URL` `object` An origin used to create new session. ##### [options](https://nodejs.org/api/http2.html#http2_http2_connect_authority_options_listener) Type: `object` The options used to create new session. Returns a Promise giving free `Http2Session`. If no free sessions are found, a new one is created. #### agent.getSession([origin](#origin), [options](options-1), listener) ##### listener Type: `object` ``` { reject: error => void, resolve: session => void } ``` If the `listener` argument is present, the Promise will resolve immediately. It will use the `resolve` function to pass the session. #### agent.request([origin](#origin), [options](#options-1), [headers](https://nodejs.org/api/http2.html#http2_headers_object), [streamOptions](https://nodejs.org/api/http2.html#http2_clienthttp2session_request_headers_options)) Returns a Promise giving `Http2Stream`. #### agent.createConnection([origin](#origin), [options](#options-1)) Returns a new `TLSSocket`. It defaults to `Agent.connect(origin, options)`. #### agent.closeFreeSessions() Makes an attempt to close free sessions. Only sessions with 0 concurrent streams will be closed. #### agent.destroy(reason) Destroys **all** sessions. #### Event: 'session' ```js agent.on('session', session => { // A new session has been created by the Agent. }); ``` ## Proxy support An example of a full-featured proxy server can be found [here](examples/proxy/server.js). It supports **mirroring, custom authorities and the CONNECT protocol**. ### Mirroring To mirror another server we need to use only [`http2-proxy`](https://github.com/nxtedition/node-http2-proxy). We don't need the CONNECT protocol or custom authorities. To see the result, just navigate to the server's address. ### HTTP/1 over HTTP/2 Since we don't care about mirroring, the server needs to support the CONNECT protocol in this case. The client looks like this: ```js const https = require('https'); const http2 = require('http2'); const session = http2.connect('https://localhost:8000', { // For demo purposes only! rejectUnauthorized: false }); session.ref(); https.request('https://httpbin.org/anything', { createConnection: options => { return session.request({ ':method': 'CONNECT', ':authority': `${options.host}:${options.port}` }); } }, response => { console.log('statusCode:', response.statusCode); console.log('headers:', response.headers); const body = []; response.on('data', chunk => { body.push(chunk); }); response.on('end', () => { console.log('body:', Buffer.concat(body).toString()); session.unref(); }); }).end(); ``` ### HTTP/2 over HTTP/2 It's a tricky one! We cannot create an HTTP/2 session on top of an HTTP/2 stream. But... we can still specify the `:authority` header, no need to use the CONNECT protocol here. The client looks like this: ```js const http2 = require('../../source'); const {Agent} = http2; class ProxyAgent extends Agent { constructor(url, options) { super(options); this.origin = url; } request(origin, sessionOptions, headers, streamOptions) { return super.request(this.origin, sessionOptions, { ...headers, ':authority': (new URL(origin)).host }, streamOptions); } } const request = http2.request({ hostname: 'httpbin.org', protocol: 'https:', path: '/anything', agent: new ProxyAgent('https://localhost:8000'), // For demo purposes only! rejectUnauthorized: false }, response => { console.log('statusCode:', response.statusCode); console.log('headers:', response.headers); const body = []; response.on('data', chunk => { body.push(chunk); }); response.on('end', () => { console.log('body:', Buffer.concat(body).toString()); }); }); request.on('error', console.error); request.end(); ``` ## Notes - If you're interested in [WebSockets over HTTP/2](https://tools.ietf.org/html/rfc8441), then [check out this discussion](https://github.com/websockets/ws/issues/1458). - [HTTP/2 sockets cannot be malformed](https://github.com/nodejs/node/blob/cc8250fab86486632fdeb63892be735d7628cd13/lib/internal/http2/core.js#L725), therefore modifying the socket will have no effect. - You can make [a custom Agent](examples/push-stream/index.js) to support push streams. ## Benchmarks CPU: Intel i7-7700k (governor: performance)<br> Server: H2O v2.2.5 [`h2o.conf`](h2o.conf)<br> Node: v14.5.0 Linux: 5.6.18-156.current `auto` means `http2wrapper.auto`. ``` http2-wrapper x 12,181 ops/sec ±3.39% (75 runs sampled) http2-wrapper - preconfigured session x 13,140 ops/sec ±2.51% (79 runs sampled) http2-wrapper - auto x 11,412 ops/sec ±2.55% (78 runs sampled) http2 x 16,050 ops/sec ±1.39% (86 runs sampled) https - auto - keepalive x 12,288 ops/sec ±2.69% (79 runs sampled) https - keepalive x 12,155 ops/sec ±3.32% (78 runs sampled) https x 1,604 ops/sec ±2.03% (77 runs sampled) http x 6,041 ops/sec ±3.82% (76 runs sampled) Fastest is http2 ``` `http2-wrapper`: - 32% **less** performant than `http2` - as performant as `https - keepalive` - 100% **more** performant than `http` `http2-wrapper - preconfigured session`: - 22% **less** performant than `http2` - 8% **more** performant than `https - keepalive` - 118% **more** performant than `http` `http2-wrapper - auto`: - 41% **less** performant than `http2` - 8% **less** performant than `https - keepalive` - 89% **more** performant than `http` `https - auto - keepalive`: - 31% **less** performant than `http2` - as performant as `https - keepalive` - 103% **more** performant than `http` ## Related - [`got`](https://github.com/sindresorhus/got) - Simplified HTTP requests ## License MIT [![codecov](https://codecov.io/gh/alepop/ed25519-hd-key/branch/master/graph/badge.svg)](https://codecov.io/gh/alepop/ed25519-hd-key) ed25519 HD Key ===== Key Derivation for `ed25519` ------------ [SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) - Specification Installation ------------ npm i --save ed25519-hd-key Usage ----- **example:** ```js const { derivePath, getMasterKeyFromSeed, getPublicKey } = require('ed25519-hd-key') const hexSeed = 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'; const { key, chainCode } = getMasterKeyFromSeed(hexSeed); console.log(key.toString('hex')) // => 2b4be7f19ee27bbf30c667b642d5f4aa69fd169872f8fc3059c08ebae2eb19e7 console.log(chainCode.toString('hex')); // => 90046a93de5380a72b5e45010748567d5ea02bbf6522f979e05c0d8d8ca9fffb const { key, chainCode} = derivePath("m/0'/2147483647'", hexSeed); console.log(key.toString('hex')) // => ea4f5bfe8694d8bb74b7b59404632fd5968b774ed545e810de9c32a4fb4192f4 console.log(chainCode.toString('hex')); // => 138f0b2551bcafeca6ff2aa88ba8ed0ed8de070841f0c4ef0165df8181eaad7f console.log(getPublicKey(key).toString('hex')) // => 005ba3b9ac6e90e83effcd25ac4e58a1365a9e35a3d3ae5eb07b9e4d90bcf7506d ``` Tests ----- ``` npm test ``` References ---------- [SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) [BIP-0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) [BIP-0044](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) # readable-stream ***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) ```bash npm install --save readable-stream ``` ***Node-core streams for userland*** This package is a mirror of the Streams2 and Streams3 implementations in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;[email protected]&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;[email protected]&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;[email protected]&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; TweetNaCl.js ============ Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) to JavaScript for modern browsers and Node.js. Public domain. [![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) ](https://travis-ci.org/dchest/tweetnacl-js) Demo: <https://dchest.github.io/tweetnacl-js/> Documentation ============= * [Overview](#overview) * [Audits](#audits) * [Installation](#installation) * [Examples](#examples) * [Usage](#usage) * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) * [Scalar multiplication](#scalar-multiplication) * [Signatures](#signatures) * [Hashing](#hashing) * [Random bytes generation](#random-bytes-generation) * [Constant-time comparison](#constant-time-comparison) * [System requirements](#system-requirements) * [Development and testing](#development-and-testing) * [Benchmarks](#benchmarks) * [Contributors](#contributors) * [Who uses it](#who-uses-it) Overview -------- The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it. There are two versions, you can use either of them: * `nacl.js` is the port of TweetNaCl with minimum differences from the original + high-level API. * `nacl-fast.js` is like `nacl.js`, but with some functions replaced with faster versions. (Used by default when importing NPM package.) Audits ------ TweetNaCl.js has been audited by [Cure53](https://cure53.de/) in January-February 2017 (audit was sponsored by [Deletype](https://deletype.com)): > The overall outcome of this audit signals a particularly positive assessment > for TweetNaCl-js, as the testing team was unable to find any security > problems in the library. It has to be noted that this is an exceptionally > rare result of a source code audit for any project and must be seen as a true > testament to a development proceeding with security at its core. > > To reiterate, the TweetNaCl-js project, the source code was found to be > bug-free at this point. > > [...] > > In sum, the testing team is happy to recommend the TweetNaCl-js project as > likely one of the safer and more secure cryptographic tools among its > competition. [Read full audit report](https://cure53.de/tweetnacl.pdf) Installation ------------ You can install TweetNaCl.js via a package manager: [Yarn](https://yarnpkg.com/): $ yarn add tweetnacl [NPM](https://www.npmjs.org/): $ npm install tweetnacl or [download source code](https://github.com/dchest/tweetnacl-js/releases). Examples -------- You can find usage examples in our [wiki](https://github.com/dchest/tweetnacl-js/wiki/Examples). Usage ----- All API functions accept and return bytes as `Uint8Array`s. If you need to encode or decode strings, use functions from <https://github.com/dchest/tweetnacl-util-js> or one of the more robust codec packages. In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to convert them manually; make sure to convert using copying: `Buffer.from(array)` (or `new Buffer(array)` in Node.js v4 or earlier), instead of sharing: `Buffer.from(array.buffer)` (or `new Buffer(array.buffer)` Node 4 or earlier), because some functions return subarrays of their buffers. ### Public-key authenticated encryption (box) Implements *x25519-xsalsa20-poly1305*. #### nacl.box.keyPair() Generates a new random key pair for box and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 32-byte secret key } #### nacl.box.keyPair.fromSecretKey(secretKey) Returns a key pair for box with public key corresponding to the given secret key. #### nacl.box(message, nonce, theirPublicKey, mySecretKey) Encrypts and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair. Returns an encrypted and authenticated message, which is `nacl.box.overheadLength` longer than the original message. #### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce. Returns the original message, or `null` if authentication fails. #### nacl.box.before(theirPublicKey, mySecretKey) Returns a precomputed shared key which can be used in `nacl.box.after` and `nacl.box.open.after`. #### nacl.box.after(message, nonce, sharedKey) Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.open.after(box, nonce, sharedKey) Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. #### Constants ##### nacl.box.publicKeyLength = 32 Length of public key in bytes. ##### nacl.box.secretKeyLength = 32 Length of secret key in bytes. ##### nacl.box.sharedKeyLength = 32 Length of precomputed shared key in bytes. ##### nacl.box.nonceLength = 24 Length of nonce in bytes. ##### nacl.box.overheadLength = 16 Length of overhead added to box compared to original message. ### Secret-key authenticated encryption (secretbox) Implements *xsalsa20-poly1305*. #### nacl.secretbox(message, nonce, key) Encrypts and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key. Returns an encrypted and authenticated message, which is `nacl.secretbox.overheadLength` longer than the original message. #### nacl.secretbox.open(box, nonce, key) Authenticates and decrypts the given secret box using the key and the nonce. Returns the original message, or `null` if authentication fails. #### Constants ##### nacl.secretbox.keyLength = 32 Length of key in bytes. ##### nacl.secretbox.nonceLength = 24 Length of nonce in bytes. ##### nacl.secretbox.overheadLength = 16 Length of overhead added to secret box compared to original message. ### Scalar multiplication Implements *x25519*. #### nacl.scalarMult(n, p) Multiplies an integer `n` by a group element `p` and returns the resulting group element. #### nacl.scalarMult.base(n) Multiplies an integer `n` by a standard group element and returns the resulting group element. #### Constants ##### nacl.scalarMult.scalarLength = 32 Length of scalar in bytes. ##### nacl.scalarMult.groupElementLength = 32 Length of group element in bytes. ### Signatures Implements [ed25519](http://ed25519.cr.yp.to). #### nacl.sign.keyPair() Generates new random key pair for signing and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 64-byte secret key } #### nacl.sign.keyPair.fromSecretKey(secretKey) Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by `nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. #### nacl.sign.keyPair.fromSeed(seed) Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use `nacl.sign.keyPair` to generate a new key pair from a random seed. #### nacl.sign(message, secretKey) Signs the message using the secret key and returns a signed message. #### nacl.sign.open(signedMessage, publicKey) Verifies the signed message and returns the message without signature. Returns `null` if verification failed. #### nacl.sign.detached(message, secretKey) Signs the message using the secret key and returns a signature. #### nacl.sign.detached.verify(message, signature, publicKey) Verifies the signature for the message and returns `true` if verification succeeded or `false` if it failed. #### Constants ##### nacl.sign.publicKeyLength = 32 Length of signing public key in bytes. ##### nacl.sign.secretKeyLength = 64 Length of signing secret key in bytes. ##### nacl.sign.seedLength = 32 Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. ##### nacl.sign.signatureLength = 64 Length of signature in bytes. ### Hashing Implements *SHA-512*. #### nacl.hash(message) Returns SHA-512 hash of the message. #### Constants ##### nacl.hash.hashLength = 64 Length of hash in bytes. ### Random bytes generation #### nacl.randomBytes(length) Returns a `Uint8Array` of the given length containing random bytes of cryptographic quality. **Implementation note** TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on: * `window.crypto.getRandomValues` (WebCrypto standard) * `window.msCrypto.getRandomValues` (Internet Explorer 11) * `crypto.randomBytes` (Node.js) If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception: * `nacl.randomBytes` * `nacl.box.keyPair` * `nacl.sign.keyPair` Other functions are deterministic and will continue working. If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not `Math.random`!), and you know what you are doing, you can plug it into TweetNaCl.js like this: nacl.setPRNG(function(x, n) { // ... copy n random bytes into x ... }); Note that `nacl.setPRNG` *completely replaces* internal random byte generator with the one provided. ### Constant-time comparison #### nacl.verify(x, y) Compares `x` and `y` in constant time and returns `true` if their lengths are non-zero and equal, and their contents are equal. Returns `false` if either of the arguments has zero length, or arguments have different lengths, or their contents differ. System requirements ------------------- TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of: * Chrome * Firefox * Safari (Mac, iOS) * Internet Explorer 11 Other systems: * Node.js Development and testing ------------------------ Install NPM modules needed for development: $ npm install To build minified versions: $ npm run build Tests use minified version, so make sure to rebuild it every time you change `nacl.js` or `nacl-fast.js`. ### Testing To run tests in Node.js: $ npm run test-node By default all tests described here work on `nacl.min.js`. To test other versions, set environment variable `NACL_SRC` to the file name you want to test. For example, the following command will test fast minified version: $ NACL_SRC=nacl-fast.min.js npm run test-node To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version: $ npm run test-node-all To prepare tests for browsers: $ npm run build-test-browser and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to run them. To run tests in both Node and Electron: $ npm test ### Benchmarking To run benchmarks in Node.js: $ npm run bench $ NACL_SRC=nacl-fast.min.js npm run bench To run benchmarks in a browser, open `test/benchmark/bench.html` (or `test/benchmark/bench-fast.html`). Benchmarks ---------- For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android: | | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | | ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| | salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | | poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | | hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | | secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | | box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | | scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | | sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | | sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | (You can run benchmarks on your devices by clicking on the links at the bottom of the [home page](https://tweetnacl.js.org)). In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 200 and verify 100 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications. Contributors ------------ See AUTHORS.md file. Third-party libraries based on TweetNaCl.js ------------------------------------------- * [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation * [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption * [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) * [tweetnacl-sealed-box](https://github.com/whs/tweetnacl-sealed-box) — implementation of [`sealed boxes`](https://download.libsodium.org/doc/public-key_cryptography/sealed_boxes.html) * [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules Who uses it ----------- Some notable users of TweetNaCl.js: * [GitHub](https://github.com) * [MEGA](https://github.com/meganz/webclient) * [Stellar](https://www.stellar.org/) * [miniLock](https://github.com/kaepora/miniLock) # lodash v4.17.21 The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. ## Installation Using npm: ```shell $ npm i -g npm $ npm i --save lodash ``` In Node.js: ```js // Load the full build. var _ = require('lodash'); // Load the core build. var _ = require('lodash/core'); // Load the FP build for immutable auto-curried iteratee-first data-last methods. var fp = require('lodash/fp'); // Load method categories. var array = require('lodash/array'); var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles. var at = require('lodash/at'); var curryN = require('lodash/fp/curryN'); ``` See the [package source](https://github.com/lodash/lodash/tree/4.17.21-npm) for more details. **Note:**<br> Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. ## Support Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.<br> Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. # Node.js ABI [![Build Status](https://travis-ci.org/lgeiger/node-abi.svg?branch=v1.0.0)](https://travis-ci.org/lgeiger/node-abi) [![Greenkeeper badge](https://badges.greenkeeper.io/lgeiger/node-abi.svg)](https://greenkeeper.io/) Get the Node ABI for a given target and runtime, and vice versa. ## Installation ``` npm install node-abi ``` ## Usage ```javascript const nodeAbi = require('node-abi') nodeAbi.getAbi('7.2.0', 'node') // '51' nodeAbi.getAbi('1.4.10', 'electron') // '50' nodeAbi.getTarget('51', 'node') // '7.2.0' nodeAbi.getTarget('50', 'electron') // '1.4.15' nodeAbi.allTargets // [ // { runtime: 'node', target: '0.10.48', abi: '11', lts: false }, // { runtime: 'node', target: '0.12.17', abi: '14', lts: false }, // { runtime: 'node', target: '4.6.1', abi: '46', lts: true }, // { runtime: 'node', target: '5.12.0', abi: '47', lts: false }, // { runtime: 'node', target: '6.9.4', abi: '48', lts: true }, // { runtime: 'node', target: '7.4.0', abi: '51', lts: false }, // { runtime: 'electron', target: '1.0.2', abi: '47', lts: false }, // { runtime: 'electron', target: '1.2.8', abi: '48', lts: false }, // { runtime: 'electron', target: '1.3.13', abi: '49', lts: false }, // { runtime: 'electron', target: '1.4.15', abi: '50', lts: false } // ] nodeAbi.deprecatedTargets nodeAbi.supportedTargets nodeAbi.additionalTargets nodeAbi.futureTargets // ... ``` ## References - https://github.com/lgeiger/electron-abi - https://nodejs.org/en/download/releases/ - https://github.com/nodejs/Release # braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) > Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save braces ``` ## v3.0.0 Released!! See the [changelog](CHANGELOG.md) for details. ## Why use braces? Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. * **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) * **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. * **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. * **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). * **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). * [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` * [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` * [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` * [Supports escaping](#escaping) - To prevent evaluation of special characters. ## Usage The main export is a function that takes one or more brace `patterns` and `options`. ```js const braces = require('braces'); // braces(patterns[, options]); console.log(braces(['{01..05}', '{a..e}'])); //=> ['(0[1-5])', '([a-e])'] console.log(braces(['{01..05}', '{a..e}'], { expand: true })); //=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] ``` ### Brace Expansion vs. Compilation By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. **Compiled** ```js console.log(braces('a/{x,y,z}/b')); //=> ['a/(x|y|z)/b'] console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); //=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] ``` **Expanded** Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): ```js console.log(braces('a/{x,y,z}/b', { expand: true })); //=> ['a/x/b', 'a/y/b', 'a/z/b'] console.log(braces.expand('{01..10}')); //=> ['01','02','03','04','05','06','07','08','09','10'] ``` ### Lists Expand lists (like Bash "sets"): ```js console.log(braces('a/{foo,bar,baz}/*.js')); //=> ['a/(foo|bar|baz)/*.js'] console.log(braces.expand('a/{foo,bar,baz}/*.js')); //=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] ``` ### Sequences Expand ranges of characters (like Bash "sequences"): ```js console.log(braces.expand('{1..3}')); // ['1', '2', '3'] console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] // supports zero-padded ranges console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] ``` See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. ### Steppped ranges Steps, or increments, may be used with ranges: ```js console.log(braces.expand('{2..10..2}')); //=> ['2', '4', '6', '8', '10'] console.log(braces('{2..10..2}')); //=> ['(2|4|6|8|10)'] ``` When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. ### Nesting Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. **"Expanded" braces** ```js console.log(braces.expand('a{b,c,/{x,y}}/e')); //=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] console.log(braces.expand('a/{x,{1..5},y}/c')); //=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] ``` **"Optimized" braces** ```js console.log(braces('a{b,c,/{x,y}}/e')); //=> ['a(b|c|/(x|y))/e'] console.log(braces('a/{x,{1..5},y}/c')); //=> ['a/(x|([1-5])|y)/c'] ``` ### Escaping **Escaping braces** A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: ```js console.log(braces.expand('a\\{d,c,b}e')); //=> ['a{d,c,b}e'] console.log(braces.expand('a{d,c,b\\}e')); //=> ['a{d,c,b}e'] ``` **Escaping commas** Commas inside braces may also be escaped: ```js console.log(braces.expand('a{b\\,c}d')); //=> ['a{b,c}d'] console.log(braces.expand('a{d\\,c,b}e')); //=> ['ad,ce', 'abe'] ``` **Single items** Following bash conventions, a brace pattern is also not expanded when it contains a single character: ```js console.log(braces.expand('a{b}c')); //=> ['a{b}c'] ``` ## Options ### options.maxLength **Type**: `Number` **Default**: `65,536` **Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. ```js console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error ``` ### options.expand **Type**: `Boolean` **Default**: `undefined` **Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). ```js console.log(braces('a/{b,c}/d', { expand: true })); //=> [ 'a/b/d', 'a/c/d' ] ``` ### options.nodupes **Type**: `Boolean` **Default**: `undefined` **Description**: Remove duplicates from the returned array. ### options.rangeLimit **Type**: `Number` **Default**: `1000` **Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. **Examples** ```js // pattern exceeds the "rangeLimit", so it's optimized automatically console.log(braces.expand('{1..1000}')); //=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] // pattern does not exceed "rangeLimit", so it's NOT optimized console.log(braces.expand('{1..100}')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] ``` ### options.transform **Type**: `Function` **Default**: `undefined` **Description**: Customize range expansion. **Example: Transforming non-numeric values** ```js const alpha = braces.expand('x/{a..e}/y', { transform(value, index) { // When non-numeric values are passed, "value" is a character code. return 'foo/' + String.fromCharCode(value) + '-' + index; } }); console.log(alpha); //=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] ``` **Example: Transforming numeric values** ```js const numeric = braces.expand('{1..5}', { transform(value) { // when numeric values are passed, "value" is a number return 'foo/' + value * 2; } }); console.log(numeric); //=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] ``` ### options.quantifiers **Type**: `Boolean` **Default**: `undefined` **Description**: 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. **Examples** ```js const braces = require('braces'); console.log(braces('a/b{1,3}/{x,y,z}')); //=> [ 'a/b(1|3)/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); //=> [ 'a/b{1,3}/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); //=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] ``` ### options.unescape **Type**: `Boolean` **Default**: `undefined` **Description**: Strip backslashes that were used for escaping from the result. ## What is "brace expansion"? Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). In addition to "expansion", braces are also used for matching. In other words: * [brace expansion](#brace-expansion) is for generating new lists * [brace matching](#brace-matching) is for filtering existing lists <details> <summary><strong>More about brace expansion</strong> (click to expand)</summary> There are two main types of brace expansion: 1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` 2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". Here are some example brace patterns to illustrate how they work: **Sets** ``` {a,b,c} => a b c {a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 ``` **Sequences** ``` {1..9} => 1 2 3 4 5 6 7 8 9 {4..-4} => 4 3 2 1 0 -1 -2 -3 -4 {1..20..3} => 1 4 7 10 13 16 19 {a..j} => a b c d e f g h i j {j..a} => j i h g f e d c b a {a..z..3} => a d g j m p s v y ``` **Combination** Sets and sequences can be mixed together or used along with any other strings. ``` {a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar ``` The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. ## Brace matching In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. For example, the pattern `foo/{1..3}/bar` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar ``` But not: ``` baz/1/qux baz/2/qux baz/3/qux ``` Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` ## Brace matching pitfalls Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. ### tldr **"brace bombs"** * brace expansion can eat up a huge amount of processing resources * as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially * users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. ### The solution Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. ### Geometric complexity At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: ``` {1,2}{3,4} => (2X2) => 13 14 23 24 {1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 ``` But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: ``` {1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 249 257 258 259 267 268 269 347 348 349 357 358 359 367 368 369 ``` Now, imagine how this complexity grows given that each element is a n-tuple: ``` {1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) {1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) ``` Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. **More information** Interested in learning more about brace expansion? * [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) * [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) * [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) </details> ## Performance Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. ### Better algorithms Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. **The proof is in the numbers** Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs)| N/A (freezes) | | `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | | `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | | `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | | `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | | `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | | `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | | `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | | `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | | `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | | `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | | `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | | `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | | `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | | `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | | `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | | `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | ### Faster algorithms When you need expansion, braces is still much faster. _(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | | `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | | `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | | `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | | `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | | `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | | `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | | `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm benchmark ``` ### Latest results Braces is more accurate, without sacrificing performance. ```bash # range (expanded) braces x 29,040 ops/sec ±3.69% (91 runs sampled)) minimatch x 4,735 ops/sec ±1.28% (90 runs sampled) # range (optimized for regex) braces x 382,878 ops/sec ±0.56% (94 runs sampled) minimatch x 1,040 ops/sec ±0.44% (93 runs sampled) # nested ranges (expanded) braces x 19,744 ops/sec ±2.27% (92 runs sampled)) minimatch x 4,579 ops/sec ±0.50% (93 runs sampled) # nested ranges (optimized for regex) braces x 246,019 ops/sec ±2.02% (93 runs sampled) minimatch x 1,028 ops/sec ±0.39% (94 runs sampled) # set (expanded) braces x 138,641 ops/sec ±0.53% (95 runs sampled) minimatch x 219,582 ops/sec ±0.98% (94 runs sampled) # set (optimized for regex) braces x 388,408 ops/sec ±0.41% (95 runs sampled) minimatch x 44,724 ops/sec ±0.91% (89 runs sampled) # nested sets (expanded) braces x 84,966 ops/sec ±0.48% (94 runs sampled) minimatch x 140,720 ops/sec ±0.37% (95 runs sampled) # nested sets (optimized for regex) braces x 263,340 ops/sec ±2.06% (92 runs sampled) minimatch x 28,714 ops/sec ±0.40% (90 runs sampled) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 197 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | | 1 | [hemanth](https://github.com/hemanth) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ is2 === is2 is a type-checking module for JavaScript to test values. Is does not throw exceptions and every function only returns true or false. Use is2 to validate types in your node.js code. Every function in is2 returns either true of false. ## Installation To install is2, type: $ npm install is2 ## Usage const is = require('is2'); console.log(`1===1 is: ${is.equal(true, 1===1)}`); console.log(`10 is a positive number: ${is.positiveNumber(10)}`); console.log(`11 is an odd number: ${is.oddNumber(11)}`); ## API Each function returns true or false. The names after the '-' are aliases, which provide brevity. Environment: * is.browser() * is.defined(val) - is.def * is.nodejs() - is.node() * is.undefined(val) - is.udef, is.undef Types: * is.array(val) - is.ary, is.arry * is.arrayLike(val) - is.arryLike, is.aryLike, is.arrLike * is.arguments(val) - is.args * is.boolean(val) - is.bool * is.buffer(val) - is.buf, is.buff * is.date(val) * is.error(val) - is.err * is.false(val) * is.function(val) - is.funct, is.fun * is.mongoId - is.objectId, is.objId * is.null(val) * is.nullOrUndefined(val) - is.nullOrUndef * is.number(val) - is.num * is.object(val) - is.obj * is.regExp(val) - is.regexp, is.re * is.string(val) - is.str * is.true(val) * is.uuid(val) Relationships: * is.equal(val, other) - is.eq, is.objEquals * is.hosted(val, host) * is.instanceOf(val, constructor) - is.instOf, is.instanceof * is.matching(val1, val2 [, val3, ...]) - is.match : true if the first arument is strictly equal to any of the subsequent args. * is.objectInstanceof(obj, objType) - is.instOf, is.instanceOf, is.objInstOf, is.objectInstanceOf * is.type(val, type) - is.a * is.enumerator(val, array) - is.enum, is.inArray Object State: * is.empty(val) * is.emptyArguments(val) - is.emptyArgs, is.noArgs * is.emptyArray(val) - is.emptyArry, is.emptyAry, is.emptyArray * is.emptyArrayLike(val) - is.emptyArrLike * is.emptyString(val) - is.emptyStr * is.nonEmptyArray(val) - is.nonEmptyArry, is.nonEmptyAry * is.nonEmptyObject(val) - is.nonEmptyObj * is.emptyObject(val) - is.emptyObj * is.nonEmptyString(val) - is.nonEmptyStr Numeric Types within Number: * is.even(val) - is.evenNum, is.evenNumber * is.decimal(val) - is.decNum, is.dec * is.integer(val) - is.int * is.notANumber(val) - is.nan, is.notANum * is.odd(val) - is.oddNum, is.oddNumber Numeric Type and State: * is.positiveNumber(val) - is.pos, is.positive, is.posNum, is.positiveNum * is.negativeNumber(val) - is.neg, is.negNum, is.negativeNum, is.negativeNumber * is.negativeInteger(val) - is.negativeInt, is.negInt * is.positiveInteger(val) - is.posInt, is.positiveInt Numeric Relationship: * is.divisibleBy(val, other) - is.divisBy, is.divBy * is.greaterOrEqualTo(val, other) - is.ge, is.greaterOrEqual * is.greaterThan(val, other) - is.gt * is.lessThanOrEqualTo(val, other) - is.lessThanOrEq, is.lessThanOrEqual, is.le * is.lessThan(val, other) - is.lt * is.maximum(val, array) - is.max * is.minimum(val, array) - is.min * is.withIn(val, start, finish) - is.within * is.prettyClose(val, comp, precision) - is.closish, is.near Networking: * is.dnsAddress(val) - is.dnsAddr, is.dns * is.emailAddress(val) - is.email, is.emailAddr * is.ipv4Address(val) - is.ipv4, is.ipv4Addr * is.ipv6Address(val) - is.ipv6, is.ipv6Addr * is.ipAddress(val) - is.ip, is.ipAddr * is.hostAddress(val) - is.host = is.hostIp = is.hostAddr * is.port(val) * is.systemPort(val) - is.sysPort * is.url(val) - is.uri * is.userPort(val) Credit Cards: * is.creditCardNumber(str) - is.creditCard, is.creditCardNum * is.americanExpressCardNumber(str) - is.amexCardNum, is.amexCard * is.chinaUnionPayCardNumber(str) - is.chinaUnionPayCard, is.chinaUnion * is.dankortCardNumber(str) - is.dankortCard, is.dankort * is.dinersClubCarteBlancheCardNumber(str) - is.dinersClubCarteBlancheCard, is.dinersClubCB * is.dinersClubInternationalCardNumber(str) - is.dinersClubInternationalCard, is.dinersClubInt * is.dinersClubUSACanadaCardNumber(str) - is.dinersClubUSACanCard, is.dinersClub * is.discoverCardNumber(str) - is.discoverCard, is.discover * is.instaPaymentCardNumber(str) - is.instaPayment * is.jcbCardNumber(str) - is.jcbCard, is.jcb * is.laserCardNumber(str) - is.laserCard, is.laser * is.maestroCardNumber(str) - is.maestroCard, is.maestro * is.masterCardCardNumber - is.masterCardCard, is.masterCard * is.visaCardNumber(str) - is.visaCard, is.visa * is.visaElectronCardNumber(str) - is.visaElectronCard, is.visaElectron Personal information: * is.streetAddress(str) - is.street, is.address * is.zipCode(str) - is.zip * is.phoneNumber(str) - is.phone ## License The MIT License (MIT) Copyright (c) 2013,2014 Edmond Meinfelder Copyright (c) 2011 Enrico Marino Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cipher-base === [![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) Abstract base class to inherit from if you want to create streams implementing the same api as node crypto streams. Requires you to implement 2 methods `_final` and `_update`. `_update` takes a buffer and should return a buffer, `_final` takes no arguments and should return a buffer. The constructor takes one argument and that is a string which if present switches it into hash mode, i.e. the object you get from crypto.createHash or crypto.createSign, this switches the name of the final method to be the string you passed instead of `final` and returns `this` from update. # node-supports-preserve-symlinks-flag <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] Determine if the current node version supports the `--preserve-symlinks` flag. ## Example ```js var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); var assert = require('assert'); assert.equal(supportsPreserveSymlinks, null); // in a browser assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag [npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg [deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag [dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg [dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies [npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg [downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag [codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag [actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions gauge ===== A nearly stateless terminal based horizontal gauge / progress bar. ```javascript var Gauge = require("gauge") var gauge = new Gauge() gauge.show("test", 0.20) gauge.pulse("this") gauge.hide() ``` ![](gauge-demo.gif) ### CHANGES FROM 1.x Gauge 2.x is breaking release, please see the [changelog] for details on what's changed if you were previously a user of this module. [changelog]: CHANGELOG.md ### THE GAUGE CLASS This is the typical interface to the module– it provides a pretty fire-and-forget interface to displaying your status information. ``` var Gauge = require("gauge") var gauge = new Gauge([stream], [options]) ``` * **stream** – *(optional, default STDERR)* A stream that progress bar updates are to be written to. Gauge honors backpressure and will pause most writing if it is indicated. * **options** – *(optional)* An option object. Constructs a new gauge. Gauges are drawn on a single line, and are not drawn if **stream** isn't a tty and a tty isn't explicitly provided. If **stream** is a terminal or if you pass in **tty** to **options** then we will detect terminal resizes and redraw to fit. We do this by watching for `resize` events on the tty. (To work around a bug in verisons of Node prior to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to larger window sizes will be clean, but shrinking the window will always result in some cruft. **IMPORTANT:** If you prevously were passing in a non-tty stream but you still want output (for example, a stream wrapped by the `ansi` module) then you need to pass in the **tty** option below, as `gauge` needs access to the underlying tty in order to do things like terminal resizes and terminal width detection. The **options** object can have the following properties, all of which are optional: * **updateInterval**: How often gauge updates should be drawn, in miliseconds. * **fixedFramerate**: Defaults to false on node 0.8, true on everything else. When this is true a timer is created to trigger once every `updateInterval` ms, when false, updates are printed as soon as they come in but updates more often than `updateInterval` are ignored. The reason 0.8 doesn't have this set to true is that it can't `unref` its timer and so it would stop your program from exiting– if you want to use this feature with 0.8 just make sure you call `gauge.disable()` before you expect your program to exit. * **themes**: A themeset to use when selecting the theme to use. Defaults to `gauge/themes`, see the [themes] documentation for details. * **theme**: Select a theme for use, it can be a: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. * **template**: Describes what you want your gauge to look like. The default is what npm uses. Detailed [documentation] is later in this document. * **hideCursor**: Defaults to true. If true, then the cursor will be hidden while the gauge is displayed. * **tty**: The tty that you're ultimately writing to. Defaults to the same as **stream**. This is used for detecting the width of the terminal and resizes. The width used is `tty.columns - 1`. If no tty is available then a width of `79` is assumed. * **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true the gauge starts enabled. If disabled then all update commands are ignored and no gauge will be printed until you call `.enable()`. * **Plumbing**: The class to use to actually generate the gauge for printing. This defaults to `require('gauge/plumbing')` and ordinarly you shouldn't need to override this. * **cleanupOnExit**: Defaults to true. Ordinarily we register an exit handler to make sure your cursor is turned back on and the progress bar erased when your process exits, even if you Ctrl-C out or otherwise exit unexpectedly. You can disable this and it won't register the exit handler. [has-unicode]: https://www.npmjs.com/package/has-unicode [themes]: #themes [documentation]: #templates #### `gauge.show(section | status, [completed])` The first argument is either the section, the name of the current thing contributing to progress, or an object with keys like **section**, **subsection** & **completed** (or any others you have types for in a custom template). If you don't want to update or set any of these you can pass `null` and it will be ignored. The second argument is the percent completed as a value between 0 and 1. Without it, completion is just not updated. You'll also note that completion can be passed in as part of a status object as the first argument. If both it and the completed argument are passed in, the completed argument wins. #### `gauge.hide([cb])` Removes the gauge from the terminal. Optionally, callback `cb` after IO has had an opportunity to happen (currently this just means after `setImmediate` has called back.) It turns out this is important when you're pausing the progress bar on one filehandle and printing to another– otherwise (with a big enough print) node can end up printing the "end progress bar" bits to the progress bar filehandle while other stuff is printing to another filehandle. These getting interleaved can cause corruption in some terminals. #### `gauge.pulse([subsection])` * **subsection** – *(optional)* The specific thing that triggered this pulse Spins the spinner in the gauge to show output. If **subsection** is included then it will be combined with the last name passed to `gauge.show`. #### `gauge.disable()` Hides the gauge and ignores further calls to `show` or `pulse`. #### `gauge.enable()` Shows the gauge and resumes updating when `show` or `pulse` is called. #### `gauge.isEnabled()` Returns true if the gauge is enabled. #### `gauge.setThemeset(themes)` Change the themeset to select a theme from. The same as the `themes` option used in the constructor. The theme will be reselected from this themeset. #### `gauge.setTheme(theme)` Change the active theme, will be displayed with the next show or pulse. This can be: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. #### `gauge.setTemplate(template)` Change the active template, will be displayed with the next show or pulse ### Tracking Completion If you have more than one thing going on that you want to track completion of, you may find the related [are-we-there-yet] helpful. It's `change` event can be wired up to the `show` method to get a more traditional progress bar interface. [are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet ### THEMES ``` var themes = require('gauge/themes') // fetch the default color unicode theme for this platform var ourTheme = themes({hasUnicode: true, hasColor: true}) // fetch the default non-color unicode theme for osx var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) // create a new theme based on the color ascii theme for this platform // that brackets the progress bar with arrows var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), { preProgressbar: '→', postProgressbar: '←' }) ``` The object returned by `gauge/themes` is an instance of the `ThemeSet` class. ``` var ThemeSet = require('gauge/theme-set') var themes = new ThemeSet() // or var themes = require('gauge/themes') var mythemes = themes.newThemeset() // creates a new themeset based on the default themes ``` #### themes(opts) #### themes.getDefault(opts) Theme objects are a function that fetches the default theme based on platform, unicode and color support. Options is an object with the following properties: * **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is available then a non-unicode theme will be used. * **hasColor** - If true, fetch a color theme, if no color theme is available a non-color theme will be used. * **platform** (optional) - Defaults to `process.platform`. If no platform match is available then `fallback` is used instead. If no compatible theme can be found then an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.addTheme(themeName, themeObj) #### themes.addTheme(themeName, [parentTheme], newTheme) Adds a named theme to the themeset. You can pass in either a theme object, as returned by `themes.newTheme` or the arguments you'd pass to `themes.newTheme`. #### themes.getThemeNames() Return a list of all of the names of the themes in this themeset. Suitable for use in `themes.getTheme(…)`. #### themes.getTheme(name) Returns the theme object from this theme set named `name`. If `name` does not exist in this themeset an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.setDefault([opts], themeName) `opts` is an object with the following properties. * **platform** - Defaults to `'fallback'`. If your theme is platform specific, specify that here with the platform from `process.platform`, eg, `win32`, `darwin`, etc. * **hasUnicode** - Defaults to `false`. If your theme uses unicode you should set this to true. * **hasColor** - Defaults to `false`. If your theme uses color you should set this to true. `themeName` is the name of the theme (as given to `addTheme`) to use for this set of `opts`. #### themes.newTheme([parentTheme,] newTheme) Create a new theme object based on `parentTheme`. If no `parentTheme` is provided then a minimal parentTheme that defines functions for rendering the activity indicator (spinner) and progress bar will be defined. (This fallback parent is defined in `gauge/base-theme`.) newTheme should be a bare object– we'll start by discussing the properties defined by the default themes: * **preProgressbar** - displayed prior to the progress bar, if the progress bar is displayed. * **postProgressbar** - displayed after the progress bar, if the progress bar is displayed. * **progressBarTheme** - The subtheme passed through to the progress bar renderer, it's an object with `complete` and `remaining` properties that are the strings you want repeated for those sections of the progress bar. * **activityIndicatorTheme** - The theme for the activity indicator (spinner), this can either be a string, in which each character is a different step, or an array of strings. * **preSubsection** - Displayed as a separator between the `section` and `subsection` when the latter is printed. More generally, themes can have any value that would be a valid value when rendering templates. The properties in the theme are used when their name matches a type in the template. Their values can be: * **strings & numbers** - They'll be included as is * **function (values, theme, width)** - Should return what you want in your output. *values* is an object with values provided via `gauge.show`, *theme* is the theme specific to this item (see below) or this theme object, and *width* is the number of characters wide your result should be. There are a couple of special prefixes: * **pre** - Is shown prior to the property, if its displayed. * **post** - Is shown after the property, if its displayed. And one special suffix: * **Theme** - Its value is passed to a function-type item as the theme. #### themes.addToAllThemes(theme) This *mixes-in* `theme` into all themes currently defined. It also adds it to the default parent theme for this themeset, so future themes added to this themeset will get the values from `theme` by default. #### themes.newThemeset() Copy the current themeset into a new one. This allows you to easily inherit one themeset from another. ### TEMPLATES A template is an array of objects and strings that, after being evaluated, will be turned into the gauge line. The default template is: ```javascript [ {type: 'progressbar', length: 20}, {type: 'activityIndicator', kerning: 1, length: 1}, {type: 'section', kerning: 1, default: ''}, {type: 'subsection', kerning: 1, default: ''} ] ``` The various template elements can either be **plain strings**, in which case they will be be included verbatum in the output, or objects with the following properties: * *type* can be any of the following plus any keys you pass into `gauge.show` plus any keys you have on a custom theme. * `section` – What big thing you're working on now. * `subsection` – What component of that thing is currently working. * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` from your active theme. * `progressbar` – A progress bar representing your current `completed` using the `progressbarTheme` from your active theme. * *kerning* – Number of spaces that must be between this item and other items, if this item is displayed at all. * *maxLength* – The maximum length for this element. If its value is longer it will be truncated. * *minLength* – The minimum length for this element. If its value is shorter it will be padded according to the *align* value. * *align* – (Default: left) Possible values "left", "right" and "center". Works as you'd expect from word processors. * *length* – Provides a single value for both *minLength* and *maxLength*. If both *length* and *minLength or *maxLength* are specifed then the latter take precedence. * *value* – A literal value to use for this template item. * *default* – A default value to use for this template item if a value wasn't otherwise passed in. ### PLUMBING This is the super simple, assume nothing, do no magic internals used by gauge to implement its ordinary interface. ``` var Plumbing = require('gauge/plumbing') var gauge = new Plumbing(theme, template, width) ``` * **theme**: The theme to use. * **template**: The template to use. * **width**: How wide your gauge should be #### `gauge.setTheme(theme)` Change the active theme. #### `gauge.setTemplate(template)` Change the active template. #### `gauge.setWidth(width)` Change the width to render at. #### `gauge.hide()` Return the string necessary to hide the progress bar #### `gauge.hideCursor()` Return a string to hide the cursor. #### `gauge.showCursor()` Return a string to show the cursor. #### `gauge.show(status)` Using `status` for values, render the provided template with the theme and return a string that is suitable for printing to update the gauge. NOTE: The default branch has been renamed! master is now named main If you have a local clone, you can update it by running: ```shell git branch -m master main git fetch origin git branch -u origin/main main ``` # **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead. There are three options for implementing addons: Node-API, nan, or direct use of internal V8, libuv and Node.js libraries. Unless there is a need for direct access to functionality which is not exposed by Node-API as outlined in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) in Node.js core, use Node-API. Refer to [C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) for more information on Node-API. Node-API is an ABI stable C interface provided by Node.js for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as part of Node.js itself. It is intended to insulate native addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. The `node-addon-api` module, which is not part of Node.js, preserves the benefits of the Node-API as it consists only of inline code that depends only on the stable API provided by Node-API. As such, modules built against one version of Node.js using node-addon-api should run without having to be rebuilt with newer versions of Node.js. It is important to remember that *other* Node.js interfaces such as `libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` exclusively and build against a version of Node.js that includes an implementation of Node-API (meaning an active LTS version of Node.js) in order to benefit from ABI stability across Node.js major versions. Node.js provides an [ABI stability guide][] containing a detailed explanation of ABI stability in general, and the Node-API ABI stability guarantee in particular. As new APIs are added to Node-API, node-addon-api must be updated to provide wrappers for those new APIs. For this reason node-addon-api provides methods that allow callers to obtain the underlying Node-API handles so direct calls to Node-API and the use of the objects/methods provided by node-addon-api can be used together. For example, in order to be able to use an API for which the node-addon-api does not yet provide a wrapper. APIs exposed by node-addon-api are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the **ECMA262 Language Specification**. The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. - **[Setup](#setup)** - **[API Documentation](#api)** - **[Examples](#examples)** - **[Tests](#tests)** - **[More resource and info about native Addons](#resources)** - **[Badges](#badges)** - **[Code of Conduct](CODE_OF_CONDUCT.md)** - **[Contributors](#contributors)** - **[License](#license)** ## **Current version: 4.3.0** (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) [![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) <a name="setup"></a> node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-API version. **However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. The oldest Node.js version supported by the current version of node-addon-api is Node.js 12.x. ## Setup - [Installation and usage](doc/setup.md) - [node-gyp](doc/node-gyp.md) - [cmake-js](doc/cmake-js.md) - [Conversion tool](doc/conversion-tool.md) - [Checker tool](doc/checker-tool.md) - [Generator](doc/generator.md) - [Prebuild tools](doc/prebuild_tools.md) <a name="api"></a> ### **API Documentation** The following is the documentation for node-addon-api. - [Full Class Hierarchy](doc/hierarchy.md) - [Addon Structure](doc/addon.md) - Data Types: - [Env](doc/env.md) - [CallbackInfo](doc/callbackinfo.md) - [Reference](doc/reference.md) - [Value](doc/value.md) - [Name](doc/name.md) - [Symbol](doc/symbol.md) - [String](doc/string.md) - [Number](doc/number.md) - [Date](doc/date.md) - [BigInt](doc/bigint.md) - [Boolean](doc/boolean.md) - [External](doc/external.md) - [Object](doc/object.md) - [Array](doc/array.md) - [ObjectReference](doc/object_reference.md) - [PropertyDescriptor](doc/property_descriptor.md) - [Function](doc/function.md) - [FunctionReference](doc/function_reference.md) - [ObjectWrap](doc/object_wrap.md) - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - [Buffer](doc/buffer.md) - [ArrayBuffer](doc/array_buffer.md) - [TypedArray](doc/typed_array.md) - [TypedArrayOf](doc/typed_array_of.md) - [DataView](doc/dataview.md) - [Error Handling](doc/error_handling.md) - [Error](doc/error.md) - [TypeError](doc/type_error.md) - [RangeError](doc/range_error.md) - [Object Lifetime Management](doc/object_lifetime_management.md) - [HandleScope](doc/handle_scope.md) - [EscapableHandleScope](doc/escapable_handle_scope.md) - [Memory Management](doc/memory_management.md) - [Async Operations](doc/async_operations.md) - [AsyncWorker](doc/async_worker.md) - [AsyncContext](doc/async_context.md) - [AsyncWorker Variants](doc/async_worker_variants.md) - [Thread-safe Functions](doc/threadsafe.md) - [ThreadSafeFunction](doc/threadsafe_function.md) - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) - [Promises](doc/promises.md) - [Version management](doc/version_management.md) <a name="examples"></a> ### **Examples** Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** - **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** - **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** - **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** - **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** - **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** - **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** - **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** <a name="tests"></a> ### **Tests** To run the **node-addon-api** tests do: ``` npm install npm test ``` To avoid testing the deprecated portions of the API run ``` npm install npm test --disable-deprecated ``` To run the tests targeting a specific version of Node-API run ``` npm install export NAPI_VERSION=X npm test --NAPI_VERSION=X ``` where X is the version of Node-API you want to target. ### **Debug** To run the **node-addon-api** tests with `--debug` option: ``` npm run-script dev ``` If you want faster build, you might use the following option: ``` npm run-script dev:incremental ``` Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** ### **Benchmarks** You can run the available benchmarks using the following command: ``` npm run-script benchmark ``` See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. <a name="resources"></a> ### **More resource and info about native Addons** - **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** - **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** - **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** - **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** As node-addon-api's core mission is to expose the plain C Node-API as C++ wrappers, tools that facilitate n-api/node-addon-api providing more convenient patterns on developing a Node.js add-ons with n-api/node-addon-api can be published to NPM as standalone packages. It is also recommended to tag such packages with `node-addon-api` to provide more visibility to the community. Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). <a name="other-bindings"></a> ### **Other bindings** - **[napi-rs](https://napi.rs)** - (`Rust`) <a name="badges"></a> ### **Badges** The use of badges is recommended to indicate the minimum version of Node-API required for the module. This helps to determine which Node.js major versions are supported. Addon maintainers can consult the [Node-API support matrix][] to determine which Node.js versions provide a given Node-API version. The following badges are available: ![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) ![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) ![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) ![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) ![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) ![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) ![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) ![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) ![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) ## **Contributing** We love contributions from the community to **node-addon-api**! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. <a name="contributors"></a> ## Team members ### Active | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Chengzhong Wu | [legendecas](https://github.com/legendecas) | | Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Jim Schlight | [jschlight](https://github.com/jschlight) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | | Kevin Eady | [KevinEady](https://github.com/KevinEady) | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | ### Emeritus | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | | Jason Ginchereau | [jasongin](https://github.com/jasongin) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | | Taylor Woll | [boingoing](https://github.com/boingoing) | <a name="license"></a> Licensed under [MIT](./LICENSE.md) [ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ [Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix # core-util-is The `util.is*` functions introduced in Node v0.12. # WebIDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a WebIDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). ## Status All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't Use This Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. # micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml) > Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> - [Install](#install) - [Quickstart](#quickstart) - [Why use micromatch?](#why-use-micromatch) * [Matching features](#matching-features) - [Switching to micromatch](#switching-to-micromatch) * [From minimatch](#from-minimatch) * [From multimatch](#from-multimatch) - [API](#api) - [Options](#options) - [Options Examples](#options-examples) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.expandRange](#optionsexpandrange) * [options.format](#optionsformat) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.noextglob](#optionsnoextglob) * [options.nonegate](#optionsnonegate) * [options.noglobstar](#optionsnoglobstar) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.onIgnore](#optionsonignore) * [options.onMatch](#optionsonmatch) * [options.onResult](#optionsonresult) * [options.posixSlashes](#optionsposixslashes) * [options.unescape](#optionsunescape) - [Extended globbing](#extended-globbing) * [Extglobs](#extglobs) * [Braces](#braces) * [Regex character classes](#regex-character-classes) * [Regex groups](#regex-groups) * [POSIX bracket expressions](#posix-bracket-expressions) - [Notes](#notes) * [Bash 4.3 parity](#bash-43-parity) * [Backslashes](#backslashes) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Latest results](#latest-results) - [Contributing](#contributing) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=8.6): ```sh $ npm install --save micromatch ``` ## Quickstart ```js const micromatch = require('micromatch'); // micromatch(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] ``` Use [.isMatch()](#ismatch) to for boolean matching: ```js console.log(micromatch.isMatch('foo', 'f*')) //=> true console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! <br> ## Why use micromatch? > micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) * More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. * **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). * **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories * **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. * **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) * **Well tested** - More than 5,000 [test assertions](./test) * **Windows support** - More reliable windows support than minimatch and multimatch. * **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. ### Matching features * Support for multiple glob patterns (no need for wrappers like multimatch) * Wildcards (`**`, `*.js`) * Negation (`'!a/*.js'`, `'*!(b).js'`) * [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) * [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) * regex character classes (`foo-[1-5].js`) * regex logical "or" (`foo/(abc|xyz).js`) You can mix and match these features to create whatever patterns you need! ## Switching to micromatch _(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ ### From minimatch Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: ```js console.log(micromatch.isMatch('foo', 'b*')); //=> false ``` Use [micromatch.match()](#match) instead of `minimatch.match()`: ```js console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' ``` ### From multimatch Same signature: ```js console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] ``` ## API **Params** * `list` **{String|Array<string>}**: List of strings to match. * `patterns` **{String|Array<string>}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) * `returns` **{Array}**: Returns an array of matches **Example** ```js const mm = require('micromatch'); // mm(list, patterns[, options]); console.log(mm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.matcher](index.js#L104) Returns a 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. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}** * `returns` **{Function}**: Returns a matcher function. **Example** ```js const mm = require('micromatch'); // mm.matcher(pattern[, options]); const isMatch = mm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.isMatch](index.js#L123) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `[options]` **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.isMatch(string, patterns[, options]); console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(mm.isMatch('a.a', 'b.*')); //=> false ``` ### [.not](index.js#L148) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js const mm = require('micromatch'); // mm.not(list, patterns[, options]); console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L188) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. **Example** ```js var mm = require('micromatch'); // mm.contains(string, pattern[, options]); console.log(mm.contains('aa/bb/cc', '*b')); //=> true console.log(mm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L230) 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. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js const mm = require('micromatch'); // mm.matchKeys(object, patterns[, options]); const obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(mm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.some](index.js#L259) Returns true if some of the strings in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.some(list, patterns[, options]); console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L295) Returns true if every string in the given `list` matches any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.every(list, patterns[, options]); console.log(mm.every('foo.js', ['foo.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.all](index.js#L334) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.all(string, patterns[, options]); console.log(mm.all('foo.js', ['foo.js'])); // true console.log(mm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(mm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.capture](index.js#L361) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `glob` **{String}**: Glob pattern to use for matching. * `input` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. **Example** ```js const mm = require('micromatch'); // mm.capture(pattern, string[, options]); console.log(mm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(mm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L387) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const mm = require('micromatch'); // mm.makeRe(pattern[, options]); console.log(mm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.scan](index.js#L403) Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const mm = require('micromatch'); const state = mm.scan(pattern[, options]); ``` ### [.parse](index.js#L419) Parse a glob pattern to create the source string for a regular expression. **Params** * `glob` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. **Example** ```js const mm = require('micromatch'); const state = mm.parse(pattern[, options]); ``` ### [.braces](index.js#L446) Process the given brace `pattern`. **Params** * `pattern` **{String}**: String with brace pattern to process. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * `returns` **{Array}** **Example** ```js const { braces } = require('micromatch'); console.log(braces('foo/{a,b,c}/bar')); //=> [ 'foo/(a|b|c)/bar' ] console.log(braces('foo/{a,b,c}/bar', { expand: true })); //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] ``` ## Options | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | | `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | ## Options Examples ### options.basename 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`. **Type**: `Boolean` **Default**: `false` **Example** ```js micromatch(['a/b.js', 'a/c.md'], '*.js'); //=> [] micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); //=> ['a/b.js'] ``` ### options.bash 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 any other star. **Type**: `Boolean` **Default**: `true` **Example** ```js const files = ['abc', 'ajz']; console.log(micromatch(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(micromatch(files, '[a-c]*', { bash: false })); ``` ### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. ```js const fill = require('fill-range'); const regex = micromatch.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex) //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` ### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')) //=> true ``` ### options.ignore String or array of glob patterns to match files to ignore. **Type**: `String|Array` **Default**: `undefined` ```js const isMatch = micromatch.matcher('*', { ignore: 'f*' }); console.log(isMatch('foo')) //=> false console.log(isMatch('bar')) //=> true console.log(isMatch('baz')) //=> true ``` ### options.matchBase Alias for [options.basename](#options-basename). ### options.noextglob Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. **Type**: `Boolean` **Default**: `undefined` **Examples** ```js console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); //=> ['a/b', 'a/!(z)'] console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); //=> ['a/!(z)'] (matches only as literal characters) ``` ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. **Type**: `Boolean` **Default**: `undefined` ### options.noglobstar Disable matching with globstars (`**`). **Type**: `Boolean` **Default**: `undefined` ```js micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` ### options.nonull Alias for [options.nullglob](#options-nullglob). ### options.nullglob 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`. **Type**: `Boolean` **Default**: `undefined` ### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } }; const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ input, output }); // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } }; const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); isMatch('some\\path'); isMatch('some\\path'); isMatch('some\\path'); ``` ### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = micromatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.posixSlashes Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. **Type**: `Boolean` **Default**: `true` on windows, `false` everywhere else. **Example** ```js console.log(micromatch.match(['a\\b\\c'], 'a/**')); //=> ['a/b/c'] console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); //=> ['a\\b\\c'] ``` ### options.unescape Remove backslashes from escaped glob characters before creating the regular expression to perform matches. **Type**: `Boolean` **Default**: `undefined` **Example** In this example we want to match a literal `*`: ```js console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); //=> ['a\\*c'] console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); //=> ['a*c'] ``` <br> <br> ## Extended globbing Micromatch supports the following extended globbing features. ### Extglobs Extended globbing, as described by the bash man page: | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | <sup><strong>*</strong></sup> Note that `@` isn't a regex character. ### Braces Brace patterns can be used to match specific ranges or sets of characters. **Example** The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. ### Regex character classes Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). ### Regex groups Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. ### POSIX bracket expressions POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. **Example** ```js console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false ``` *** ## Notes ### Bash 4.3 parity Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. ### Backslashes There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. * Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. We made this decision for micromatch for a couple of reasons: * Consistency with bash conventions. * Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. **A note about joining paths to globs** Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. ## Benchmarks ### Running benchmarks Install dependencies for running benchmarks: ```sh $ cd bench && npm install ``` Run the benchmarks: ```sh $ npm run bench ``` ### Latest results As of March 24, 2022 (longer bars are better): ```sh # .makeRe star micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) # .makeRe star; dot=true micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) # .makeRe globstar micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) # .makeRe globstars micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) # .makeRe with leading star micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) # .makeRe - braces micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) # .makeRe braces - range (expanded) micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) # .makeRe braces - range (compiled) micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) # .makeRe braces - nested ranges (expanded) micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) # .makeRe braces - nested ranges (compiled) micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) # .makeRe braces - set (compiled) micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) # .makeRe braces - nested sets (compiled) micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) ``` ## Contributing All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. **Bug reports** Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: * [research existing issues first](../../issues) (open and closed) * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js * if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. **Platform issues** It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 512 | [jonschlinkert](https://github.com/jonschlinkert) | | 12 | [es128](https://github.com/es128) | | 9 | [danez](https://github.com/danez) | | 8 | [doowb](https://github.com/doowb) | | 6 | [paulmillr](https://github.com/paulmillr) | | 5 | [mrmlnc](https://github.com/mrmlnc) | | 3 | [DrPizza](https://github.com/DrPizza) | | 2 | [TrySound](https://github.com/TrySound) | | 2 | [mceIdo](https://github.com/mceIdo) | | 2 | [Glazy](https://github.com/Glazy) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [antonyk](https://github.com/antonyk) | | 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | | 1 | [amilajack](https://github.com/amilajack) | | 1 | [Cslove](https://github.com/Cslove) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [DianeLooney](https://github.com/DianeLooney) | | 1 | [UltCombo](https://github.com/UltCombo) | | 1 | [frangio](https://github.com/frangio) | | 1 | [joyceerhl](https://github.com/joyceerhl) | | 1 | [juszczykjakub](https://github.com/juszczykjakub) | | 1 | [muescha](https://github.com/muescha) | | 1 | [sebdeckers](https://github.com/sebdeckers) | | 1 | [tomByrer](https://github.com/tomByrer) | | 1 | [fidian](https://github.com/fidian) | | 1 | [curbengh](https://github.com/curbengh) | | 1 | [simlu](https://github.com/simlu) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | | 1 | [yvele](https://github.com/yvele) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2022, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 24, 2022._ # East Asian Width Get [East Asian Width](http://www.unicode.org/reports/tr11/) from a character. 'F'(Fullwidth), 'H'(Halfwidth), 'W'(Wide), 'Na'(Narrow), 'A'(Ambiguous) or 'N'(Natural). Original Code is [東アジアの文字幅 (East Asian Width) の判定 - 中途](http://d.hatena.ne.jp/takenspc/20111126#1322252878). ## Install $ npm install eastasianwidth ## Usage var eaw = require('eastasianwidth'); console.log(eaw.eastAsianWidth('₩')) // 'F' console.log(eaw.eastAsianWidth('。')) // 'H' console.log(eaw.eastAsianWidth('뀀')) // 'W' console.log(eaw.eastAsianWidth('a')) // 'Na' console.log(eaw.eastAsianWidth('①')) // 'A' console.log(eaw.eastAsianWidth('ف')) // 'N' console.log(eaw.characterLength('₩')) // 2 console.log(eaw.characterLength('。')) // 1 console.log(eaw.characterLength('뀀')) // 2 console.log(eaw.characterLength('a')) // 1 console.log(eaw.characterLength('①')) // 2 console.log(eaw.characterLength('ف')) // 1 console.log(eaw.length('あいうえお')) // 10 console.log(eaw.length('abcdefg')) // 7 console.log(eaw.length('¢₩。ᅵㄅ뀀¢⟭a⊙①بف')) // 19 # Statuses [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP status utility for node. This module provides a list of status codes and messages sourced from a few different projects: * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) * The [Node.js project](https://nodejs.org/) * The [NGINX project](https://www.nginx.com/) * The [Apache HTTP Server project](https://httpd.apache.org/) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install statuses ``` ## API <!-- eslint-disable no-unused-vars --> ```js var status = require('statuses') ``` ### var code = status(Integer || String) If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. <!-- eslint-disable no-undef --> ```js status(403) // => 403 status('403') // => 403 status('forbidden') // => 403 status('Forbidden') // => 403 status(306) // throws, as it's not supported by node.js ``` ### status.STATUS_CODES Returns an object which maps status codes to status messages, in the same format as the [Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). ### status.codes Returns an array of all the status codes as `Integer`s. ### var msg = status[code] Map of `code` to `status message`. `undefined` for invalid `code`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status[404] // => 'Not Found' ``` ### var code = status[msg] Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status['not found'] // => 404 status['Not Found'] // => 404 ``` ### status.redirect[code] Returns `true` if a status code is a valid redirect status. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.redirect[200] // => undefined status.redirect[301] // => true ``` ### status.empty[code] Returns `true` if a status code expects an empty body. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.empty[200] // => undefined status.empty[204] // => true status.empty[304] // => true ``` ### status.retry[code] Returns `true` if you should retry the rest. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.retry[501] // => undefined status.retry[503] // => true ``` [npm-image]: https://img.shields.io/npm/v/statuses.svg [npm-url]: https://npmjs.org/package/statuses [node-version-image]: https://img.shields.io/node/v/statuses.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/statuses.svg [travis-url]: https://travis-ci.org/jshttp/statuses [coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg [coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master [downloads-image]: https://img.shields.io/npm/dm/statuses.svg [downloads-url]: https://npmjs.org/package/statuses atob === | **atob** | [btoa](https://git.coolaj86.com/coolaj86/btoa.js) | [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js) | Sponsored by [ppl](https://ppl.family) Uses `Buffer` to emulate the exact functionality of the browser's atob. Note: Unicode may be handled incorrectly (like the browser). It turns base64-encoded <strong>a</strong>scii data back **to** <strong>b</strong>inary. ```javascript (function () { "use strict"; var atob = require('atob'); var b64 = "SGVsbG8sIFdvcmxkIQ=="; var bin = atob(b64); console.log(bin); // "Hello, World!" }()); ``` ### Need Unicode and Binary Support in the Browser? Check out [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js) Changelog ======= * v2.1.0 address a few issues and PRs, update URLs * v2.0.0 provide browser version for ios web workers * v1.2.0 provide (empty) browser version * v1.1.3 add MIT license * v1.1.2 node only LICENSE ======= Code copyright 2012-2018 AJ ONeal Dual-licensed MIT and Apache-2.0 Docs copyright 2012-2018 AJ ONeal Docs released under [Creative Commons](https://git.coolaj86.com/coolaj86/atob.js/blob/master/LICENSE.DOCS). aproba ====== A ridiculously light-weight function argument validator ``` var validate = require("aproba") function myfunc(a, b, c) { // `a` must be a string, `b` a number, `c` a function validate('SNF', arguments) // [a,b,c] is also valid } myfunc('test', 23, function () {}) // ok myfunc(123, 23, function () {}) // type error myfunc('test', 23) // missing arg error myfunc('test', 23, function () {}, true) // too many args error ``` Valid types are: | type | description | :--: | :---------- | * | matches any type | A | `Array.isArray` OR an `arguments` object | S | typeof == string | N | typeof == number | F | typeof == function | O | typeof == object and not type A and not type E | B | typeof == boolean | E | `instanceof Error` OR `null` **(special: see below)** | Z | == `null` Validation failures throw one of three exception types, distinguished by a `code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`. If you pass in an invalid type then it will throw with a code of `EUNKNOWNTYPE`. If an **error** argument is found and is not null then the remaining arguments are optional. That is, if you say `ESO` then that's like using a non-magical `E` in: `E|ESO|ZSO`. ### But I have optional arguments?! You can provide more than one signature by separating them with pipes `|`. If any signature matches the arguments then they'll be considered valid. So for example, say you wanted to write a signature for `fs.createWriteStream`. The docs for it describe it thusly: ``` fs.createWriteStream(path[, options]) ``` This would be a signature of `SO|S`. That is, a string and and object, or just a string. Now, if you read the full `fs` docs, you'll see that actually path can ALSO be a buffer. And options can be a string, that is: ``` path <String> | <Buffer> options <String> | <Object> ``` To reproduce this you have to fully enumerate all of the possible combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The awkwardness is a feature: It reminds you of the complexity you're adding to your API when you do this sort of thing. ### Browser support This has no dependencies and should work in browsers, though you'll have noisier stack traces. ### Why this exists I wanted a very simple argument validator. It needed to do two things: 1. Be more concise and easier to use than assertions 2. Not encourage an infinite bikeshed of DSLs This is why types are specified by a single character and there's no such thing as an optional argument. This is not intended to validate user data. This is specifically about asserting the interface of your functions. If you need greater validation, I encourage you to write them by hand or look elsewhere. # Acorn AST walker An abstract syntax tree walker for the [ESTree](https://github.com/estree/estree) format. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn-walk ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface An algorithm for recursing through a syntax tree is stored as an object, with a property for each tree node type holding a function that will recurse through such a node. There are several ways to run such a walker. **simple**`(node, visitors, base, state)` does a 'simple' walk over a tree. `node` should be the AST node to walk, and `visitors` an object with properties whose names correspond to node types in the [ESTree spec](https://github.com/estree/estree). The properties should contain functions that will be called with the node object and, if applicable the state at that point. The last two arguments are optional. `base` is a walker algorithm, and `state` is a start state. The default walker will simply visit all statements and expressions and not produce a meaningful state. (An example of a use of state is to track scope at each point in the tree.) ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.simple(acorn.parse("let x = 10"), { Literal(node) { console.log(`Found a literal: ${node.value}`) } }) ``` **ancestor**`(node, visitors, base, state)` does a 'simple' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.ancestor(acorn.parse("foo('hi')"), { Literal(_, ancestors) { console.log("This literal's ancestors are:", ancestors.map(n => n.type)) } }) ``` **recursive**`(node, state, functions, base)` does a 'recursive' walk, where the walker functions are responsible for continuing the walk on the child nodes of their target node. `state` is the start state, and `functions` should contain an object that maps node types to walker functions. Such functions are called with `(node, state, c)` arguments, and can cause the walk to continue on a sub-node by calling the `c` argument on it with `(node, state)` arguments. The optional `base` argument provides the fallback walker functions for node types that aren't handled in the `functions` object. If not given, the default walkers will be used. **make**`(functions, base)` builds a new walker object by using the walker functions in `functions` and filling in the missing ones by taking defaults from `base`. **full**`(node, callback, base, state)` does a 'full' walk over a tree, calling the callback with the arguments (node, state, type) for each node **fullAncestor**`(node, callback, base, state)` does a 'full' walk over a tree, building up an array of ancestor nodes (including the current node) and passing the array to the callbacks as a third parameter. ```js const acorn = require("acorn") const walk = require("acorn-walk") walk.full(acorn.parse("1 + 1"), node => { console.log(`There's a ${node.type} node at ${node.ch}`) }) ``` **findNodeAt**`(node, start, end, test, base, state)` tries to locate a node in a tree at the given start and/or end offsets, which satisfies the predicate `test`. `start` and `end` can be either `null` (as wildcard) or a number. `test` may be a string (indicating a node type) or a function that takes `(nodeType, node)` arguments and returns a boolean indicating whether this node is interesting. `base` and `state` are optional, and can be used to specify a custom walker. Nodes are tested from inner to outer, so if two nodes match the boundaries, the inner one will be preferred. **findNodeAround**`(node, pos, test, base, state)` is a lot like `findNodeAt`, but will match any node that exists 'around' (spanning) the given position. **findNodeAfter**`(node, pos, test, base, state)` is similar to `findNodeAround`, but will match all nodes *after* the given position (testing outer nodes before inner nodes). # readable-stream ***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) ```bash npm install --save readable-stream ``` This package is a mirror of the streams implementations in Node.js. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. ## Version 3.x.x v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: 1. Error codes: https://github.com/nodejs/node/pull/13310, https://github.com/nodejs/node/pull/13291, https://github.com/nodejs/node/pull/16589, https://github.com/nodejs/node/pull/15042, https://github.com/nodejs/node/pull/15665, https://github.com/nodejs/readable-stream/pull/344 2. 'readable' have precedence over flowing https://github.com/nodejs/node/pull/18994 3. make virtual methods errors consistent https://github.com/nodejs/node/pull/18813 4. updated streams error handling https://github.com/nodejs/node/pull/18438 5. writable.end should return this. https://github.com/nodejs/node/pull/18780 6. readable continues to read when push('') https://github.com/nodejs/node/pull/18211 7. add custom inspect to BufferList https://github.com/nodejs/node/pull/17907 8. always defer 'readable' with nextTick https://github.com/nodejs/node/pull/17979 ## Version 2.x.x v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. ### Big Thanks Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] # Usage You can swap your `require('stream')` with `require('readable-stream')` without any changes, if you are just using one of the main classes and functions. ```js const { Readable, Writable, Transform, Duplex, pipeline, finished } = require('readable-stream') ```` Note that `require('stream')` will return `Stream`, while `require('readable-stream')` will return `Readable`. We discourage using whatever is exported directly, but rather use one of the properties as shown in the example above. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;[email protected]&gt; [sauce]: https://saucelabs.com # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # json-buffer JSON functions that can convert buffers! [![build status](https://secure.travis-ci.org/dominictarr/json-buffer.png)](http://travis-ci.org/dominictarr/json-buffer) [![testling badge](https://ci.testling.com/dominictarr/json-buffer.png)](https://ci.testling.com/dominictarr/json-buffer) JSON mangles buffers by converting to an array... which isn't helpful. json-buffers converts to base64 instead, and deconverts base64 to a buffer. ``` js var JSONB = require('json-buffer') var Buffer = require('buffer').Buffer var str = JSONB.stringify(new Buffer('hello there!')) console.log(JSONB.parse(str)) //GET a BUFFER back ``` ## License MIT <h1 align=center> <a href="http://chaijs.com" title="Chai Documentation"> <img alt="ChaiJS" src="http://chaijs.com/img/chai-logo.png"/> type-detect </a> </h1> <br> <p align=center> Improved typeof detection for <a href="http://nodejs.org">node</a> and the browser. </p> <p align=center> <a href="./LICENSE"> <img alt="license:mit" src="https://img.shields.io/badge/license-mit-green.svg?style=flat-square" /> </a> <a href="https://github.com/chaijs/type-detect/releases"> <img alt="tag:?" src="https://img.shields.io/github/tag/chaijs/type-detect.svg?style=flat-square" /> </a> <a href="https://travis-ci.org/chaijs/type-detect"> <img alt="build:?" src="https://img.shields.io/travis/chaijs/type-detect/master.svg?style=flat-square" /> </a> <a href="https://coveralls.io/r/chaijs/type-detect"> <img alt="coverage:?" src="https://img.shields.io/coveralls/chaijs/type-detect/master.svg?style=flat-square" /> </a> <a href="https://www.npmjs.com/packages/type-detect"> <img alt="npm:?" src="https://img.shields.io/npm/v/type-detect.svg?style=flat-square" /> </a> <a href="https://www.npmjs.com/packages/type-detect"> <img alt="dependencies:?" src="https://img.shields.io/npm/dm/type-detect.svg?style=flat-square" /> </a> <a href=""> <img alt="devDependencies:?" src="https://img.shields.io/david/chaijs/type-detect.svg?style=flat-square" /> </a> <br/> <table> <tr><th colspan=6>Supported Browsers</th></tr> <tr> <th align=center><img src="https://camo.githubusercontent.com/ab586f11dfcb49bf5f2c2fa9adadc5e857de122a/687474703a2f2f73766773686172652e636f6d2f692f3278532e737667" alt=""> Chrome</th> <th align=center><img src="https://camo.githubusercontent.com/98cca3108c18dcfaa62667b42046540c6822cdac/687474703a2f2f73766773686172652e636f6d2f692f3279352e737667" alt=""> Edge</th> <th align=center><img src="https://camo.githubusercontent.com/acdcb09840a9e1442cbaf1b684f95ab3c3f41cf4/687474703a2f2f73766773686172652e636f6d2f692f3279462e737667" alt=""> Firefox</th> <th align=center><img src="https://camo.githubusercontent.com/728f8cb0bee9ed58ab85e39266f1152c53e0dffd/687474703a2f2f73766773686172652e636f6d2f692f3278342e737667" alt=""> Safari</th> <th align=center><img src="https://camo.githubusercontent.com/96a2317034dee0040d0a762e7a30c3c650c45aac/687474703a2f2f73766773686172652e636f6d2f692f3279532e737667" alt=""> IE</th> </tr><tr> <td align=center>✅</td> <td align=center>✅</td> <td align=center>✅</td> <td align=center>✅</td> <td align=center>9, 10, 11</td> </tr> </table> <br> <a href="https://chai-slack.herokuapp.com/"> <img alt="Join the Slack chat" src="https://img.shields.io/badge/slack-join%20chat-E2206F.svg?style=flat-square" /> </a> <a href="https://gitter.im/chaijs/chai"> <img alt="Join the Gitter chat" src="https://img.shields.io/badge/gitter-join%20chat-D0104D.svg?style=flat-square" /> </a> </p> ## What is Type-Detect? Type Detect is a module which you can use to detect the type of a given object. It returns a string representation of the object's type, either using [`typeof`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-typeof-operator) or [`@@toStringTag`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-symbol.tostringtag). It also normalizes some object names for consistency among browsers. ## Why? The `typeof` operator will only specify primitive values; everything else is `"object"` (including `null`, arrays, regexps, etc). Many developers use `Object.prototype.toString()` - which is a fine alternative and returns many more types (null returns `[object Null]`, Arrays as `[object Array]`, regexps as `[object RegExp]` etc). Sadly, `Object.prototype.toString` is slow, and buggy. By slow - we mean it is slower than `typeof`. By buggy - we mean that some values (like Promises, the global object, iterators, dataviews, a bunch of HTML elements) all report different things in different browsers. `type-detect` fixes all of the shortcomings with `Object.prototype.toString`. We have extra code to speed up checks of JS and DOM objects, as much as 20-30x faster for some values. `type-detect` also fixes any consistencies with these objects. ## Installation ### Node.js `type-detect` is available on [npm](http://npmjs.org). To install it, type: $ npm install type-detect ### Browsers You can also use it within the browser; install via npm and use the `type-detect.js` file found within the download. For example: ```html <script src="./node_modules/type-detect/type-detect.js"></script> ``` ## Usage The primary export of `type-detect` is function that can serve as a replacement for `typeof`. The results of this function will be more specific than that of native `typeof`. ```js var type = require('type-detect'); ``` #### array ```js assert(type([]) === 'Array'); assert(type(new Array()) === 'Array'); ``` #### regexp ```js assert(type(/a-z/gi) === 'RegExp'); assert(type(new RegExp('a-z')) === 'RegExp'); ``` #### function ```js assert(type(function () {}) === 'function'); ``` #### arguments ```js (function () { assert(type(arguments) === 'Arguments'); })(); ``` #### date ```js assert(type(new Date) === 'Date'); ``` #### number ```js assert(type(1) === 'number'); assert(type(1.234) === 'number'); assert(type(-1) === 'number'); assert(type(-1.234) === 'number'); assert(type(Infinity) === 'number'); assert(type(NaN) === 'number'); assert(type(new Number(1)) === 'Number'); // note - the object version has a capital N ``` #### string ```js assert(type('hello world') === 'string'); assert(type(new String('hello')) === 'String'); // note - the object version has a capital S ``` #### null ```js assert(type(null) === 'null'); assert(type(undefined) !== 'null'); ``` #### undefined ```js assert(type(undefined) === 'undefined'); assert(type(null) !== 'undefined'); ``` #### object ```js var Noop = function () {}; assert(type({}) === 'Object'); assert(type(Noop) !== 'Object'); assert(type(new Noop) === 'Object'); assert(type(new Object) === 'Object'); ``` #### ECMA6 Types All new ECMAScript 2015 objects are also supported, such as Promises and Symbols: ```js assert(type(new Map() === 'Map'); assert(type(new WeakMap()) === 'WeakMap'); assert(type(new Set()) === 'Set'); assert(type(new WeakSet()) === 'WeakSet'); assert(type(Symbol()) === 'symbol'); assert(type(new Promise(callback) === 'Promise'); assert(type(new Int8Array()) === 'Int8Array'); assert(type(new Uint8Array()) === 'Uint8Array'); assert(type(new UInt8ClampedArray()) === 'Uint8ClampedArray'); assert(type(new Int16Array()) === 'Int16Array'); assert(type(new Uint16Array()) === 'Uint16Array'); assert(type(new Int32Array()) === 'Int32Array'); assert(type(new UInt32Array()) === 'Uint32Array'); assert(type(new Float32Array()) === 'Float32Array'); assert(type(new Float64Array()) === 'Float64Array'); assert(type(new ArrayBuffer()) === 'ArrayBuffer'); assert(type(new DataView(arrayBuffer)) === 'DataView'); ``` Also, if you use `Symbol.toStringTag` to change an Objects return value of the `toString()` Method, `type()` will return this value, e.g: ```js var myObject = {}; myObject[Symbol.toStringTag] = 'myCustomType'; assert(type(myObject) === 'myCustomType'); ``` # NEAR JavaScript SDK ## Quick Start Use [`create-near-app`](https://github.com/near/create-near-app) to quickly get started writing smart contracts in JavaScript on NEAR. npx create-near-app This will scaffold a basic template for you 😎 Learn more in our [Quick Start guide](https://docs.near.org/develop/quickstart-guide). ## Running Examples There are a couple of contract examples in the project: - [Clean contract state](https://github.com/near/near-sdk-js/tree/develop/examples/src/clean-state.js) - [Counter using low level API](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter-lowlevel.js) - [Counter in JavaScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter.js) - [Counter in TypeScript](https://github.com/near/near-sdk-js/tree/develop/examples/src/counter.ts) - [Doing cross contract call](https://github.com/near/near-sdk-js/tree/develop/examples/src/cross-contract-call.js) - [Fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token.js) - [Lockable fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/fungible-token-lockable.js) - [Non fungible token](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token.js) - [Non fungible token receiver contract](https://github.com/near/near-sdk-js/tree/develop/examples/src/non-fungible-token-receiver.js) - [Status message board](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message.js) - [Status message board with unique messages](https://github.com/near/near-sdk-js/tree/develop/examples/src/status-message-collections.js) To build all examples, run `yarn build` in `examples/`. To test all examples, run `yarn test`. You can also build and test one specific example with `yarn build:<example-name>` and `yarn test:<example-name>`, see `examples/package.json`. To deploy and call a contract on a NEAR node, use near-cli's `near deploy` and `near call`. ## Test We recommend to use near-workspaces to write tests for your smart contracts. See any of the examples for how tests are setup and written. ## Error Handling in NEAR-SDK-JS If you want to indicate an error happened and fail the transaction, just throw an error object in JavaScript. The compiled JavaScript contract includes error handling capability. It will catch throwed errors and automatically invoke `panic_utf8` with `"{error.message}\n:{error.stack}"`. As a result, transaction will fail with `"Smart contract panicked: {error.message}\n{error.stack}"` error message. You can also use an error utilities library to organize your errors, such as verror. When your JS code or library throws an error, uncaught, the transaction will also fail with GuestPanic error, with the error message and stacktrace. When call host function with inappropriate type, means incorrect number of arguments or arg is not expected type: - if arguments less than params, remaining argument are set as 'undefined' - if arguments more than params, remaining argument are ignored - if argument is different than the required type, it'll be coerced to required type - if argument is different than the required type but cannot be coerced, will throw runtime type error, also with message and stacktrace ## NEAR-SDK-JS API Reference All NEAR blockchain provided functionality (host functions) are defined in `src/api.ts` and exported as `near`. You can use them by: ```js import { near } from "near-sdk-js"; // near.<api doucmented below>. e.g.: let signer = near.signerAccountId(); ``` To use nightly host functions, such as `altBn128G1Sum`, your contract need to be built with nightly enabled. Use: ``` export NEAR_NIGHTLY=1 yarn build ``` ### About Type NEAR-SDK-JS is written in TypeScript, so every API function has a type specified by signature that looks familiar to JavaScript/TypeScript Developers. Two types in the signature need a special attention: - Most of the API take `bigint` instead of Number as type. This because JavaScript Number cannot hold 64 bit and 128 bit integer without losing precision. - `Bytes` in both arguments and return represent a byte buffer, internally it's a JavaScript String Object. Any binary data `0x00-0xff` is stored as the char '\x00-\xff'. This is because QuickJS doesn't have Uint8Array in C API. - To ensure correctness, every `Bytes` argument need to be pass in with the `bytes()` function to runtime type check it's indeed a `Bytes`. - If `Bytes` is too long that `bytes()` can cause gas limit problem, such as in factory contract, represents the content of contract to be deployed. In this case you can precheck and guarantee the correctness of the content and use without `bytes()`. ### Context API ``` function currentAccountId(): string; function signerAccountId(): string; function signerAccountPk(): Bytes; function predecessorAccountId(): string; function input(): Bytes; function blockIndex(): bigint; function blockHeight(): bigint; function blockTimestamp(): bigint; function epochHeight(): bigint; function storageUsage(): bigint ``` ### Economics API ``` function accountBalance(): bigint; function accountLockedBalance(): bigint; function attachedDeposit(): bigint; function prepaidGas(): bigint; function usedGas(): bigint; ``` ### Math API ``` function randomSeed(): Bytes; function sha256(value: Bytes): Bytes; function keccak256(value: Bytes): Bytes; function keccak512(value: Bytes): Bytes; function ripemd160(value: Bytes): Bytes; function ecrecover(hash: Bytes, sign: Bytes, v: bigint, malleability_flag: bigint): Bytes | null; ``` ### Miscellaneous API ``` function valueReturn(value: Bytes); function panic(msg?: string); function panicUtf8(msg: Bytes); function log(msg: string); function logUtf8(msg: Bytes); function logUtf16(msg: Bytes); ``` ### Promises API ``` function promiseCreate(account_id: string, method_name: string, arguments: Bytes, amount: bigint, gas: bigint): bigint; function promiseThen(promise_index: bigint, account_id: string, method_name: string, arguments: Bytes, amount: bigint, gas: bigint): bigint; function promiseAnd(...promise_idx: bigint): bigint; function promiseBatchCreate(account_id: string): bigint; function promiseBatchThen(promise_index: bigint, account_id: string): bigint; ``` ### Promise API actions ``` function promiseBatchActionCreateAccount(promise_index: bigint); function promiseBatchActionDeployContract(promise_index: bigint, code: Bytes); function promiseBatchActionFunctionCall(promise_index: bigint, method_name: string, arguments: Bytes, amount: bigint, gas: bigint); function promiseBatchActionFunctionCallWeight(promise_index: bigint, method_name: string, arguments: Bytes, amount: bigint, gas: bigint, weight: bigint); function promiseBatchActionTransfer(promise_index: bigint, amount: bigint); function promiseBatchActionStake(promise_index: bigint, amount: bigint, public_key: Bytes); function promiseBatchActionAddKeyWithFullAccess(promise_index: bigint, public_key: Bytes, nonce: bigint); function promiseBatchActionAddKeyWithFunctionCall(promise_index: bigint, public_key: Bytes, nonce: bigint, allowance: bigint, receiver_id: string, method_names: string); function promiseBatchActionDeleteKey(promise_index: bigint, public_key: Bytes); function promiseBatchActionDeleteAccount(promise_index: bigint, beneficiary_id: string); ``` ### Promise API results ``` function promiseResultsCount(): bigint; function promiseResult(result_idx: bigint, register_id: bigint): bigint; function promiseReturn(promise_idx: bigint); ``` ### Storage API ``` function storageWrite(key: Bytes, value: Bytes, register_id: bigint): bigint; function storageRead(key: Bytes, register_id: bigint): bigint; function storageRemove(key: Bytes, register_id: bigint): bigint; function storageHasKey(key: Bytes): bigint; ``` ### Validator API ``` function validatorStake(account_id: string): bigint; function validatorTotalStake(): bigint; ``` ### Alt BN128 ``` function altBn128G1Multiexp(value: Bytes, register_id: bigint); function altBn128G1Sum(value: Bytes, register_id: bigint); function altBn128PairingCheck(value: Bytes): bigint; ``` ### NearBindgen and other decorators You can write a simple smart contract by only using low-level APIs, such as `near.input()`, `near.storageRead()`, etc. In this case, the API of your contract will consist of all the exported JS functions. You can find an example of such a contract [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/counter-lowlevel.js). But if you want to build a more complex contracts with ease, you can use decorators from this SDK that will handle serialization, deserialization, and other boilerplate operations for you. In order to do that, your contract must be a class decorated with `@NearBindgen({})`. Each method in this class with `@call({})`, `@view({})`, and `@initialize({})` decorators will become functions of your smart contract. `call` functions can change state, and `view` functions can only read it. Your class must have a `constructor()`. You will not be able to call it, which is why it should not accept any parameters. You must declare all the parameters that you are planning to use in the constructor and set default values. The simplest example of the contract that follows all these rules can be found [here](https://github.com/near/near-sdk-js/blob/develop/examples/src/status-message.js) `NearBindgen` decorator can accept `requireInit parameter`. ```JS @NearBindgen({ requireInit: true }) class YourContract { ... } ``` It is `false` by default, but if you will set it to `true`, it will prevent all the `call` functions from being executed before you initialize the state of the contract. In order to initialize the contract, you need to add functions flagged with `@initialize({})` decorator. `@call({})` decorator can accept two parameters: `privateFunction` and `payableFunction`. They are both `false` by default. `privateFunction: true` can restrict access to this function to the contract itself. `payableFunction: true` will allow the function to accept payments (deposit). Without this flag, it will panic if any deposit was provided. ### Collections A few useful on-chain persistent collections are provided. All keys, values and elements are of type `Bytes`. #### Vector Vector is an iterable implementation of vector that stores its content on the trie. Usage: ```js import {Vector} from 'near-sdk-js' // in contract class constructor: constructor() { super() this.v = new Vector('my_prefix_') } // Override the deserializer to load vector from chain deserialize() { super.deserialize() this.v = Object.assign(new Vector, this.v) } someMethod() { // insert this.v.push('abc') this.v.push('def') this.v.push('ghi') // batch insert, extend: this.v.extend(['xyz', '123']) // get let first = this.v.get(0) // remove, move the last element to the given index this.v.swapRemove(0) // replace this.v.replace(1, 'jkl') // remove the last this.v.pop() // len, isEmpty let len = this.v.length let isEmpty = this.v.isEmpty() // iterate for (let element of this.v) { near.log(element) } // toArray, convert to JavaScript Array let a = this.v.toArray() // clear ths.v.clear() } ``` #### LookupMap LookupMap is an non-iterable implementation of a map that stores its content directly on the trie. It's like a big hash map, but on trie. Usage: ```js import {LookupMap} from 'near-sdk-js' // in contract class constructor: constructor() { super() this.m = new LookupMap('prefix_a') } // Override the deserializer to load vector from chain deserialize() { super.deserialize() this.m = Object.assign(new LookupMap, this.m) } someMethod() { // insert this.m.set('abc', 'aaa') this.m.set('def', 'bbb') this.m.set('ghi', 'ccc') // batch insert, extend: this.m.extend([['xyz', '123'], ['key2', 'value2']]) // check exist let exist = this.m.containsKey('abc') // get let value = this.m.get('abc') // remove this.m.remove('def') // replace this.m.set('ghi', 'ddd') } ``` #### LookupSet LookupSet is an non-iterable implementation of a set that stores its content directly on the trie. It's like LookupMap, but it only stores whether the value presents. Usage: ```js import {LookupSet} from 'near-sdk-js' // in contract class constructor: constructor() { super() this.s = new LookupSet('prefix_b') } // Override the deserializer to load vector from chain deserialize() { super.deserialize() this.s = Object.assign(new LookupSet, this.s) } someMethod() { // insert this.s.set('abc') this.s.set('def') this.s.set('ghi') // batch insert, extend: this.s.extend(['xyz', '123']) // check exist let exist = this.s.contains('abc') // remove this.s.remove('def') } ``` #### UnorderedMap UnorderedMap is an iterable implementation of a map that stores its content directly on the trie. Usage: ```js import {UnorderedMap} from 'near-sdk-js' // in contract class constructor: constructor() { super() this.m = new UnorderedMap('prefix_c') } // Override the deserializer to load vector from chain deserialize() { super.deserialize() this.m.keys = Object.assign(new Vector, this.m.keys) this.m.values = Object.assign(new Vector, this.m.values) this.m = Object.assign(new UnorderedMap, this.m) } someMethod() { // insert this.m.set('abc', 'aaa') this.m.set('def', 'bbb') this.m.set('ghi', 'ccc') // batch insert, extend: this.m.extend([['xyz', '123'], ['key2', 'value2']]) // get let value = this.m.get('abc') // remove this.m.remove('def') // replace this.m.set('ghi', 'ddd') // len, isEmpty let len = this.m.length let isEmpty = this.m.isEmpty() // iterate for (let [k, v] of this.m) { near.log(k+v) } // toArray, convert to JavaScript Array let a = this.m.toArray() // clear this.m.clear() } ``` #### UnorderedSet UnorderedSet is an iterable implementation of a set that stores its content directly on the trie. It's like UnorderedMap but it only stores whether the value presents. Usage: ```js import {UnorderedSet} from 'near-sdk-js' // in contract class constructor: constructor() { super() this.s = new UnorderedSet('prefix_d') } // Override the deserializer to load vector from chain deserialize() { super.deserialize() this.s.elements = Object.assign(new Vector, this.s.elements) this.s = Object.assign(new UnorderedSet, this.s) } someMethod() { // insert this.s.set('abc') this.s.set('def') this.s.set('ghi') // batch insert, extend: this.s.extend(['xyz', '123']) // check exist let exist = this.s.contains('abc') // remove this.s.remove('def') // len, isEmpty let len = this.s.length let isEmpty = this.s.isEmpty() // iterate for (let e of this.s) { near.log(e) } // toArray, convert to JavaScript Array let a = this.s.toArray() // clear this.s.clear() } ``` ### Highlevel Promise APIs Within a contract class that decorated by `@Nearbindgen`, you can work a high level JavaScript class, called `NearPromise`. It's equivalently expressive as promise batch APIs but much shorter to write and can be chained like a JavaScript Promise. In a `@call` method, you can return either a JavaScript value or a `NearPromise` object. In the later case, `@NearBindgen` will automatically `promiseReturn` it for you. Usage: ```js // create new promise import { NearPromise, near, includeBytes } from "near-sdk-js"; import { PublicKey } from "near-sdk-js/lib/types"; let promise = NearPromise.new("account-to-run-promise"); // possible promise actions, choose and chain what you need: promise .createAccount() .transfer(1_000_000_000_000_000_000_000_000_000_000_000_000n) .addFullAccessKey(new PublicKey(near.signerAccountPk())) .addAccessKey( new PublicKey(near.signerAccountPk()), 250000000000000000000000n, // allowance "receiver_account_id", "allowed_function_names" ) .stake(100000000000000000000000000000n, new PublicKey(near.signerAccountPk())) .deployContract(includeBytes("path/to/contract.wasm")) .functionCall( "callee_contract_account_id", inputArgs, 0, // amount 2 * Math.pow(10, 13) // gas ) .functionCallWeight( "callee_contract_account_id", inputArgs, 0, // amount 2 * Math.pow(10, 13), // gas 1 // weight ) .deleteKey(new PublicKey(near.signerAccountPk())) .deleteAccount("beneficial_account_id"); return promise; ``` In the case of deploy contract, `includeBytes` is a helpful build-time util. You can include the content of a wasm contract, by using `includeBytes('path/to/contract.wasm')`. In the case of `addFullAccessKey`, `addAccessKey` and `stake`, it takes a `PublicKey` object, you can find more details about it in the Types sections below. Besides above APIs to build something on top of an API, you can also chain promises with `.then` and `.and`, they're equivalent to promiseThen, promiseAnd: ```js // assume promise, promise2 and promise3 are create with above APIs, with several actions added like above. promise.and(promise2).then(promise3); // promiseAnd of [promise_id, promise2_id], then promiseThen(promise_and_id, promise3_id) return promise; ``` ### Types NEAR-SDK-JS also includes type defintions that are equivalent to that in Rust SDK / nearcore. You can browse them in near-sdk-js/src/types. Most of them are just type alias to Bytes and bigint. #### Public Key Public Key is representing a NEAR account's public key in a JavaScript class. You can either initiate a Public Key from binary data, or from a human readable string. The binary data is in the same format as nearcore, but encoded in bytes. That's one byte to represent the curve type of the public key, either ed25519 (`\x00`), or secp256k1 ('\x01'), follows by the curve-specific public key data in bytes. Examples: ```js new PublicKey(near.signerAccountPk()); new PublicKey( "\x00\xeb\x7f\x5f\x11\xd1\x08\x1f\xe0\xd2\x24\xc5\x67\x36\x21\xad\xcb\x97\xd5\x13\xff\xa8\x5e\x55\xbc\x2b\x74\x4f\x0d\xb1\xe9\xf8\x1f" ); new PublicKey( "\x01\xf2\x56\xc6\xe6\xc8\x0b\x21\x3f\x2a\xa0\xb0\x17\x44\x23\x5d\x51\x5c\x59\x44\x35\xbe\x65\x1b\x15\x88\x3a\x10\xdd\x47\x2f\xa6\x46\xce\x62\xea\xf3\x67\x0d\xc5\xcb\x91\x00\xa0\xca\x2a\x55\xb2\xc1\x47\xc1\xe9\xa3\x8c\xe4\x28\x87\x8e\x7d\x46\xe1\xfb\x71\x4a\x99" ); ``` The human readable form is `ed25519:` or `secp256k1:` following base58-encoded public key. And initialize the Public Key with `PublicKey.fromString`: ```js PublicKey.fromString('ed25519:DXkVZkHd7WUUejCK7i74uAoZWy1w9AZqshhTHxhmqHuB`) PublicKey.fromString('secp256k1:5r22SrjrDvgY3wdQsnjgxkeAbU1VcM71FYvALEQWihjM3Xk4Be1CpETTqFccChQr4iJwDroSDVmgaWZv2AcXvYeL`) ``` Once a PublicKey object is created, it can be used in high level promise APIs that takes a public key, such as `addFullAccessKey`, `addAccessKey` and `stake`. # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # TypeScript [![GitHub Actions CI](https://github.com/microsoft/TypeScript/workflows/CI/badge.svg)](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI) [![Devops Build Status](https://dev.azure.com/typescript/TypeScript/_apis/build/status/Typescript/node10)](https://dev.azure.com/typescript/TypeScript/_build?definitionId=7) [![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript) [![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript) [TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript). Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/). ## Installing For the latest stable version: ```bash npm install -g typescript ``` For our nightly builds: ```bash npm install -g typescript@next ``` ## Contribute There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript. * [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). * Help each other in the [TypeScript Community Discord](https://discord.gg/typescript). * Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter. * [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md). * Read the archived language specification ([docx](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.docx?raw=true), [pdf](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.pdf?raw=true), [md](https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md)). This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. ## Documentation * [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) * [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html) * [Homepage](https://www.typescriptlang.org/) ## Roadmap For details on our planned features and future direction please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap). semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # Console Control Strings A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted. ## Usage ```js var consoleControl = require('console-control-strings') console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) process.stdout.write(consoleControl.goto(75, 10)) ``` ## Why Another? There are tons of libraries similar to this one. I wanted one that was: 1. Very clear about compatibility goals. 2. Could emit, for instance, a start color code without an end one. 3. Returned strings w/o writing to streams. 4. Was not weighed down with other unrelated baggage. ## Functions ### var code = consoleControl.up(_num = 1_) Returns the escape sequence to move _num_ lines up. ### var code = consoleControl.down(_num = 1_) Returns the escape sequence to move _num_ lines down. ### var code = consoleControl.forward(_num = 1_) Returns the escape sequence to move _num_ lines righ. ### var code = consoleControl.back(_num = 1_) Returns the escape sequence to move _num_ lines left. ### var code = consoleControl.nextLine(_num = 1_) Returns the escape sequence to move _num_ lines down and to the beginning of the line. ### var code = consoleControl.previousLine(_num = 1_) Returns the escape sequence to move _num_ lines up and to the beginning of the line. ### var code = consoleControl.eraseData() Returns the escape sequence to erase everything from the current cursor position to the bottom right of the screen. This is line based, so it erases the remainder of the current line and all following lines. ### var code = consoleControl.eraseLine() Returns the escape sequence to erase to the end of the current line. ### var code = consoleControl.goto(_x_, _y_) Returns the escape sequence to move the cursor to the designated position. Note that the origin is _1, 1_ not _0, 0_. ### var code = consoleControl.gotoSOL() Returns the escape sequence to move the cursor to the beginning of the current line. (That is, it returns a carriage return, `\r`.) ### var code = consoleControl.beep() Returns the escape sequence to cause the termianl to beep. (That is, it returns unicode character `\x0007`, a Control-G.) ### var code = consoleControl.hideCursor() Returns the escape sequence to hide the cursor. ### var code = consoleControl.showCursor() Returns the escape sequence to show the cursor. ### var code = consoleControl.color(_colors = []_) ### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) Returns the escape sequence to set the current terminal display attributes (mostly colors). Arguments can either be a list of attributes or an array of attributes. The difference between passing in an array or list of colors and calling `.color` separately for each one, is that in the former case a single escape sequence will be produced where as in the latter each change will have its own distinct escape sequence. Each attribute can be one of: * Reset: * **reset** – Reset all attributes to the terminal default. * Styles: * **bold** – Display text as bold. In some terminals this means using a bold font, in others this means changing the color. In some it means both. * **italic** – Display text as italic. This is not available in most Windows terminals. * **underline** – Underline text. This is not available in most Windows Terminals. * **inverse** – Invert the foreground and background colors. * **stopBold** – Do not display text as bold. * **stopItalic** – Do not display text as italic. * **stopUnderline** – Do not underline text. * **stopInverse** – Do not invert foreground and background. * Colors: * **white** * **black** * **blue** * **cyan** * **green** * **magenta** * **red** * **yellow** * **grey** / **brightBlack** * **brightRed** * **brightGreen** * **brightYellow** * **brightBlue** * **brightMagenta** * **brightCyan** * **brightWhite** * Background Colors: * **bgWhite** * **bgBlack** * **bgBlue** * **bgCyan** * **bgGreen** * **bgMagenta** * **bgRed** * **bgYellow** * **bgGrey** / **bgBrightBlack** * **bgBrightRed** * **bgBrightGreen** * **bgBrightYellow** * **bgBrightBlue** * **bgBrightMagenta** * **bgBrightCyan** * **bgBrightWhite** # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # Can I cache this? [![Build Status](https://travis-ci.org/kornelski/http-cache-semantics.svg?branch=master)](https://travis-ci.org/kornelski/http-cache-semantics) `CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. ## Usage Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. ```js const policy = new CachePolicy(request, response, options); if (!policy.storable()) { // throw the response away, it's not usable at all return; } // Cache the data AND the policy object in your cache // (this is pseudocode, roll your own cache (lru-cache package works)) letsPretendThisIsSomeCache.set( request.url, { policy, response }, policy.timeToLive() ); ``` ```js // And later, when you receive a new request: const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url); // It's not enough that it exists in the cache, it has to match the new request, too: if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { // OK, the previous response can be used to respond to the `newRequest`. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. response.headers = policy.responseHeaders(); return response; } ``` It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc. The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. ### Constructor options Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method). ```js const request = { url: '/', method: 'GET', headers: { accept: '*/*', }, }; const response = { status: 200, headers: { 'cache-control': 'public, max-age=7234', }, }; const options = { shared: true, cacheHeuristic: 0.1, immutableMinTimeToLive: 24 * 3600 * 1000, // 24h ignoreCargoCult: false, }; ``` If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). `shared: true` is recommended for HTTP clients. `options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100\*0.1 = 10 days. `options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default. If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults. ### `storable()` Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response. ### `satisfiesWithoutRevalidation(newRequest)` This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request. If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`. If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`). ### `responseHeaders()` Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time. ```js cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); ``` ### `timeToLive()` Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh). After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`. `stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale. ### `toObject()`/`fromObject(json)` Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it. ### Refreshing stale cache (revalidation) When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth. The following methods help perform the update efficiently and correctly. #### `revalidationHeaders(newRequest)` Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is. Use this method when updating cache from the origin server. ```js updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); ``` #### `revalidatedPolicy(revalidationRequest, revalidationResponse)` Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: - `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. - `modified` — Boolean indicating whether the response body has changed. - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. This is also affected by `stale-if-error`. - If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource. ```js // When serving requests from cache: const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get( newRequest.url ); if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) { // Change the request to ask the origin server if the cached response can be used newRequest.headers = oldPolicy.revalidationHeaders(newRequest); // Send request to the origin server. The server may respond with status 304 const newResponse = await makeRequest(newRequest); // Create updated policy and combined response from the old and new data const { policy, modified } = oldPolicy.revalidatedPolicy( newRequest, newResponse ); const response = modified ? newResponse : oldResponse; // Update the cache with the newer/fresher response letsPretendThisIsSomeCache.set( newRequest.url, { policy, response }, policy.timeToLive() ); // And proceed returning cached response as usual response.headers = policy.responseHeaders(); return response; } ``` # Yo, FRESH ![satisfiesWithoutRevalidation](fresh.jpg) ## Used by - [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request) ([got](https://www.npmjs.com/package/got)), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/kornelski/http-cache-semantics/network/dependents) ## Implemented - `Cache-Control` response header with all the quirks. - `Expires` with check for bad clocks. - `Pragma` response header. - `Age` response header. - `Vary` response header. - Default cacheability of statuses and methods. - Requests for stale data. - Filtering of hop-by-hop headers. - Basic revalidation request - `stale-if-error` ## Unimplemented - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable) - Revalidation of multiple representations ### Trusting server `Date` Per the RFC, the cache should take into account the time between server-supplied `Date` and the time it received the response. The RFC-mandated behavior creates two problems: * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong). * Even reasonably correct clocks may be off by a couple of seconds, breaking `max-age=1` trick (which is useful for reverse proxies on high-traffic servers). Previous versions of this library had an option to ignore the server date if it was "too inaccurate". To support the `max-age=1` trick the library also has to ignore dates that pretty accurate. There's no point of having an option to trust dates that are only a bit inaccurate, so this library won't trust any server dates. `max-age` will be interpreted from the time the response has been received, not from when it has been sent. This will affect only [RFC 1149 networks](https://tools.ietf.org/html/rfc1149). # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # is-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/is-buffer/master.svg [travis-url]: https://travis-ci.org/feross/is-buffer [npm-image]: https://img.shields.io/npm/v/is-buffer.svg [npm-url]: https://npmjs.org/package/is-buffer [downloads-image]: https://img.shields.io/npm/dm/is-buffer.svg [downloads-url]: https://npmjs.org/package/is-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Determine if an object is a [`Buffer`](http://nodejs.org/api/buffer.html) (including the [browserify Buffer](https://github.com/feross/buffer)) [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/is-buffer.svg [saucelabs-url]: https://saucelabs.com/u/is-buffer ## Why not use `Buffer.isBuffer`? This module lets you check if an object is a `Buffer` without using `Buffer.isBuffer` (which includes the whole [buffer](https://github.com/feross/buffer) module in [browserify](http://browserify.org/)). It's future-proof and works in node too! ## install ```bash npm install is-buffer ``` ## usage ```js var isBuffer = require('is-buffer') isBuffer(new Buffer(4)) // true isBuffer(undefined) // false isBuffer(null) // false isBuffer('') // false isBuffer(true) // false isBuffer(false) // false isBuffer(0) // false isBuffer(1) // false isBuffer(1.0) // false isBuffer('string') // false isBuffer({}) // false isBuffer(function foo () {}) // false ``` ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # cbor Encode and parse data in the Concise Binary Object Representation (CBOR) data format ([RFC8949](https://www.rfc-editor.org/rfc/rfc8949.html)). ## Supported Node.js versions This project now only supports versions of Node that the Node team is [currently supporting](https://github.com/nodejs/Release#release-schedule). Ava's [support statement](https://github.com/avajs/ava/blob/main/docs/support-statement.md) is what we will be using as well. Currently, that means Node `10`+ is required. If you need to support an older version of Node (back to version 6), use cbor version 5.2.x, which will get nothing but security updates from here on out. ## Installation: ```bash $ npm install --save cbor ``` **NOTE** If you are going to use this on the web, use [cbor-web](../cbor-web) instead. If you need support for encoding and decoding BigDecimal fractions (tag 4) or BigFloats (tag 5), please see [cbor-bigdecimal](../cbor-bigdecimal). ## Documentation: See the full API [documentation](http://hildjj.github.io/node-cbor/). For a command-line interface, see [cbor-cli](../cbor-cli). Example: ```js const cbor = require('cbor') const assert = require('assert') let encoded = cbor.encode(true) // Returns <Buffer f5> cbor.decodeFirst(encoded, (error, obj) => { // If there was an error, error != null // obj is the unpacked object assert.ok(obj === true) }) // Use integers as keys? const m = new Map() m.set(1, 2) encoded = cbor.encode(m) // <Buffer a1 01 02> ``` Allows streaming as well: ```js const cbor = require('cbor') const fs = require('fs') const d = new cbor.Decoder() d.on('data', obj => { console.log(obj) }) const s = fs.createReadStream('foo') s.pipe(d) const d2 = new cbor.Decoder({input: '00', encoding: 'hex'}) d.on('data', obj => { console.log(obj) }) ``` There is also support for synchronous decodes: ```js try { console.log(cbor.decodeFirstSync('02')) // 2 console.log(cbor.decodeAllSync('0202')) // [2, 2] } catch (e) { // Throws on invalid input } ``` The sync encoding and decoding are exported as a [leveldb encoding](https://github.com/Level/levelup#custom_encodings), as `cbor.leveldb`. ## highWaterMark The synchronous routines for encoding and decoding will have problems with objects that are larger than 16kB, which the default buffer size for Node streams. There are a few ways to fix this: 1) pass in a `highWaterMark` option with the value of the largest buffer size you think you will need: ```js cbor.encodeOne(new ArrayBuffer(40000), {highWaterMark: 65535}) ``` 2) use stream mode. Catch the `data`, `finish`, and `error` events. Make sure to call `end()` when you're done. ```js const enc = new cbor.Encoder() enc.on('data', buf => /* Send the data somewhere */ null) enc.on('error', console.error) enc.on('finish', () => /* Tell the consumer we are finished */ null) enc.end(['foo', 1, false]) ``` 3) use `encodeAsync()`, which uses the approach from approach 2 to return a memory-inefficient promise for a Buffer. ## Supported types The following types are supported for encoding: * boolean * number (including -0, NaN, and ±Infinity) * string * Array, Set (encoded as Array) * Object (including null), Map * undefined * Buffer * Date, * RegExp * URL * TypedArrays, ArrayBuffer, DataView * Map, Set * BigInt Decoding supports the above types, including the following CBOR tag numbers: | Tag | Generated Type | |-----|---------------------| | 0 | Date | | 1 | Date | | 2 | BigInt | | 3 | BigInt | | 21 | Tagged, with toJSON | | 22 | Tagged, with toJSON | | 23 | Tagged, with toJSON | | 32 | URL | | 33 | Tagged | | 34 | Tagged | | 35 | RegExp | | 64 | Uint8Array | | 65 | Uint16Array | | 66 | Uint32Array | | 67 | BigUint64Array | | 68 | Uint8ClampedArray | | 69 | Uint16Array | | 70 | Uint32Array | | 71 | BigUint64Array | | 72 | Int8Array | | 73 | Int16Array | | 74 | Int32Array | | 75 | BigInt64Array | | 77 | Int16Array | | 78 | Int32Array | | 79 | BigInt64Array | | 81 | Float32Array | | 82 | Float64Array | | 85 | Float32Array | | 86 | Float64Array | | 258 | Set | ## Adding new Encoders There are several ways to add a new encoder: ### `encodeCBOR` method This is the easiest approach, if you can modify the class being encoded. Add an `encodeCBOR` method to your class, which takes a single parameter of the encoder currently being used. Your method should return `true` on success, else `false`. Your method may call `encoder.push(buffer)` or `encoder.pushAny(any)` as needed. For example: ```js class Foo { constructor() { this.one = 1 this.two = 2 } encodeCBOR(encoder) { const tagged = new Tagged(64000, [this.one, this.two]) return encoder.pushAny(tagged) } } ``` You can also modify an existing type by monkey-patching an `encodeCBOR` function onto its prototype, but this isn't recommended. ### `addSemanticType` Sometimes, you want to support an existing type without modification to that type. In this case, call `addSemanticType(type, encodeFunction)` on an existing `Encoder` instance. The `encodeFunction` takes an encoder and an object to encode, for example: ```js class Bar { constructor() { this.three = 3 } } const enc = new Encoder() enc.addSemanticType(Bar, (encoder, b) => { encoder.pushAny(b.three) }) ``` ## Adding new decoders Most of the time, you will want to add support for decoding a new tag type. If the Decoder class encounters a tag it doesn't support, it will generate a `Tagged` instance that you can handle or ignore as needed. To have a specific type generated instead, pass a `tags` option to the `Decoder`'s constructor, consisting of an object with tag number keys and function values. The function will be passed the decoded value associated with the tag, and should return the decoded value. For the `Foo` example above, this might look like: ```js const d = new Decoder({ tags: { 64000: val => { // Check val to make sure it's an Array as expected, etc. const foo = new Foo() ;[foo.one, foo.two] = val return foo }, }, }) ``` You can also replace the default decoders by passing in an appropriate tag function. For example: ```js cbor.decodeFirstSync(input, { tags: { // Replace the Tag 0 (RFC3339 Date/Time string) decoder. // See https://tc39.es/proposal-temporal/docs/ for the upcoming // Temporal built-in, which supports nanosecond time: 0: x => Temporal.Instant.from(x), }, }) ``` Developers ---------- The tests for this package use a set of test vectors from RFC 8949 appendix A by importing a machine readable version of them from https://github.com/cbor/test-vectors. For these tests to work, you will need to use the command `git submodule update --init` after cloning or pulling this code. See https://gist.github.com/gitaarik/8735255#file-git_submodules-md for more information. Get a list of build steps with `npm run`. I use `npm run dev`, which rebuilds, runs tests, and refreshes a browser window with coverage metrics every time I save a `.js` file. If you don't want to run the fuzz tests every time, set a `NO_GARBAGE` environment variable: ``` env NO_GARBAGE=1 npm run dev ``` [![Build Status](https://github.com/hildjj/node-cbor/workflows/Tests/badge.svg)](https://github.com/hildjj/node-cbor/actions?query=workflow%3ATests) [![Coverage Status](https://coveralls.io/repos/hildjj/node-cbor/badge.svg?branch=main)](https://coveralls.io/r/hildjj/node-cbor?branch=main) write-file-atomic ----------------- This is an extension for node's `fs.writeFile` that makes its operation atomic and allows you set ownership (uid/gid of the file). ### var writeFileAtomic = require('write-file-atomic')<br>writeFileAtomic(filename, data, [options], [callback]) * filename **String** * data **String** | **Buffer** * options **Object** | **String** * chown **Object** default, uid & gid of existing file, if any * uid **Number** * gid **Number** * encoding **String** | **Null** default = 'utf8' * fsync **Boolean** default = true * mode **Number** default, from existing file, if any * tmpfileCreated **Function** called when the tmpfile is created * callback **Function** Atomically and asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`. Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread. If writeFile completes successfully then, if passed the **chown** option it will change the ownership of the file. Finally it renames the file back to the filename you specified. If it encounters errors at any of these steps it will attempt to unlink the temporary file and then pass the error back to the caller. If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel. If provided, the **chown** option requires both **uid** and **gid** properties or else you'll get an error. If **chown** is not specified it will default to using the owner of the previous file. To prevent chown from being ran you can also pass `false`, in which case the file will be created with the current user's credentials. If **mode** is not specified, it will default to using the permissions from an existing file, if any. Expicitly setting this to `false` remove this default, resulting in a file created with the system default permissions. If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'. If the **fsync** option is **false**, writeFile will skip the final fsync call. If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created. Example: ```javascript writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) { if (err) throw err; console.log('It\'s saved!'); }); ``` This function also supports async/await: ```javascript (async () => { try { await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}); console.log('It\'s saved!'); } catch (err) { console.error(err); process.exit(1); } })(); ``` ### var writeFileAtomicSync = require('write-file-atomic').sync<br>writeFileAtomicSync(filename, data, [options]) The synchronous version of **writeFileAtomic**. # node-hid - Access USB HID devices from Node.js # [![npm](https://img.shields.io/npm/dm/node-hid.svg?maxAge=2592000)](http://npmjs.com/package/node-hid) [![build macos](https://github.com/node-hid/node-hid/workflows/macos/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Amacos) [![build windows](https://github.com/node-hid/node-hid/workflows/windows/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Awindows) [![build linux](https://github.com/node-hid/node-hid/workflows/linux/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Alinux) * [node-hid - Access USB HID devices from Node.js](#node-hid---access-usb-hid-devices-from-nodejs) * [Platform Support](#platform-support) * [Supported Platforms](#supported-platforms) * [Supported Node versions](#supported-node-versions) * [Supported Electron versions](#supported-electron-versions) * [Installation](#installation) * [Installation Special Cases](#installation-special-cases) * [Examples](#examples) * [Usage](#usage) * [List all HID devices connected](#list-all-hid-devices-connected) * [Cost of HID.devices() and <code>new HID.HID()</code> for detecting device plug/unplug](#cost-of-hiddevices-and-new-hidhid-for-detecting-device-plugunplug) * [Opening a device](#opening-a-device) * [Picking a device from the device list](#picking-a-device-from-the-device-list) * [Reading from a device](#reading-from-a-device) * [Writing to a device](#writing-to-a-device) * [Complete API](#complete-api) * [devices = HID.devices()](#devices--hiddevices) * [HID.setDriverType(type)](#hidsetdrivertypetype) * [device = new HID.HID(path)](#device--new-hidhidpath) * [device = new HID.HID(vid,pid)](#device--new-hidhidvidpid) * [device.on('data', function(data) {} )](#deviceondata-functiondata--) * [device.on('error, function(error) {} )](#deviceonerror-functionerror--) * [device.write(data)](#devicewritedata) * [device.close()](#deviceclose) * [device.pause()](#devicepause) * [device.resume()](#deviceresume) * [device.read(callback)](#devicereadcallback) * [device.readSync()](#devicereadsync) * [device.readTimeout(time_out)](#devicereadtimeouttime_out) * [device.sendFeatureReport(data)](#devicesendfeaturereportdata) * [device.getFeatureReport(report_id, report_length)](#devicegetfeaturereportreport_id-report_length) * [device.setNonBlocking(no_block)](#devicesetnonblockingno_block) * [General notes:](#general-notes) * [Thread safety, Worker threads, Context-aware modules](#thread-safety-worker-threads-context-aware-modules) * [Devices node-hid cannot read](#devices-node-hid-cannot-read) * [Mac notes](#mac-notes) * [Windows notes](#windows-notes) * [Xbox 360 Controller on Windows 10](#xbox-360-controller-on-windows-10) * [Linux notes](#linux-notes) * [udev device permissions](#udev-device-permissions) * [Selecting driver type](#selecting-driver-type) * [Compiling from source](#compiling-from-source) * [Linux (kernel 2.6 ) : (install examples shown for Debian/Ubuntu)](#linux-kernel-26--install-examples-shown-for-debianubuntu) * [FreeBSD](#freebsd) * [Mac OS X 10.8 ](#mac-os-x-108) * [Windows 7, 8, 10](#windows-7-8-10) * [Building node-hid from source, for your projects](#building-node-hid-from-source-for-your-projects) * [Build node-hid for <code>node-hid</code> development](#build-node-hid-for-node-hid-development) * [Building node-hid for cross-compiling](#building-node-hid-for-cross-compiling) * [Electron projects using node-hid](#electron-projects-using-node-hid) * [NW.js projects using node-hid](#nwjs-projects-using-node-hid) * [Support](#support) ## Platform Support `node-hid` supports Node.js v6 and upwards. For versions before that, you will need to build from source. The platforms, architectures and node versions `node-hid` supports are the following. In general we try to provide pre-built native library binaries for the most common platforms, Node and Electron versions. We strive to make `node-hid` cross-platform so there's a good chance any combination not listed here will compile and work. ### Supported Platforms ### - Windows x86 (32-bit) (¹) - Windows x64 (64-bit) - Mac OSX 10.9+ - Linux x64 (²) - Linux x86 (¹) - Linux ARM / Raspberry Pi (¹) - Linux MIPSel (¹) - Linux PPC64 (¹) ¹ prebuilt-binaries not provided for these platforms ² prebuilt binary built on Ubuntu 18.04 x64 ### Supported Node versions ### * Node v8 to * Node v16 ### Supported Electron versions ### * Electron v3 to * Electron v16 Future versions of Node or Electron should work, since `node-hid` is now based on NAPI. ## Installation For most "standard" use cases (macOS, Windows, Linux x86), `node-hid` will install like a standard npm package: ``` npm install node-hid ``` If you install globally, the test program `src/show-devices.js` is installed as `hid-showdevices`. On Linux you can use it to try the difference between `hidraw` and `libusb` driverTypes: ``` $ npm install -g node-hid $ hid-showdevices libusb $ hid-showdevices hidraw ``` ### Installation Special Cases We are using [prebuild](https://github.com/mafintosh/prebuild) to compile and post binaries of the library for most common use cases (Linux, MacOS, Windows on standard processor platforms). If a prebuild is not available, `node-hid` will work, but `npm install node-hid` will compile the binary when you install. For more details on compiler setup, see [Compling from source](#compiling-from-source) below. ## Examples In the `src/` directory, various JavaScript programs can be found that talk to specific devices in some way. Some interesting ones: - [`show-devices.js`](./src/show-devices.js) - display all HID devices in the system - [`test-ps3-rumbleled.js`](./src/test-ps3-rumbleled.js) - Read PS3 joystick and control its LED & rumblers - [`test-powermate.js`](./src/test-powermate.js) - Read Griffin PowerMate knob and change its LED - [`test-blink1.js`](./src/test-blink1.js) - Fade colors on blink(1) RGB LED - [`test-bigredbutton.js`](./src/test-bigredbutton.js) - Read Dreamcheeky Big Red Button - [`test-teensyrawhid.js`](./src/test-teensyrawhid.js) - Read/write Teensy running RawHID "Basic" Arduino sketch To try them out, run them with `node src/showdevices.js` from within the node-hid directory. ---- ## Usage ### List all HID devices connected ```js var HID = require('node-hid'); var devices = HID.devices(); ``` `devices` will contain an array of objects, one for each HID device available. Of particular interest are the `vendorId` and `productId`, as they uniquely identify a device, and the `path`, which is needed to open a particular device. Sample output: ```js HID.devices(); { vendorId: 10168, productId: 493, path: 'IOService:/AppleACPIPl...HIDDevice@14210000,0', serialNumber: '20002E8C', manufacturer: 'ThingM', product: 'blink(1) mk2', release: 2, interface: -1, usagePage: 65280, usage: 1 }, { vendorId: 1452, productId: 610, path: 'IOService:/AppleACPIPl...Keyboard@14400000,0', serialNumber: '', manufacturer: 'Apple Inc.', product: 'Apple Internal Keyboard / Trackpad', release: 549, interface: -1, usagePage: 1, usage: 6 }, <and more> ``` #### Cost of `HID.devices()` and `new HID.HID()` for detecting device plug/unplug Both `HID.devices()` and `new HID.HID()` are relatively costly, each causing a USB (and potentially Bluetooth) enumeration. This takes time and OS resources. Doing either can slow down the read/write that you do in parallel with a device, and cause other USB devices to slow down too. This is how USB works. If you are polling `HID.devices()` or doing repeated `new HID.HID(vid,pid)` to detect device plug / unplug, consider instead using [node-usb-detection](https://github.com/MadLittleMods/node-usb-detection). `node-usb-detection` uses OS-specific, non-bus enumeration ways to detect device plug / unplug. ### Opening a device Before a device can be read from or written to, it must be opened. The `path` can be determined by a prior HID.devices() call. Use either the `path` from the list returned by a prior call to `HID.devices()`: ```js var device = new HID.HID(path); ``` or open the first device matching a VID/PID pair: ```js var device = new HID.HID(vid,pid); ``` The `device` variable will contain a handle to the device. If an error occurs opening the device, an exception will be thrown. A `node-hid` device is an `EventEmitter`. While it shares some method names and usage patterns with `Readable` and `Writable` streams, it is not a stream and the semantics vary. For example, `device.write` does not take encoding or callback args and `device.pause` does not do the same thing as `readable.pause`. There is also no `pipe` method. ### Picking a device from the device list If you need to filter down the `HID.devices()` list, you can use standard Javascript array techniques: ```js var devices = HID.devices(); var deviceInfo = devices.find( function(d) { var isTeensy = d.vendorId===0x16C0 && d.productId===0x0486; return isTeensy && d.usagePage===0xFFAB && d.usage===0x200; }); if( deviceInfo ) { var device = new HID.HID( deviceInfo.path ); // ... use device } ``` ### Reading from a device To receive FEATURE reports, use `device.getFeatureReport()`. To receive INPUT reports, use `device.on("data",...)`. A `node-hid` device is an EventEmitter. Reading from a device is performed by registering a "data" event handler: ```js device.on("data", function(data) {}); ``` You can also listen for errors like this: ```js device.on("error", function(err) {}); ``` For FEATURE reports: ```js var buf = device.getFeatureReport(reportId, reportLength) ``` Notes: - Reads via `device.on("data")` are asynchronous - Reads via `device.getFeatureReport()` are synchronous - To remove an event handler, close the device with `device.close()` - When there is not yet a data handler or no data handler exists, data is not read at all -- there is no buffer. ### Writing to a device To send FEATURE reports, use `device.sendFeatureReport()`. To send OUTPUT reports, use `device.write()`. All writing is synchronous. The ReportId is the first byte of the array sent to `device.sendFeatureReport()` or `device.write()`, meaning the array should be one byte bigger than your report. If your device does NOT use numbered reports, set the first byte of the 0x00. ```js device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); ``` ```js device.sendFeatureReport( [0x01, 'c', 0, 0xff,0x33,0x00, 70,0, 0] ); ``` Notes: - You must send the exact number of bytes for your chosen OUTPUT or FEATURE report. - Both `device.write()` and `device.sendFeatureReport()` return number of bytes written + 1. - For devices using Report Ids, the first byte of the array to `write()` or `sendFeatureReport()` must be the Report Id. ## Complete API ### `devices = HID.devices()` - Return array listing all connected HID devices ### `HID.setDriverType(type)` - Linux only - Sets underlying HID driver type - `type` can be `"hidraw"` or `"libusb"`, defaults to `"hidraw"` ### `device = new HID.HID(path)` - Open a HID device at the specified platform-specific path ### `device = new HID.HID(vid,pid)` - Open first HID device with specific VendorId and ProductId ### `device.on('data', function(data) {} )` - `data` - Buffer - the data read from the device ### `device.on('error, function(error) {} )` - `error` - The error Object emitted ### `device.write(data)` - `data` - the data to be synchronously written to the device, first byte is Report Id or 0x00 if not using numbered reports. - Returns number of bytes actually written ### `device.close()` - Closes the device. Subsequent reads will raise an error. ### `device.pause()` - Pauses reading and the emission of `data` events. This means the underlying device is _silenced_ until resumption -- it is not like pausing a stream, where data continues to accumulate. ### `device.resume()` - This method will cause the HID device to resume emmitting `data` events. If no listeners are registered for the `data` event, data will be lost. - When a `data` event is registered for this HID device, this method will be automatically called. ### `device.read(callback)` - Low-level function call to initiate an asynchronous read from the device. - `callback` is of the form `callback(err, data)` ### `device.readSync()` - Return an array of numbers data. If an error occurs, an exception will be thrown. ### `device.readTimeout(time_out)` - `time_out` - timeout in milliseconds - Return an array of numbers data. If an error occurs, an exception will be thrown. ### `device.sendFeatureReport(data)` - `data` - data of HID feature report, with 0th byte being report_id (`[report_id,...]`) - Returns number of bytes actually written ### `device.getFeatureReport(report_id, report_length)` - `report_id` - HID feature report id to get - `report_length` - length of report ### `device.setNonBlocking(no_block)` - `no_block` - boolean. Set to `true` to enable non-blocking reads - exactly mirrors `hid_set_nonblocking()` in [`hidapi`](https://github.com/libusb/hidapi) ----- ## General notes: ### Thread safety, Worker threads, Context-aware modules In general `node-hid` is not thread-safe because the underlying C-library it wraps (`hidapi`) is not thread-safe. However, `node-hid` is now reporting as minimally Context Aware to allow use in Electron v9+. Until `node-hid` (or `hidapi`) is rewritten to be thread-safe, please constrain all accesses to it via a single thread. ### Devices `node-hid` cannot read The following devices are unavailable to `node-hid` because the OS owns them: - Keyboards - Mice - Barcode readers (in USB HID keyboard mode) - RFID scanners (in USB HID keyboard mode) - Postage Scales (in USB HID keyboard mode) Most OSes will prevent USB HID keyboards or mice, or devices that appear as a keyboard to the OS. This includes many RFID scanners, barcode readers, USB HID scales, and many other devices. This is a security precaution. Otherwise, it would be trivial to build keyloggers. Some keyboard-pretending devices like barcode or RFID readers can be configured to be in "HID data" mode or "Serial / UART" mode. If in "HID Data" mode then `node-hid` can access them, if in "Serial / UART" mode, you should use `node-serialport` instead. ## Mac notes See General notes above Keyboards ## Windows notes See General notes above about Keyboards ### Xbox 360 Controller on Windows 10 For reasons similar to mice & keyboards it appears you can't access this controller on Windows 10. ## Linux notes See General notes above about Keyboards ### udev device permissions Most Linux distros use `udev` to manage access to physical devices, and USB HID devices are normally owned by the `root` user. To allow non-root access, you must create a udev rule for the device, based on the devices vendorId and productId. This rule is a text file placed in `/etc/udev/rules.d`. For an example HID device (say a blink(1) light with vendorId = 0x27b8 and productId = 0x01ed, the rules file to support both `hidraw` and `libusb` would look like: ``` SUBSYSTEM=="input", GROUP="input", MODE="0666" SUBSYSTEM=="usb", ATTRS{idVendor}=="27b8", ATTRS{idProduct}=="01ed", MODE:="666", GROUP="plugdev" KERNEL=="hidraw*", ATTRS{idVendor}=="27b8", ATTRS{idProduct}=="01ed", MODE="0666", GROUP="plugdev" ``` Note that the values for idVendor and idProduct must be in hex and lower-case. Save this file as `/etc/udev/rules.d/51-blink1.rules`, unplug the HID device, and reload the rules with: ``` sudo udevadm control --reload-rules ``` For a complete example, see the [blink1 udev rules](https://github.com/todbot/blink1/blob/master/linux/51-blink1.rules). ### Selecting driver type By default as of `[email protected]`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `[email protected]`, the more older but less capable [libusb](http://libusb.info/) driver was used. With `hidraw` Linux apps can now see `usage` and `usagePage` attributes of devices. If you would still like to use the `libusb` driver, then you can do either: During runtime, you can use `HID.setDriverType('libusb')` immediately after require()-ing `node-hid`: ```js var HID = require('node-hid'); HID.setDriverType('libusb'); ``` If you must have the libusb version and cannot use `setDriverType()`, you can install older node-hid or build from source: ``` npm install [email protected] ``` or: ``` npm install node-hid --build-from-source --driver=libusb ``` ## Compiling from source To compile & develop locally or if `prebuild` cannot download a pre-built binary for you, you will need the following compiler tools and libraries: ### Linux (kernel 2.6+) : (install examples shown for Debian/Ubuntu) * Compilation tools: `apt install build-essential git pkg-config` * libudev-dev: `apt install libudev-dev` (Debian/Ubuntu) / `yum install libusbx-devel` (Fedora) * libusb-1.0-0 w/headers:`apt install libusb-1.0-0 libusb-1.0-0-dev` ### FreeBSD * Compilation tools: `pkg install git gcc gmake libiconv node npm` ### Mac OS X 10.8+ * [Xcode](https://itunes.apple.com/us/app/xcode/id497799835?mt=12) ### Windows 7, 8, 10 The below is slightly stale. The 2021 solution is to use the official NodeJs Windows installer and pick "install native module tools" * Visual C++ compiler and Python 2.7 * either: * `npm install --global windows-build-tools` * add `%USERPROFILE%\.windows-build-tools\python27` to `PATH`, like PowerShell: `$env:Path += ";$env:USERPROFILE\.windows-build-tools\python27"` * or: * [Python 2.7](https://www.python.org/downloads/windows/) * [Visual Studio Express 2013 for Desktop](https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2013-express) ### Building `node-hid` from source, for your projects ``` npm install node-hid --build-from-source ``` ### Build `node-hid` for `node-hid` development * check out a copy of this repo * change into its directory * update the submodules * build the node package For example: ``` git clone https://github.com/node-hid/node-hid.git cd node-hid # must change into node-hid directory npm install -g rimraf # just so it doesn't get 'clean'ed npm run prepublishOnly # get the needed hidapi submodule npm install --build-from-source # rebuilds the module with C code npm run showdevices # list connected HID devices node ./src/show-devices.js # same as above ``` You may see some warnings from the C compiler as it compiles [hidapi](https://github.com/libusb/hidapi) (the underlying C library `node-hid` uses). This is expected. For ease of development, there are also the scripts: ``` npm run gypclean # "node-gyp clean" clean gyp build directory npm run gypconfigure # "node-gyp configure" configure makefiles npm run gypbuild # "node-gyp build" build native code ``` ### Building `node-hid` for cross-compiling When cross-compiling you need to override `node-hid`'s normal behavior of using Linux `pkg-config` to determine CLFAGS and LDFLAGS for `libusb`. To do this, you can use the `node-gyp` variable `node_hid_no_pkg_config` and then invoke a `node-hid` rebuild with either: ``` node-gyp rebuild --node_hid_no_pkg_config=1 ``` or ``` npm gyprebuild --node_hid_no_pkg_config=1 ``` ## Electron projects using `node-hid` In your electron project, add `electron-rebuild` to your `devDependencies`. Then in your package.json `scripts` add: ``` "postinstall": "electron-rebuild" ``` This will cause `npm` to rebuild `node-hid` for the version of Node that is in Electron. If you get an error similar to `The module "HID.node" was compiled against a different version of Node.js` then `electron-rebuild` hasn't been run and Electron is trying to use `node-hid` compiled for Node.js and not for Electron. If using `node-hid` with `webpack` or similar bundler, you may need to exclude `node-hid` and other libraries with native code. In webpack, you say which `externals` you have in your `webpack-config.js`: ``` externals: { "node-hid": 'commonjs node-hid' } ``` Examples of `node-hid` in Electron: * [electron-hid-test](https://github.com/todbot/electron-hid-test) - Simple example of using `node-hid`, should track latest Electron release * [electron-hid-test-erb](https://github.com/todbot/electron-hid-test-erb) - Simple example of using `node-hid` using [electron-react-boilerplate](https://github.com/electron-react-boilerplate/electron-react-boilerplate/) * [electron-hid-toy](https://github.com/todbot/electron-hid-toy) - Simple example of using `node-hid`, showing packaging and signing * [Blink1Control2](https://github.com/todbot/Blink1Control2/) - a complete application, using webpack (e.g. see its [webpack-config.js](https://github.com/todbot/Blink1Control2/blob/master/webpack.config.js)) ## NW.js projects using `node-hid` Without knowing much about NW.js, a quick hacky solution that works is: ``` cd my-nwjs-app npm install node-hid --save npm install -g nw-gyp cd node_modules/node-hid nw-gyp rebuild --target=0.42.3 --arch=x64 // or whatever NW.js version you have cd ../.. nwjs . ``` ## Support Please use the [node-hid github issues page](https://github.com/node-hid/node-hid/issues) for support questions and issues. # is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) > Returns true if the value is a finite number. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-number ``` ## Why is this needed? In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: ```js console.log(+[]); //=> 0 console.log(+''); //=> 0 console.log(+' '); //=> 0 console.log(typeof NaN); //=> 'number' ``` This library offers a performant way to smooth out edge cases like these. ## Usage ```js const isNumber = require('is-number'); ``` See the [tests](./test.js) for more examples. ### true ```js isNumber(5e3); // true isNumber(0xff); // true isNumber(-1.1); // true isNumber(0); // true isNumber(1); // true isNumber(1.1); // true isNumber(10); // true isNumber(10.10); // true isNumber(100); // true isNumber('-1.1'); // true isNumber('0'); // true isNumber('012'); // true isNumber('0xff'); // true isNumber('1'); // true isNumber('1.1'); // true isNumber('10'); // true isNumber('10.10'); // true isNumber('100'); // true isNumber('5e3'); // true isNumber(parseInt('012')); // true isNumber(parseFloat('012')); // true ``` ### False Everything else is false, as you would expect: ```js isNumber(Infinity); // false isNumber(NaN); // false isNumber(null); // false isNumber(undefined); // false isNumber(''); // false isNumber(' '); // false isNumber('foo'); // false isNumber([1]); // false isNumber([]); // false isNumber(function () {}); // false isNumber({}); // false ``` ## Release history ### 7.0.0 * Refactor. Now uses `.isFinite` if it exists. * Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. ### 6.0.0 * Optimizations, thanks to @benaadams. ### 5.0.0 **Breaking changes** * removed support for `instanceof Number` and `instanceof String` ## Benchmarks As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. ``` # all v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) fastest is 'v7.0' # string v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) fastest is 'parseFloat,v7.0' # number v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) fastest is 'v6.0' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 49 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [charlike-old](https://github.com/charlike-old) | | 1 | [benaadams](https://github.com/benaadams) | | 1 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # make-error [![Package Version](https://badgen.net/npm/v/make-error)](https://npmjs.org/package/make-error) [![Build Status](https://travis-ci.org/JsCommunity/make-error.png?branch=master)](https://travis-ci.org/JsCommunity/make-error) [![PackagePhobia](https://badgen.net/packagephobia/install/make-error)](https://packagephobia.now.sh/result?p=make-error) [![Latest Commit](https://badgen.net/github/last-commit/JsCommunity/make-error)](https://github.com/JsCommunity/make-error/commits/master) > Make your own error types! ## Features - Compatible Node & browsers - `instanceof` support - `error.name` & `error.stack` support - compatible with [CSP](https://en.wikipedia.org/wiki/Content_Security_Policy) (i.e. no `eval()`) ## Installation ### Node & [Browserify](http://browserify.org/)/[Webpack](https://webpack.js.org/) Installation of the [npm package](https://npmjs.org/package/make-error): ``` > npm install --save make-error ``` Then require the package: ```javascript var makeError = require("make-error"); ``` ### Browser You can directly use the build provided at [unpkg.com](https://unpkg.com): ```html <script src="https://unpkg.com/make-error@1/dist/make-error.js"></script> ``` ## Usage ### Basic named error ```javascript var CustomError = makeError("CustomError"); // Parameters are forwarded to the super class (here Error). throw new CustomError("a message"); ``` ### Advanced error class ```javascript function CustomError(customValue) { CustomError.super.call(this, "custom error message"); this.customValue = customValue; } makeError(CustomError); // Feel free to extend the prototype. CustomError.prototype.myMethod = function CustomError$myMethod() { console.log("CustomError.myMethod (%s, %s)", this.code, this.message); }; //----- try { throw new CustomError(42); } catch (error) { error.myMethod(); } ``` ### Specialized error ```javascript var SpecializedError = makeError("SpecializedError", CustomError); throw new SpecializedError(42); ``` ### Inheritance > Best for ES2015+. ```javascript import { BaseError } from "make-error"; class CustomError extends BaseError { constructor() { super("custom error message"); } } ``` ## Related - [make-error-cause](https://www.npmjs.com/package/make-error-cause): Make your own error types, with a cause! ## Contributions Contributions are _very_ welcomed, either on the documentation or on the code. You may: - report any [issue](https://github.com/JsCommunity/make-error/issues) you've encountered; - fork and create a pull request. ## License ISC © [Julien Fontanet](http://julien.isonoe.net) # promisify-child-process [![CircleCI](https://circleci.com/gh/jcoreio/promisify-child-process.svg?style=svg)](https://circleci.com/gh/jcoreio/promisify-child-process) [![Coverage Status](https://codecov.io/gh/jcoreio/promisify-child-process/branch/master/graph/badge.svg)](https://codecov.io/gh/jcoreio/promisify-child-process) [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release) [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/) [![npm version](https://badge.fury.io/js/promisify-child-process.svg)](https://badge.fury.io/js/promisify-child-process) seriously like the best async child process library Based upon [`child-process-async`](https://github.com/itsjustcon/node-child-process-async), but more thorough, because that package doesn't seem very actively maintained. `promisify-child-process` provides a **drop-in replacement** for the original `child_process` functions, not just duplicate methods that return a `Promise`. So when you call `exec(...)` we still return a `ChildProcess` instance, just with `.then()`, `.catch()`, and `.finally()` added to make it promise-friendly. ## Install and Set-up ```sh npm install --save promisify-child-process ``` If you are using a old version of Node without built-in `Promise`s or `Object.create`, you will need to use polyfills (e.g. `@babel/polyfill`). ```js // OLD: const { exec, spawn, fork, execFile } = require('child_process') // NEW: const { exec, spawn, fork, execFile } = require('promisify-child-process') ``` ## Upgrading to v3 You must now pass `maxBuffer` or `encoding` to `spawn`/`fork` if you want to capture `stdout` or `stderr`. ## Resolution/Rejection The child process promise will only resolve if the process exits with a code of 0. If it exits with any other code, is killed by a signal, or emits an `'error'` event, the promise will reject. ## Capturing output `exec` and `execFile` capture `stdout` and `stderr` by default. But `spawn` and `fork` don't capture `stdout` and `stderr` unless you pass an `encoding` or `maxBuffer` option: ```js const { spawn } = require('promisify-child-process'); async function() { // captures output const { stdout, stderr } = await spawn('ls', [ '-al' ], {encoding: 'utf8'}); const { stdout, stderr } = await spawn('ls', [ '-al' ], {maxBuffer: 200 * 1024}); // BUG, DOESN'T CAPTURE OUTPUT: const { stdout, stderr } = await spawn('ls', [ '-al' ]); } ``` ## Additional properties on rejection errors If the child process promise rejects, the error may have the following additional properties: - `code` - the process' exit code (if it exited) - `signal` - the signal the process was killed with (if it was killed) - `stdout` - the captured `stdout` (if output capturing was enabled) - `stderr` - the captured `stderr` (if output capturing was enabled) ## Wrapper If for any reason you need to wrap a `ChildProcess` you didn't create, you can use the exported `promisifyChildProcess` function: ```js const { promisifyChildProcess } = require('promisify-child-process'); async function() { const { stdout, stderr } = await promisifyChildProcess( some3rdPartyFunctionThatReturnsChildProcess(), { encoding: 'utf8' } ) } ``` ## Examples ### `exec()` ```js async function() { const { stdout, stderr } = await exec('ls -al'); // OR: const child = exec('ls -al', {}); // do whatever you want with `child` here - it's a ChildProcess instance just // with promise-friendly `.then()` & `.catch()` functions added to it! child.stdin.write(...); child.stdout.pipe(...); child.stderr.on('data', (data) => ...); const { stdout, stderr } = await child; } ``` ### `spawn()` ```js async function() { const { stdout, stderr, code } = await spawn('ls', [ '-al' ], {encoding: 'utf8'}); // OR: const child = spawn('ls', [ '-al' ], {}); // do whatever you want with `child` here - it's a ChildProcess instance just // with promise-friendly `.then()` & `.catch()` functions added to it! child.stdin.write(...); child.stdout.pipe(...); child.stderr.on('data', (data) => ...); const { stdout, stderr, code } = await child; } ``` # run-parallel [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/run-parallel/master.svg [travis-url]: https://travis-ci.org/feross/run-parallel [npm-image]: https://img.shields.io/npm/v/run-parallel.svg [npm-url]: https://npmjs.org/package/run-parallel [downloads-image]: https://img.shields.io/npm/dm/run-parallel.svg [downloads-url]: https://npmjs.org/package/run-parallel [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Run an array of functions in parallel ![parallel](https://raw.githubusercontent.com/feross/run-parallel/master/img.png) [![Sauce Test Status](https://saucelabs.com/browser-matrix/run-parallel.svg)](https://saucelabs.com/u/run-parallel) ### install ``` npm install run-parallel ``` ### usage #### parallel(tasks, [callback]) Run the `tasks` array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main `callback` is immediately called with the value of the error. Once the `tasks` have completed, the results are passed to the final `callback` as an array. It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling the results. ##### arguments - `tasks` - An array or object containing functions to run. Each function is passed a `callback(err, result)` which it must call on completion with an error `err` (which can be `null`) and an optional `result` value. - `callback(err, results)` - An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. ##### example ```js var parallel = require('run-parallel') parallel([ function (callback) { setTimeout(function () { callback(null, 'one') }, 200) }, function (callback) { setTimeout(function () { callback(null, 'two') }, 100) } ], // optional callback function (err, results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }) ``` This module is basically equavalent to [`async.parallel`](https://github.com/caolan/async#paralleltasks-callback), but it's handy to just have the one function you need instead of the kitchen sink. Modularity! Especially handy if you're serving to the browser and need to reduce your javascript bundle size. Works great in the browser with [browserify](http://browserify.org/)! ### see also - [run-auto](https://github.com/feross/run-auto) - [run-parallel-limit](https://github.com/feross/run-parallel-limit) - [run-series](https://github.com/feross/run-series) - [run-waterfall](https://github.com/feross/run-waterfall) ### license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # mustache.js - Logic-less {{mustache}} templates with JavaScript > What could be more logical awesome than no logic at all? [![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) [mustache.js](http://github.com/janl/mustache.js) is a zero-dependency implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. [Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). ## Where to use mustache.js? You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [Node.js](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. mustache.js ships with support for the [CommonJS](http://www.commonjs.org/) module API, the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API (AMD) and [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). In addition to being a package to be used programmatically, you can use it as a [command line tool](#command-line-tool). And this will be your templates after you use Mustache: !['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif) ## Install You can get Mustache via [npm](http://npmjs.com). ```bash $ npm install mustache --save ``` ## Usage Below is a quick example how to use mustache.js: ```js var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); ``` In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. ## Templates A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below. There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them: #### Include Templates If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example: ```js // file: render.js function renderHello() { var template = document.getElementById('template').innerHTML; var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; } ``` ```html <html> <body onload="renderHello()"> <div id="target">Loading...</div> <script id="template" type="x-tmpl-mustache"> Hello {{ name }}! </script> <script src="https://unpkg.com/mustache@latest"></script> <script src="render.js"></script> </body> </html> ``` #### Load External Templates If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): ```js function renderHello() { fetch('template.mustache') .then((response) => response.text()) .then((template) => { var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; }); } ``` ### Variables The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`. If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information. View: ```json { "name": "Chris", "company": "<b>GitHub</b>" } ``` Template: ``` * {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}} {{=<% %>=}} * {{company}} <%={{ }}=%> ``` Output: ```html * Chris * * &lt;b&gt;GitHub&lt;/b&gt; * <b>GitHub</b> * <b>GitHub</b> * {{company}} ``` JavaScript's dot notation may be used to access keys that are properties of objects in a view. View: ```json { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" } ``` Template: ```html * {{name.first}} {{name.last}} * {{age}} ``` Output: ```html * Michael Jackson * RIP ``` ### Sections Sections render blocks of text zero or more times, depending on the value of the key in the current context. A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". The behavior of the section is determined by the value of the key. #### False Values or Empty Lists If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered. View: ```json { "person": false } ``` Template: ```html Shown. {{#person}} Never shown! {{/person}} ``` Output: ```html Shown. ``` #### Non-Empty Lists If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. View: ```json { "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] } ``` Template: ```html {{#stooges}} <b>{{name}}</b> {{/stooges}} ``` Output: ```html <b>Moe</b> <b>Larry</b> <b>Curly</b> ``` When looping over an array of strings, a `.` can be used to refer to the current item in the list. View: ```json { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] } ``` Template: ```html {{#musketeers}} * {{.}} {{/musketeers}} ``` Output: ```html * Athos * Aramis * Porthos * D'Artagnan ``` If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. View: ```js { "beatles": [ { "firstName": "John", "lastName": "Lennon" }, { "firstName": "Paul", "lastName": "McCartney" }, { "firstName": "George", "lastName": "Harrison" }, { "firstName": "Ringo", "lastName": "Starr" } ], "name": function () { return this.firstName + " " + this.lastName; } } ``` Template: ```html {{#beatles}} * {{name}} {{/beatles}} ``` Output: ```html * John Lennon * Paul McCartney * George Harrison * Ringo Starr ``` #### Functions If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. View: ```js { "name": "Tater", "bold": function () { return function (text, render) { return "<b>" + render(text) + "</b>"; } } } ``` Template: ```html {{#bold}}Hi {{name}}.{{/bold}} ``` Output: ```html <b>Hi Tater.</b> ``` ### Inverted Sections An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list. View: ```json { "repos": [] } ``` Template: ```html {{#repos}}<b>{{name}}</b>{{/repos}} {{^repos}}No repos :({{/repos}} ``` Output: ```html No repos :( ``` ### Comments Comments begin with a bang and are ignored. The following template: ```html <h1>Today{{! ignore me }}.</h1> ``` Will render as follows: ```html <h1>Today.</h1> ``` Comments may contain newlines. ### Partials Partials begin with a greater than sign, like {{> box}}. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. They also inherit the calling context. Whereas in ERB you may have this: ```html+erb <%= partial :next_more, :start => start, :size => size %> ``` Mustache requires only this: ```html {{> next_more}} ``` Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. For example, this template and partial: base.mustache: <h2>Names</h2> {{#names}} {{> user}} {{/names}} user.mustache: <strong>{{name}}</strong> Can be thought of as a single, expanded template: ```html <h2>Names</h2> {{#names}} <strong>{{name}}</strong> {{/names}} ``` In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. ```js Mustache.render(template, view, { user: userTemplate }); ``` ### Custom Delimiters Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates. #### Setting in JavaScript The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself: ```js var customTags = [ '<%', '%>' ]; ``` ##### Pass Value into Render Method ```js Mustache.render(template, view, {}, customTags); ``` ##### Override Tags Property ```js Mustache.tags = customTags; // Subsequent parse() and render() calls will use customTags ``` #### Setting in Templates Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. Consider the following contrived example: ```html+erb * {{ default_tags }} {{=<% %>=}} * <% erb_style_tags %> <%={{ }}=%> * {{ default_tags_again }} ``` Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." Custom delimiters may not contain whitespace or the equals sign. ## Pre-parsing and Caching Templates By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`. ```js Mustache.parse(template); // Then, sometime later. Mustache.render(template, view); ``` ## Command line tool mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind ```bash $ npm install -g mustache $ mustache dataView.json myTemplate.mustache > output.html ``` also supports stdin. ```bash $ cat dataView.json | mustache - myTemplate.mustache > output.html ``` or as a package.json `devDependency` in a build process maybe? ```bash $ npm install mustache --save-dev ``` ```json { "scripts": { "build": "mustache dataView.json myTemplate.mustache > public/output.html" } } ``` ```bash $ npm run build ``` The command line tool is basically a wrapper around `Mustache.render` so you get all the features. If your templates use partials you should pass paths to partials using `-p` flag: ```bash $ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache ``` ## Plugins for JavaScript Libraries mustache.js may be built specifically for several different client libraries, including the following: - [jQuery](http://jquery.com/) - [MooTools](http://mootools.net/) - [Dojo](http://www.dojotoolkit.org/) - [YUI](http://developer.yahoo.com/yui/) - [qooxdoo](http://qooxdoo.org/) These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: ```bash $ rake jquery $ rake mootools $ rake dojo $ rake yui3 $ rake qooxdoo ``` ## TypeScript Since the source code of this package is written in JavaScript, we follow the [TypeScript publishing docs](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) preferred approach by having type definitions available via [@types/mustache](https://www.npmjs.com/package/@types/mustache). ## Testing In order to run the tests you'll need to install [Node.js](http://nodejs.org/). You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root. ```bash $ git submodule init $ git submodule update ``` Install dependencies. ```bash $ npm install ``` Then run the tests. ```bash $ npm test ``` The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: 1. Create a template file named `mytest.mustache` in the `test/_files` directory. Replace `mytest` with the name of your test. 2. Create a corresponding view file named `mytest.js` in the same directory. This file should contain a JavaScript object literal enclosed in parentheses. See any of the other view files for an example. 3. Create a file with the expected output in `mytest.txt` in the same directory. Then, you can run the test with: ```bash $ TEST=mytest npm run test-render ``` ### Browser tests Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser: ```bash $ npm run test-browser-local ``` then point your browser to `http://localhost:8080/__zuul` ## Who uses mustache.js? An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js! ## Contributing mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero. ### Your First Contribution - review a [Pull Request](https://github.com/janl/mustache.js/pulls) - fix an [Issue](https://github.com/janl/mustache.js/issues) - update the [documentation](https://github.com/janl/mustache.js#usage) - make a website - write a tutorial ## Thanks mustache.js wouldn't kick ass if it weren't for these fine souls: * Chris Wanstrath / defunkt * Alexander Lang / langalex * Sebastian Cohnen / tisba * J Chris Anderson / jchris * Tom Robinson / tlrobinson * Aaron Quint / quirkey * Douglas Crockford * Nikita Vasilyev / NV * Elise Wood / glytch * Damien Mathieu / dmathieu * Jakub Kuźma / qoobaa * Will Leinweber / will * dpree * Jason Smith / jhs * Aaron Gibralter / agibralter * Ross Boucher / boucher * Matt Sanford / mzsanford * Ben Cherry / bcherry * Michael Jackson / mjackson * Phillip Johnsen / phillipj * David da Silva Contín / dasilvacontin bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> <h1 align="center">Picomatch</h1> <p align="center"> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/v/picomatch.svg" alt="version"> </a> <a href="https://github.com/micromatch/picomatch/actions?workflow=Tests"> <img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status"> </a> <a href="https://coveralls.io/github/micromatch/picomatch"> <img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status"> </a> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br> <em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em> </p> <br> <br> ## Why picomatch? * **Lightweight** - No dependencies * **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. * **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) * **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) * **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. * **Well tested** - Thousands of unit tests See the [library comparison](#library-comparisons) to other libraries. <br> <br> ## Table of Contents <details><summary> Click to expand </summary> - [Install](#install) - [Usage](#usage) - [API](#api) * [picomatch](#picomatch) * [.test](#test) * [.matchBase](#matchbase) * [.isMatch](#ismatch) * [.parse](#parse) * [.scan](#scan) * [.compileRe](#compilere) * [.makeRe](#makere) * [.toRegex](#toregex) - [Options](#options) * [Picomatch options](#picomatch-options) * [Scan Options](#scan-options) * [Options Examples](#options-examples) - [Globbing features](#globbing-features) * [Basic globbing](#basic-globbing) * [Advanced globbing](#advanced-globbing) * [Braces](#braces) * [Matching special characters as literals](#matching-special-characters-as-literals) - [Library Comparisons](#library-comparisons) - [Benchmarks](#benchmarks) - [Philosophies](#philosophies) - [About](#about) * [Author](#author) * [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ </details> <br> <br> ## Install Install with [npm](https://www.npmjs.com/): ```sh npm install --save picomatch ``` <br> ## Usage The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. ```js const pm = require('picomatch'); const isMatch = pm('*.js'); console.log(isMatch('abcd')); //=> false console.log(isMatch('a.js')); //=> true console.log(isMatch('a.md')); //=> false console.log(isMatch('a/b.js')); //=> false ``` <br> ## API ### [picomatch](lib/picomatch.js#L32) Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. **Params** * `globs` **{String|Array}**: One or more glob patterns. * `options` **{Object=}** * `returns` **{Function=}**: Returns a matcher function. **Example** ```js const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.test](lib/picomatch.js#L117) Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. **Params** * `input` **{String}**: String to test. * `regex` **{RegExp}** * `returns` **{Object}**: Returns an object with matching info. **Example** ```js const picomatch = require('picomatch'); // picomatch.test(input, regex[, options]); console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` ### [.matchBase](lib/picomatch.js#L161) Match the basename of a filepath. **Params** * `input` **{String}**: String to test. * `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). * `returns` **{Boolean}** **Example** ```js const picomatch = require('picomatch'); // picomatch.matchBase(input, glob[, options]); console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true ``` ### [.isMatch](lib/picomatch.js#L183) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * **{String|Array}**: str The string to test. * **{String|Array}**: patterns One or more glob patterns to use for matching. * **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const picomatch = require('picomatch'); // picomatch.isMatch(string, patterns[, options]); console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(picomatch.isMatch('a.a', 'b.*')); //=> false ``` ### [.parse](lib/picomatch.js#L199) Parse a glob pattern to create the source string for a regular expression. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. **Example** ```js const picomatch = require('picomatch'); const result = picomatch.parse(pattern[, options]); ``` ### [.scan](lib/picomatch.js#L231) Scan a glob pattern to separate the pattern into segments. **Params** * `input` **{String}**: Glob pattern to scan. * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const picomatch = require('picomatch'); // picomatch.scan(input[, options]); const result = picomatch.scan('!./foo/*.js'); console.log(result); { prefix: '!./', input: '!./foo/*.js', start: 3, base: 'foo', glob: '*.js', isBrace: false, isBracket: false, isGlob: true, isExtglob: false, isGlobstar: false, negated: true } ``` ### [.compileRe](lib/picomatch.js#L245) Compile a regular expression from the `state` object returned by the [parse()](#parse) method. **Params** * `state` **{Object}** * `options` **{Object}** * `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. * `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * `returns` **{RegExp}** ### [.makeRe](lib/picomatch.js#L286) Create a regular expression from a parsed glob pattern. **Params** * `state` **{String}**: The object returned from the `.parse` method. * `options` **{Object}** * `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const picomatch = require('picomatch'); const state = picomatch.parse('*.js'); // picomatch.compileRe(state[, options]); console.log(picomatch.compileRe(state)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` ### [.toRegex](lib/picomatch.js#L321) Create a regular expression from the given regex source string. **Params** * `source` **{String}**: Regular expression source string. * `options` **{Object}** * `returns` **{RegExp}** **Example** ```js const picomatch = require('picomatch'); // picomatch.toRegex(source[, options]); const { output } = picomatch.parse('*.js'); console.log(picomatch.toRegex(output)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` <br> ## Options ### Picomatch options The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | | `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. ### Scan Options In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | | `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | **Example** ```js const picomatch = require('picomatch'); const result = picomatch.scan('!./foo/*.js', { tokens: true }); console.log(result); // { // prefix: '!./', // input: '!./foo/*.js', // start: 3, // base: 'foo', // glob: '*.js', // isBrace: false, // isBracket: false, // isGlob: true, // isExtglob: false, // isGlobstar: false, // negated: true, // maxDepth: 2, // tokens: [ // { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, // { value: 'foo', depth: 1, isGlob: false }, // { value: '*.js', depth: 1, isGlob: true } // ], // slashes: [ 2, 6 ], // parts: [ 'foo', '*.js' ] // } ``` <br> ### Options Examples #### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a folder ```js const fill = require('fill-range'); const regex = pm.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex); //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` #### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')); //=> true ``` #### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onMatch }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` <br> <br> ## Globbing features * [Basic globbing](#basic-globbing) (Wildcard matching) * [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) ### Basic globbing | **Character** | **Description** | | --- | --- | | `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | | `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | | `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | | `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | #### Matching behavior vs. Bash Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: * Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. * Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. <br> ### Advanced globbing * [extglobs](#extglobs) * [POSIX brackets](#posix-brackets) * [Braces](#brace-expansion) #### Extglobs | **Pattern** | **Description** | | --- | --- | | `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | | `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | | `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | | `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | | `!(pattern)` | Match _anything but_ `pattern` | **Examples** ```js const pm = require('picomatch'); // *(pattern) matches ZERO or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // +(pattern) matches ONE or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // supports multiple extglobs console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false // supports nested extglobs console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true ``` #### POSIX brackets POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. **Enable POSIX bracket support** ```js console.log(pm.makeRe('[[:word:]]+', { posix: true })); //=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ ``` **Supported POSIX classes** The following named POSIX bracket expressions are supported: * `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` * `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. * `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. * `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. * `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. * `[:digit:]` - Numerical digits, equivalent to `[0-9]`. * `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. * `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. * `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. * `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. * `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. * `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. * `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. * `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. ### Braces Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. ### Matching special characters as literals If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: **Special Characters** Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. To match any of the following characters as literals: `$^*+?()[] Examples: ```js console.log(pm.makeRe('foo/bar \\(1\\)')); console.log(pm.makeRe('foo/bar \\(1\\)')); ``` <br> <br> ## Library Comparisons The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). | **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | | --- | --- | --- | --- | --- | --- | --- | --- | | Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | | Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | | Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | | Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | | Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | | Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | | Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | | File system operations | - | - | - | - | - | - | - | <br> <br> ## Benchmarks Performance comparison of picomatch and minimatch. ``` # .makeRe star picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) # .makeRe star; dot=true picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) # .makeRe globstar picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) # .makeRe globstars picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) # .makeRe with leading star picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) # .makeRe - basic braces picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) ``` <br> <br> ## Philosophies The goal of this library is to be blazing fast, without compromising on accuracy. **Accuracy** The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. **Performance** Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. <br> <br> ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # graceful-fs graceful-fs functions as a drop-in replacement for the fs module, making various improvements. The improvements are meant to normalize behavior across different platforms and environments, and to make filesystem access more resilient to errors. ## Improvements over [fs module](https://nodejs.org/api/fs.html) * Queues up `open` and `readdir` calls, and retries them once something closes if there is an EMFILE error from too many file descriptors. * fixes `lchmod` for Node versions prior to 0.6.2. * implements `fs.lutimes` if possible. Otherwise it becomes a noop. * ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or `lchown` if the user isn't root. * makes `lchmod` and `lchown` become noops, if not available. * retries reading a file if `read` results in EAGAIN error. On Windows, it retries renaming a file for up to one second if `EACCESS` or `EPERM` error occurs, likely because antivirus software has locked the directory. ## USAGE ```javascript // use just like fs var fs = require('graceful-fs') // now go and do stuff with it... fs.readFile('some-file-or-whatever', (err, data) => { // Do stuff here. }) ``` ## Sync methods This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync methods. If you use sync methods which open file descriptors then you are responsible for dealing with any errors. This is a known limitation, not a bug. ## Global Patching If you want to patch the global fs module (or any other fs-like module) you can do this: ```javascript // Make sure to read the caveat below. var realFs = require('fs') var gracefulFs = require('graceful-fs') gracefulFs.gracefulify(realFs) ``` This should only ever be done at the top-level application layer, in order to delay on EMFILE errors from any fs-using dependencies. You should **not** do this in a library, because it can cause unexpected delays in other parts of the program. ## Changes This module is fairly stable at this point, and used by a lot of things. That being said, because it implements a subtle behavior change in a core part of the node API, even modest changes can be extremely breaking, and the versioning is thus biased towards bumping the major when in doubt. The main change between major versions has been switching between providing a fully-patched `fs` module vs monkey-patching the node core builtin, and the approach by which a non-monkey-patched `fs` was created. The goal is to trade `EMFILE` errors for slower fs operations. So, if you try to open a zillion files, rather than crashing, `open` operations will be queued up and wait for something else to `close`. There are advantages to each approach. Monkey-patching the fs means that no `EMFILE` errors can possibly occur anywhere in your application, because everything is using the same core `fs` module, which is patched. However, it can also obviously cause undesirable side-effects, especially if the module is loaded multiple times. Implementing a separate-but-identical patched `fs` module is more surgical (and doesn't run the risk of patching multiple times), but also imposes the challenge of keeping in sync with the core module. The current approach loads the `fs` module, and then creates a lookalike object that has all the same methods, except a few that are patched. It is safe to use in all versions of Node from 0.8 through 7.0. ### v4 * Do not monkey-patch the fs module. This module may now be used as a drop-in dep, and users can opt into monkey-patching the fs builtin if their app requires it. ### v3 * Monkey-patch fs, because the eval approach no longer works on recent node. * fixed possible type-error throw if rename fails on windows * verify that we *never* get EMFILE errors * Ignore ENOSYS from chmod/chown * clarify that graceful-fs must be used as a drop-in ### v2.1.0 * Use eval rather than monkey-patching fs. * readdir: Always sort the results * win32: requeue a file if error has an OK status ### v2.0 * A return to monkey patching * wrap process.cwd ### v1.1 * wrap readFile * Wrap fs.writeFile. * readdir protection * Don't clobber the fs builtin * Handle fs.read EAGAIN errors by trying again * Expose the curOpen counter * No-op lchown/lchmod if not implemented * fs.rename patch only for win32 * Patch fs.rename to handle AV software on Windows * Close #4 Chown should not fail on einval or eperm if non-root * Fix isaacs/fstream#1 Only wrap fs one time * Fix #3 Start at 1024 max files, then back off on EMFILE * lutimes that doens't blow up on Linux * A full on-rewrite using a queue instead of just swallowing the EMFILE error * Wrap Read/Write streams as well ### 1.0 * Update engines for node 0.6 * Be lstat-graceful on Windows * first # chunkd > Get a chunk of an array based on the total number of chunks and current index ## Install ```sh yarn add [--dev] chunkd ``` ## Example ```js const chunkd = require("chunkd") chunkd([1, 2, 3, 4], 0, 3) // [1, 2] chunkd([1, 2, 3, 4], 1, 3) // [3] chunkd([1, 2, 3, 4], 2, 3) // [4] ``` # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # ansi-align > align-text with ANSI support for CLIs [![Build Status](https://travis-ci.org/nexdrew/ansi-align.svg?branch=master)](https://travis-ci.org/nexdrew/ansi-align) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/ansi-align/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/ansi-align?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) [![Greenkeeper badge](https://badges.greenkeeper.io/nexdrew/ansi-align.svg)](https://greenkeeper.io/) Easily center- or right- align a block of text, carefully ignoring ANSI escape codes. E.g. turn this: <img width="281" alt="ansi text block no alignment :(" src="https://cloud.githubusercontent.com/assets/1929625/14937509/7c3076dc-0ed7-11e6-8c16-4f6a4ccc8346.png"> Into this: <img width="278" alt="ansi text block center aligned!" src="https://cloud.githubusercontent.com/assets/1929625/14937510/7c3ca0b0-0ed7-11e6-8f0a-541ca39b6e0a.png"> ## Install ```sh npm install --save ansi-align ``` ```js var ansiAlign = require('ansi-align') ``` ## API ### `ansiAlign(text, [opts])` Align the given text per the line with the greatest [`string-width`](https://github.com/sindresorhus/string-width), returning a new string (or array). #### Arguments - `text`: required, string or array The text to align. If a string is given, it will be split using either the `opts.split` value or `'\n'` by default. If an array is given, a different array of modified strings will be returned. - `opts`: optional, object Options to change behavior, see below. #### Options - `opts.align`: string, default `'center'` The alignment mode. Use `'center'` for center-alignment, `'right'` for right-alignment, or `'left'` for left-alignment. Note that the given `text` is assumed to be left-aligned already, so specifying `align: 'left'` just returns the `text` as is (no-op). - `opts.split`: string or RegExp, default `'\n'` The separator to use when splitting the text. Only used if text is given as a string. - `opts.pad`: string, default `' '` The value used to left-pad (prepend to) lines of lesser width. Will be repeated as necessary to adjust alignment to the line with the greatest width. ### `ansiAlign.center(text)` Alias for `ansiAlign(text, { align: 'center' })`. ### `ansiAlign.right(text)` Alias for `ansiAlign(text, { align: 'right' })`. ### `ansiAlign.left(text)` Alias for `ansiAlign(text, { align: 'left' })`, which is a no-op. ## Similar Packages - [`center-align`](https://github.com/jonschlinkert/center-align): Very close to this package, except it doesn't support ANSI codes. - [`left-pad`](https://github.com/camwest/left-pad): Great for left-padding but does not support center alignment or ANSI codes. - Pretty much anything by the [chalk](https://github.com/chalk) team ## License ISC © Contributors # md5.js [![NPM Package](https://img.shields.io/npm/v/md5.js.svg?style=flat-square)](https://www.npmjs.org/package/md5.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/md5.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/md5.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/md5.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/md5.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `md5` on pure JavaScript. From [NIST SP 800-131A][1]: *md5 is no longer acceptable where collision resistance is required such as digital signatures.* ## Example ```js var MD5 = require('md5.js') console.log(new MD5().update('42').digest('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 var md5stream = new MD5() md5stream.end('42') console.log(md5stream.read().toString('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 ``` ## LICENSE [MIT](LICENSE) [1]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # cacheable-request > Wrap native HTTP requests with RFC compliant cache support [![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters. **Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. ## Features - Only stores cacheable responses as defined by RFC 7234 - Fresh cache entries are served directly from cache - Stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers - 304 responses from revalidation requests use cached body - Updates `Age` header on cached responses - Can completely bypass cache on a per request basis - In memory cache by default - Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters - Easily plug in your own or third-party storage adapters - If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) - Adds cache support to any existing HTTP code with minimal changes - Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance ## Install ```shell npm install cacheable-request ``` ## Usage ```js const http = require('http'); const CacheableRequest = require('cacheable-request'); // Then instead of const req = http.request('http://example.com', cb); req.end(); // You can do const cacheableRequest = new CacheableRequest(http.request); const cacheReq = cacheableRequest('http://example.com', cb); cacheReq.on('request', req => req.end()); // Future requests to 'example.com' will be returned from cache if still valid // You pass in any other http.request API compatible method to be wrapped with cache support: const cacheableRequest = new CacheableRequest(https.request); const cacheableRequest = new CacheableRequest(electron.net); ``` ## Storage Adapters `cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: ``` npm install @keyv/redis ``` And then you can pass `CacheableRequest` your connection string: ```js const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); ``` [View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. e.g The following are all valid storage adapters ```js const storageAdapter = new Map(); // or const storageAdapter = require('./my-storage-adapter'); // or const QuickLRU = require('quick-lru'); const storageAdapter = new QuickLRU({ maxSize: 1000 }); const cacheableRequest = new CacheableRequest(http.request, storageAdapter); ``` View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. ## API ### new cacheableRequest(request, [storageAdapter]) Returns the provided request function wrapped with cache support. #### request Type: `function` Request function to wrap with cache support. Should be [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) or a similar API compatible request function. #### storageAdapter Type: `Keyv storage adapter`<br> Default: `new Map()` A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. ### Instance #### cacheableRequest(opts, [cb]) Returns an event emitter. ##### opts Type: `object`, `string` - Any of the default request functions options. - Any [`http-cache-semantics`](https://github.com/kornelski/http-cache-semantics#constructor-options) options. - Any of the following: ###### opts.cache Type: `boolean`<br> Default: `true` If the cache should be used. Setting this to false will completely bypass the cache for the current request. ###### opts.strictTtl Type: `boolean`<br> Default: `false` If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. If set to `false` (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with `If-None-Match`/`If-Modified-Since` headers. ###### opts.maxTtl Type: `number`<br> Default: `undefined` Limits TTL. The `number` represents milliseconds. ###### opts.automaticFailover Type: `boolean`<br> Default: `false` When set to `true`, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed. ###### opts.forceRefresh Type: `boolean`<br> Default: `false` Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead. ##### cb Type: `function` The callback function which will receive the response as an argument. The response can be either a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) or a [responselike object](https://github.com/lukechilds/responselike). The response will also have a `fromCache` property set with a boolean value. ##### .on('request', request) `request` event to get the request object of the request. **Note:** This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the `request` event to end the request and handle any potential request errors. ##### .on('response', response) `response` event to get the response object from the HTTP request or cache. ##### .on('error', error) `error` event emitted in case of an error with the cache. Errors emitted here will be an instance of `CacheableRequest.RequestError` or `CacheableRequest.CacheError`. You will only ever receive a `RequestError` if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the `request` event. To properly handle all error scenarios you should use the following pattern: ```js cacheableRequest('example.com', cb) .on('error', err => { if (err instanceof CacheableRequest.CacheError) { handleCacheError(err); // Cache error } else if (err instanceof CacheableRequest.RequestError) { handleRequestError(err); // Request function thrown } }) .on('request', req => { req.on('error', handleRequestError); // Request error emitted req.end(); }); ``` **Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. ## License MIT © Luke Childs # v8-compile-cache-lib > Fork of [`v8-compile-cache`](https://www.npmjs.com/package/v8-compile-cache) exposed as an API for programmatic usage in other libraries and tools. --- [![Build status](https://img.shields.io/github/workflow/status/cspotcode/v8-compile-cache-lib/Continuous%20Integration)](https://github.com/cspotcode/v8-compile-cache-lib/actions?query=workflow%3A%22Continuous+Integration%22) `v8-compile-cache-lib` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache-lib ``` 2. Then, in your entry module add: ```js require('v8-compile-cache-lib').install(); ``` **`.install()` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache-lib`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. Cache directory is defined by environment variable `V8_COMPILE_CACHE_CACHE_DIR` or defaults to `<os.tmpdir()>/v8-compile-cache-<V8_VERSION>`. ## Internals Cache files are suffixed `.BLOB` and `.MAP` corresponding to the entry module that required `v8-compile-cache-lib`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/cspotcode/v8-compile-cache-lib/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * The original [`v8-compile-cache`](https://github.com/zertosh/v8-compile-cache) from which this library is forked. * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # npmlog The logger util that npm uses. This logger is very basic. It does the logging for npm. It supports custom levels and colored output. By default, logs are written to stderr. If you want to send log messages to outputs other than streams, then you can change the `log.stream` member, or you can just listen to the events that it emits, and do whatever you want with them. # Installation ```console npm install npmlog --save ``` # Basic Usage ```javascript var log = require('npmlog') // additional stuff ---------------------------+ // message ----------+ | // prefix ----+ | | // level -+ | | | // v v v v log.info('fyi', 'I have a kitty cat: %j', myKittyCat) ``` ## log.level * {String} The level to display logs at. Any logs at or above this level will be displayed. The special level `silent` will prevent anything from being displayed ever. ## log.record * {Array} An array of all the log messages that have been entered. ## log.maxRecordSize * {Number} The maximum number of records to keep. If log.record gets bigger than 10% over this value, then it is sliced down to 90% of this value. The reason for the 10% window is so that it doesn't have to resize a large array on every log entry. ## log.prefixStyle * {Object} A style object that specifies how prefixes are styled. (See below) ## log.headingStyle * {Object} A style object that specifies how the heading is styled. (See below) ## log.heading * {String} Default: "" If set, a heading that is printed at the start of every line. ## log.stream * {Stream} Default: `process.stderr` The stream where output is written. ## log.enableColor() Force colors to be used on all messages, regardless of the output stream. ## log.disableColor() Disable colors on all messages. ## log.enableProgress() Enable the display of log activity spinner and progress bar ## log.disableProgress() Disable the display of a progress bar ## log.enableUnicode() Force the unicode theme to be used for the progress bar. ## log.disableUnicode() Disable the use of unicode in the progress bar. ## log.setGaugeTemplate(template) Set a template for outputting the progress bar. See the [gauge documentation] for details. [gauge documentation]: https://npmjs.com/package/gauge ## log.setGaugeThemeset(themes) Select a themeset to pick themes from for the progress bar. See the [gauge documentation] for details. ## log.pause() Stop emitting messages to the stream, but do not drop them. ## log.resume() Emit all buffered messages that were written while paused. ## log.log(level, prefix, message, ...) * `level` {String} The level to emit the message at * `prefix` {String} A string prefix. Set to "" to skip. * `message...` Arguments to `util.format` Emit a log message at the specified level. ## log\[level](prefix, message, ...) For example, * log.silly(prefix, message, ...) * log.verbose(prefix, message, ...) * log.info(prefix, message, ...) * log.http(prefix, message, ...) * log.warn(prefix, message, ...) * log.error(prefix, message, ...) Like `log.log(level, prefix, message, ...)`. In this way, each level is given a shorthand, so you can do `log.info(prefix, message)`. ## log.addLevel(level, n, style, disp) * `level` {String} Level indicator * `n` {Number} The numeric level * `style` {Object} Object with fg, bg, inverse, etc. * `disp` {String} Optional replacement for `level` in the output. Sets up a new level with a shorthand function and so forth. Note that if the number is `Infinity`, then setting the level to that will cause all log messages to be suppressed. If the number is `-Infinity`, then the only way to show it is to enable all log messages. ## log.newItem(name, todo, weight) * `name` {String} Optional; progress item name. * `todo` {Number} Optional; total amount of work to be done. Default 0. * `weight` {Number} Optional; the weight of this item relative to others. Default 1. This adds a new `are-we-there-yet` item tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `Tracker` object. ## log.newStream(name, todo, weight) This adds a new `are-we-there-yet` stream tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerStream` object. ## log.newGroup(name, weight) This adds a new `are-we-there-yet` tracker group to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerGroup` object. # Events Events are all emitted with the message object. * `log` Emitted for all messages * `log.<level>` Emitted for all messages with the `<level>` level. * `<prefix>` Messages with prefixes also emit their prefix as an event. # Style Objects Style objects can have the following fields: * `fg` {String} Color for the foreground text * `bg` {String} Color for the background * `bold`, `inverse`, `underline` {Boolean} Set the associated property * `bell` {Boolean} Make a noise (This is pretty annoying, probably.) # Message Objects Every log event is emitted with a message object, and the `log.record` list contains all of them that have been created. They have the following fields: * `id` {Number} * `level` {String} * `prefix` {String} * `message` {String} Result of `util.format()` * `messageRaw` {Array} Arguments to `util.format()` # Blocking TTYs We use [`set-blocking`](https://npmjs.com/package/set-blocking) to set stderr and stdout blocking if they are tty's and have the setBlocking call. This is a work around for an issue in early versions of Node.js 6.x, which made stderr and stdout non-blocking on OSX. (They are always blocking Windows and were never blocking on Linux.) `npmlog` needs them to be blocking so that it can allow output to stdout and stderr to be interlaced. # Polyfill for `Object.setPrototypeOf` [![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. ## Usage: ``` $ npm install --save setprototypeof ``` ```javascript var setPrototypeOf = require('setprototypeof') var obj = {} setPrototypeOf(obj, { foo: function () { return 'bar' } }) obj.foo() // bar ``` TypeScript is also supported: ```typescript import setPrototypeOf from 'setprototypeof' ``` # fast-glob > It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js]. This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective. ## Table of Contents <details> <summary><strong>Details</strong></summary> * [Highlights](#highlights) * [Donation](#donation) * [Old and modern mode](#old-and-modern-mode) * [Pattern syntax](#pattern-syntax) * [Basic syntax](#basic-syntax) * [Advanced syntax](#advanced-syntax) * [Installation](#installation) * [API](#api) * [Asynchronous](#asynchronous) * [Synchronous](#synchronous) * [Stream](#stream) * [patterns](#patterns) * [[options]](#options) * [Helpers](#helpers) * [generateTasks](#generatetaskspatterns-options) * [isDynamicPattern](#isdynamicpatternpattern-options) * [escapePath](#escapepathpattern) * [Options](#options-3) * [Common](#common) * [concurrency](#concurrency) * [cwd](#cwd) * [deep](#deep) * [followSymbolicLinks](#followsymboliclinks) * [fs](#fs) * [ignore](#ignore) * [suppressErrors](#suppresserrors) * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink) * [Output control](#output-control) * [absolute](#absolute) * [markDirectories](#markdirectories) * [objectMode](#objectmode) * [onlyDirectories](#onlydirectories) * [onlyFiles](#onlyfiles) * [stats](#stats) * [unique](#unique) * [Matching control](#matching-control) * [braceExpansion](#braceexpansion) * [caseSensitiveMatch](#casesensitivematch) * [dot](#dot) * [extglob](#extglob) * [globstar](#globstar) * [baseNameMatch](#basenamematch) * [FAQ](#faq) * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) * [How to write patterns on Windows?](#how-to-write-patterns-on-windows) * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong) * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading) * [How to use UNC path?](#how-to-use-unc-path) * [Compatible with `node-glob`?](#compatible-with-node-glob) * [Benchmarks](#benchmarks) * [Server](#server) * [Nettop](#nettop) * [Changelog](#changelog) * [License](#license) </details> ## Highlights * Fast. Probably the fastest. * Supports multiple and negative patterns. * Synchronous, Promise and Stream API. * Object mode. Can return more than just strings. * Error-tolerant. ## Donation Do you like this project? Support it by donating, creating an issue or pull request. [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)][paypal_mrmlnc] ## Old and modern mode This package works in two modes, depending on the environment in which it is used. * **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*. * **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*. The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern]. ## Pattern syntax > :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq). > :book: This package uses a [`micromatch`][micromatch] as a library for pattern matching. ### Basic syntax * An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`). * A double star or globstar (`**`) — matches zero or more directories. * Question mark (`?`) – matches any single character except slashes (path separators). * Sequence (`[seq]`) — matches any character in sequence. > :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior]. Some examples: * `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension. * `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension. * `file-[01].js` — matches files: `file-0.js`, `file-1.js`. ### Advanced syntax * [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals. * [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`). * [Extended globs][micromatch_extglobs] (`?(pattern-list)`). * [Bash style brace expansions][micromatch_braces] (`{}`). * [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`). * [Regex groups][regular_expressions_brackets] (`(a|b)`). > :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing]. Some examples: * `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension. * `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`. * `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`. * `file-(1|2)` — matches files: `file-1.js`, `file-2.js`. ## Installation ```console npm install fast-glob ``` ## API ### Asynchronous ```js fg(patterns, [options]) ``` Returns a `Promise` with an array of matching entries. ```js const fg = require('fast-glob'); const entries = await fg(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Synchronous ```js fg.sync(patterns, [options]) ``` Returns an array of matching entries. ```js const fg = require('fast-glob'); const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Stream ```js fg.stream(patterns, [options]) ``` Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry. ```js const fg = require('fast-glob'); const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true }); for await (const entry of stream) { // .editorconfig // services/index.js } ``` #### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). > :1234: [Pattern syntax](#pattern-syntax) > > :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls. #### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. ### Helpers #### `generateTasks(patterns, [options])` Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory). ```js fg.generateTasks('*'); [{ base: '.', // Parent directory for all patterns inside this task dynamic: true, // Dynamic or static patterns are in this task patterns: ['*'], positive: ['*'], negative: [] }] ``` ##### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `isDynamicPattern(pattern, [options])` Returns `true` if the passed pattern is a dynamic pattern. > :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) ```js fg.isDynamicPattern('*'); // true fg.isDynamicPattern('abc'); // false ``` ##### pattern * Required: `true` * Type: `string` Any correct pattern. ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `escapePath(pattern)` Returns a path with escaped special characters (`*?|(){}[]`, `!` at the beginning of line, `@+!` before the opening parenthesis). ```js fg.escapePath('!abc'); // \\!abc fg.escapePath('C:/Program Files (x86)'); // C:/Program Files \\(x86\\) ``` ##### pattern * Required: `true` * Type: `string` Any string, for example, a path to a file. ## Options ### Common options #### concurrency * Type: `number` * Default: `os.cpus().length` Specifies the maximum number of concurrent requests from a reader to read directories. > :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`. #### cwd * Type: `string` * Default: `process.cwd()` The current working directory in which to search. #### deep * Type: `number` * Default: `Infinity` Specifies the maximum depth of a read directory relative to the start directory. For example, you have the following tree: ```js dir/ └── one/ // 1 └── two/ // 2 └── file.js // 3 ``` ```js // With base directory fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one'] fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two'] // With cwd option fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one'] fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two'] ``` > :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option. #### followSymbolicLinks * Type: `boolean` * Default: `true` Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns. > :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read. > :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it. #### fs * Type: `FileSystemAdapter` * Default: `fs.*` Custom implementation of methods for working with the file system. ```ts export interface FileSystemAdapter { lstat?: typeof fs.lstat; stat?: typeof fs.stat; lstatSync?: typeof fs.lstatSync; statSync?: typeof fs.statSync; readdir?: typeof fs.readdir; readdirSync?: typeof fs.readdirSync; } ``` #### ignore * Type: `string[]` * Default: `[]` An array of glob patterns to exclude matches. This is an alternative way to use negative patterns. ```js dir/ ├── package-lock.json └── package.json ``` ```js fg.sync(['*.json', '!package-lock.json']); // ['package.json'] fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json'] ``` #### suppressErrors * Type: `boolean` * Default: `false` By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error. > :book: Can be useful when the directory has entries with a special level of access. #### throwErrorOnBrokenSymbolicLink * Type: `boolean` * Default: `false` Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. > :book: This option has no effect on errors when reading the symbolic link directory. ### Output control #### absolute * Type: `boolean` * Default: `false` Return the absolute path for entries. ```js fg.sync('*.js', { absolute: false }); // ['index.js'] fg.sync('*.js', { absolute: true }); // ['/home/user/index.js'] ``` > :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`. #### markDirectories * Type: `boolean` * Default: `false` Mark the directory path with the final slash. ```js fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/'] ``` #### objectMode * Type: `boolean` * Default: `false` Returns objects (instead of strings) describing entries. ```js fg.sync('*', { objectMode: false }); // ['src/index.js'] fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }] ``` The object has the following fields: * name (`string`) — the last part of the path (basename) * path (`string`) — full path relative to the pattern base directory * dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent` > :book: An object is an internal representation of entry, so getting it does not affect performance. #### onlyDirectories * Type: `boolean` * Default: `false` Return only directories. ```js fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src'] fg.sync('*', { onlyDirectories: true }); // ['src'] ``` > :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`. #### onlyFiles * Type: `boolean` * Default: `true` Return only files. ```js fg.sync('*', { onlyFiles: false }); // ['index.js', 'src'] fg.sync('*', { onlyFiles: true }); // ['index.js'] ``` #### stats * Type: `boolean` * Default: `false` Enables an [object mode](#objectmode) with an additional field: * stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats` ```js fg.sync('*', { stats: false }); // ['src/index.js'] fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }] ``` > :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified. > > :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details. #### unique * Type: `boolean` * Default: `true` Ensures that the returned entries are unique. ```js fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json'] ``` If `true` and similar entries are found, the result is the first found. ### Matching control #### braceExpansion * Type: `boolean` * Default: `true` Enables Bash-like brace expansion. > :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces]. ```js dir/ ├── abd ├── acd └── a{b,c}d ``` ```js fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d'] fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd'] ``` #### caseSensitiveMatch * Type: `boolean` * Default: `true` Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files. ```js dir/ ├── file.txt └── File.txt ``` ```js fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt'] fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt'] ``` #### dot * Type: `boolean` * Default: `false` Allow patterns to match entries that begin with a period (`.`). > :book: Note that an explicit dot in a portion of the pattern will always match dot files. ```js dir/ ├── .editorconfig └── package.json ``` ```js fg.sync('*', { dot: false }); // ['package.json'] fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json'] ``` #### extglob * Type: `boolean` * Default: `true` Enables Bash-like `extglob` functionality. > :1234: [Syntax description][micromatch_extglobs]. ```js dir/ ├── README.md └── package.json ``` ```js fg.sync('*.+(json|md)', { extglob: false }); // [] fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json'] ``` #### globstar * Type: `boolean` * Default: `true` Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`. ```js dir/ └── a └── b ``` ```js fg.sync('**', { onlyFiles: false, globstar: false }); // ['a'] fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b'] ``` #### baseNameMatch * Type: `boolean` * Default: `false` If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes. ```js dir/ └── one/ └── file.md ``` ```js fg.sync('*.md', { baseNameMatch: false }); // [] fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md'] ``` ## FAQ ## What is a static or dynamic pattern? All patterns can be divided into two types: * **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system. * **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly. A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options: * The [`caseSensitiveMatch`](#casesensitivematch) option is disabled * `\\` (the escape character) * `*`, `?`, `!` (at the beginning of line) * `[…]` * `(…|…)` * `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option) * `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option) ## How to write patterns on Windows? Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format. **Bad** ```ts [ 'directory\\*', path.join(process.cwd(), '**') ] ``` **Good** ```ts [ 'directory/*', path.join(process.cwd(), '**').replace(/\\/g, '/') ] ``` > :book: Use the [`normalize-path`][npm_normalize_path] or the [`unixify`][npm_unixify] package to convert Windows-style path to a Unix-style path. Read more about [matching with backslashes][micromatch_backslashes]. ## Why are parentheses match wrong? ```js dir/ └── (special-*file).txt ``` ```js fg.sync(['(special-*file).txt']) // [] ``` Refers to Bash. You need to escape special characters: ```js fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt'] ``` Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. ## How to exclude directory from reading? You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below. ```js first/ ├── file.md └── second/ └── file.txt ``` If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`. ```js fg.sync(['**/*.md', '!**/second']); // ['first/file.md'] fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md'] ``` > :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results. You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances. ## How to use UNC path? You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax), but you can use them as [`cwd`](#cwd) directory. ```ts fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); ``` ## Compatible with `node-glob`? | node-glob | fast-glob | | :----------: | :-------: | | `cwd` | [`cwd`](#cwd) | | `root` | – | | `dot` | [`dot`](#dot) | | `nomount` | – | | `mark` | [`markDirectories`](#markdirectories) | | `nosort` | – | | `nounique` | [`unique`](#unique) | | `nobrace` | [`braceExpansion`](#braceexpansion) | | `noglobstar` | [`globstar`](#globstar) | | `noext` | [`extglob`](#extglob) | | `nocase` | [`caseSensitiveMatch`](#casesensitivematch) | | `matchBase` | [`baseNameMatch`](#basenamematch) | | `nodir` | [`onlyFiles`](#onlyfiles) | | `ignore` | [`ignore`](#ignore) | | `follow` | [`followSymbolicLinks`](#followsymboliclinks) | | `realpath` | – | | `absolute` | [`absolute`](#absolute) | ## Benchmarks ### Server Link: [Vultr Bare Metal][vultr_pricing_baremetal] * Processor: E3-1270v6 (8 CPU) * RAM: 32GB * Disk: SSD ([Intel DC S3520 SSDSC2BB240G7][intel_ssd]) You can see results [here][github_gist_benchmark_server] for latest release. ### Nettop Link: [Zotac bi323][zotac_bi323] * Processor: Intel N3150 (4 CPU) * RAM: 8GB * Disk: SSD ([Silicon Power SP060GBSS3S55S25][silicon_power_ssd]) You can see results [here][github_gist_benchmark_nettop] for latest release. ## Changelog See the [Releases section of our GitHub project][github_releases] for changelog for each release version. ## License This software is released under the terms of the MIT license. [bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace [github_gist_benchmark_nettop]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-nettop-product-txt [github_gist_benchmark_server]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-server-product-txt [github_releases]: https://github.com/mrmlnc/fast-glob/releases [glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming) [glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html [intel_ssd]: https://ark.intel.com/content/www/us/en/ark/products/93012/intel-ssd-dc-s3520-series-240gb-2-5in-sata-6gb-s-3d1-mlc.html [micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes [micromatch_braces]: https://github.com/micromatch/braces [micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing [micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs [micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes [micromatch]: https://github.com/micromatch/micromatch [node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent [node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats [node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams [node_js]: https://nodejs.org/en [nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode [npm_normalize_path]: https://www.npmjs.com/package/normalize-path [npm_unixify]: https://www.npmjs.com/package/unixify [paypal_mrmlnc]:https://paypal.me/mrmlnc [picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash [picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals [picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets [regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html [silicon_power_ssd]: https://www.silicon-power.com/web/product-1 [unc_path]: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc [vultr_pricing_baremetal]: https://www.vultr.com/pricing/baremetal [wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity [zotac_bi323]: https://www.zotac.com/ee/product/mini_pcs/zbox-bi323 # normalize-path [![NPM version](https://img.shields.io/npm/v/normalize-path.svg?style=flat)](https://www.npmjs.com/package/normalize-path) [![NPM monthly downloads](https://img.shields.io/npm/dm/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![NPM total downloads](https://img.shields.io/npm/dt/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/normalize-path.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/normalize-path) > Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save normalize-path ``` ## Usage ```js const normalize = require('normalize-path'); console.log(normalize('\\foo\\bar\\baz\\')); //=> '/foo/bar/baz' ``` **win32 namespaces** ```js console.log(normalize('\\\\?\\UNC\\Server01\\user\\docs\\Letter.txt')); //=> '//?/UNC/Server01/user/docs/Letter.txt' console.log(normalize('\\\\.\\CdRomX')); //=> '//./CdRomX' ``` **Consecutive slashes** Condenses multiple consecutive forward slashes (except for leading slashes in win32 namespaces) to a single slash. ```js console.log(normalize('.//foo//bar///////baz/')); //=> './foo/bar/baz' ``` ### Trailing slashes By default trailing slashes are removed. Pass `false` as the last argument to disable this behavior and _**keep** trailing slashes_: ```js console.log(normalize('foo\\bar\\baz\\', false)); //=> 'foo/bar/baz/' console.log(normalize('./foo/bar/baz/', false)); //=> './foo/bar/baz/' ``` ## Release history ### v3.0 No breaking changes in this release. * a check was added to ensure that [win32 namespaces](https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces) are handled properly by win32 `path.parse()` after a path has been normalized by this library. * a minor optimization was made to simplify how the trailing separator was handled ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects Other useful path-related libraries: * [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.") * [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.") * [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") * [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.") * [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.") * [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 35 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [phated](https://github.com/phated) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 19, 2018._ # tslib This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions. This library is primarily used by the `--importHelpers` flag in TypeScript. When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: ```ts var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; exports.x = {}; exports.y = __assign({}, exports.x); ``` will instead be emitted as something like the following: ```ts var tslib_1 = require("tslib"); exports.x = {}; exports.y = tslib_1.__assign({}, exports.x); ``` Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. # Installing For the latest stable version, run: ## npm ```sh # TypeScript 2.3.3 or later npm install tslib # TypeScript 2.3.2 or earlier npm install [email protected] ``` ## yarn ```sh # TypeScript 2.3.3 or later yarn add tslib # TypeScript 2.3.2 or earlier yarn add [email protected] ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install [email protected] ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install [email protected] ``` # Usage Set the `importHelpers` compiler option on the command line: ``` tsc --importHelpers file.ts ``` or in your tsconfig.json: ```json { "compilerOptions": { "importHelpers": true } } ``` #### For bower and JSPM users You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: ```json { "compilerOptions": { "module": "amd", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["bower_components/tslib/tslib.d.ts"] } } } ``` For JSPM users: ```json { "compilerOptions": { "module": "system", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["jspm_packages/npm/tslib@1.[version].0/tslib.d.ts"] } } } ``` # Contribute There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. * [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). * Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). # Documentation * [Quick tutorial](http://www.typescriptlang.org/Tutorial) * [Programming handbook](http://www.typescriptlang.org/Handbook) * [Homepage](http://www.typescriptlang.org/) # Tools ## clang-format The clang-format checking tools is designed to check changed lines of code compared to given git-refs. ## Migration Script The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. ### How To Use To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. ``` npm install node-addon-api ``` Then run the script passing your project directory ``` node ./node_modules/node-addon-api/tools/conversion.js ./ ``` After finish, recompile and debug things that are missed by the script. ### Quick Fixes Here is the list of things that can be fixed easily. 1. Change your methods' return value to void if it doesn't return value to JavaScript. 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); ### Major Reconstructions The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as ``` [ClassName](const Napi::CallbackInfo& info); ``` and define it as ``` [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ ... } ``` This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 2. Move your original constructor code into the new constructor. Delete your original constructor. 3. In your class initialization function, associate native methods in the following way. ``` Napi::FunctionReference constructor; void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { Napi::HandleScope scope(env); Napi::Function ctor = DefineClass(env, "Canvas", { InstanceMethod<&[ClassName]::Func1>("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. TweetNaCl.js ============ Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) to JavaScript for modern browsers and Node.js. Public domain. [![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) ](https://travis-ci.org/dchest/tweetnacl-js) Demo: <https://dchest.github.io/tweetnacl-js/> Documentation ============= * [Overview](#overview) * [Audits](#audits) * [Installation](#installation) * [Examples](#examples) * [Usage](#usage) * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) * [Scalar multiplication](#scalar-multiplication) * [Signatures](#signatures) * [Hashing](#hashing) * [Random bytes generation](#random-bytes-generation) * [Constant-time comparison](#constant-time-comparison) * [System requirements](#system-requirements) * [Development and testing](#development-and-testing) * [Benchmarks](#benchmarks) * [Contributors](#contributors) * [Who uses it](#who-uses-it) Overview -------- The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it. There are two versions, you can use either of them: * `nacl.js` is the port of TweetNaCl with minimum differences from the original + high-level API. * `nacl-fast.js` is like `nacl.js`, but with some functions replaced with faster versions. (Used by default when importing NPM package.) Audits ------ TweetNaCl.js has been audited by [Cure53](https://cure53.de/) in January-February 2017 (audit was sponsored by [Deletype](https://deletype.com)): > The overall outcome of this audit signals a particularly positive assessment > for TweetNaCl-js, as the testing team was unable to find any security > problems in the library. It has to be noted that this is an exceptionally > rare result of a source code audit for any project and must be seen as a true > testament to a development proceeding with security at its core. > > To reiterate, the TweetNaCl-js project, the source code was found to be > bug-free at this point. > > [...] > > In sum, the testing team is happy to recommend the TweetNaCl-js project as > likely one of the safer and more secure cryptographic tools among its > competition. [Read full audit report](https://cure53.de/tweetnacl.pdf) Installation ------------ You can install TweetNaCl.js via a package manager: [Yarn](https://yarnpkg.com/): $ yarn add tweetnacl [NPM](https://www.npmjs.org/): $ npm install tweetnacl or [download source code](https://github.com/dchest/tweetnacl-js/releases). Examples -------- You can find usage examples in our [wiki](https://github.com/dchest/tweetnacl-js/wiki/Examples). Usage ----- All API functions accept and return bytes as `Uint8Array`s. If you need to encode or decode strings, use functions from <https://github.com/dchest/tweetnacl-util-js> or one of the more robust codec packages. In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to convert them manually; make sure to convert using copying: `Buffer.from(array)` (or `new Buffer(array)` in Node.js v4 or earlier), instead of sharing: `Buffer.from(array.buffer)` (or `new Buffer(array.buffer)` Node 4 or earlier), because some functions return subarrays of their buffers. ### Public-key authenticated encryption (box) Implements *x25519-xsalsa20-poly1305*. #### nacl.box.keyPair() Generates a new random key pair for box and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 32-byte secret key } #### nacl.box.keyPair.fromSecretKey(secretKey) Returns a key pair for box with public key corresponding to the given secret key. #### nacl.box(message, nonce, theirPublicKey, mySecretKey) Encrypts and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair. Returns an encrypted and authenticated message, which is `nacl.box.overheadLength` longer than the original message. #### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce. Returns the original message, or `null` if authentication fails. #### nacl.box.before(theirPublicKey, mySecretKey) Returns a precomputed shared key which can be used in `nacl.box.after` and `nacl.box.open.after`. #### nacl.box.after(message, nonce, sharedKey) Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.open.after(box, nonce, sharedKey) Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. #### Constants ##### nacl.box.publicKeyLength = 32 Length of public key in bytes. ##### nacl.box.secretKeyLength = 32 Length of secret key in bytes. ##### nacl.box.sharedKeyLength = 32 Length of precomputed shared key in bytes. ##### nacl.box.nonceLength = 24 Length of nonce in bytes. ##### nacl.box.overheadLength = 16 Length of overhead added to box compared to original message. ### Secret-key authenticated encryption (secretbox) Implements *xsalsa20-poly1305*. #### nacl.secretbox(message, nonce, key) Encrypts and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key. Returns an encrypted and authenticated message, which is `nacl.secretbox.overheadLength` longer than the original message. #### nacl.secretbox.open(box, nonce, key) Authenticates and decrypts the given secret box using the key and the nonce. Returns the original message, or `null` if authentication fails. #### Constants ##### nacl.secretbox.keyLength = 32 Length of key in bytes. ##### nacl.secretbox.nonceLength = 24 Length of nonce in bytes. ##### nacl.secretbox.overheadLength = 16 Length of overhead added to secret box compared to original message. ### Scalar multiplication Implements *x25519*. #### nacl.scalarMult(n, p) Multiplies an integer `n` by a group element `p` and returns the resulting group element. #### nacl.scalarMult.base(n) Multiplies an integer `n` by a standard group element and returns the resulting group element. #### Constants ##### nacl.scalarMult.scalarLength = 32 Length of scalar in bytes. ##### nacl.scalarMult.groupElementLength = 32 Length of group element in bytes. ### Signatures Implements [ed25519](http://ed25519.cr.yp.to). #### nacl.sign.keyPair() Generates new random key pair for signing and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 64-byte secret key } #### nacl.sign.keyPair.fromSecretKey(secretKey) Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by `nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. #### nacl.sign.keyPair.fromSeed(seed) Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use `nacl.sign.keyPair` to generate a new key pair from a random seed. #### nacl.sign(message, secretKey) Signs the message using the secret key and returns a signed message. #### nacl.sign.open(signedMessage, publicKey) Verifies the signed message and returns the message without signature. Returns `null` if verification failed. #### nacl.sign.detached(message, secretKey) Signs the message using the secret key and returns a signature. #### nacl.sign.detached.verify(message, signature, publicKey) Verifies the signature for the message and returns `true` if verification succeeded or `false` if it failed. #### Constants ##### nacl.sign.publicKeyLength = 32 Length of signing public key in bytes. ##### nacl.sign.secretKeyLength = 64 Length of signing secret key in bytes. ##### nacl.sign.seedLength = 32 Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. ##### nacl.sign.signatureLength = 64 Length of signature in bytes. ### Hashing Implements *SHA-512*. #### nacl.hash(message) Returns SHA-512 hash of the message. #### Constants ##### nacl.hash.hashLength = 64 Length of hash in bytes. ### Random bytes generation #### nacl.randomBytes(length) Returns a `Uint8Array` of the given length containing random bytes of cryptographic quality. **Implementation note** TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on: * `window.crypto.getRandomValues` (WebCrypto standard) * `window.msCrypto.getRandomValues` (Internet Explorer 11) * `crypto.randomBytes` (Node.js) If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception: * `nacl.randomBytes` * `nacl.box.keyPair` * `nacl.sign.keyPair` Other functions are deterministic and will continue working. If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not `Math.random`!), and you know what you are doing, you can plug it into TweetNaCl.js like this: nacl.setPRNG(function(x, n) { // ... copy n random bytes into x ... }); Note that `nacl.setPRNG` *completely replaces* internal random byte generator with the one provided. ### Constant-time comparison #### nacl.verify(x, y) Compares `x` and `y` in constant time and returns `true` if their lengths are non-zero and equal, and their contents are equal. Returns `false` if either of the arguments has zero length, or arguments have different lengths, or their contents differ. System requirements ------------------- TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of: * Chrome * Firefox * Safari (Mac, iOS) * Internet Explorer 11 Other systems: * Node.js Development and testing ------------------------ Install NPM modules needed for development: $ npm install To build minified versions: $ npm run build Tests use minified version, so make sure to rebuild it every time you change `nacl.js` or `nacl-fast.js`. ### Testing To run tests in Node.js: $ npm run test-node By default all tests described here work on `nacl.min.js`. To test other versions, set environment variable `NACL_SRC` to the file name you want to test. For example, the following command will test fast minified version: $ NACL_SRC=nacl-fast.min.js npm run test-node To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version: $ npm run test-node-all To prepare tests for browsers: $ npm run build-test-browser and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to run them. To run tests in both Node and Electron: $ npm test ### Benchmarking To run benchmarks in Node.js: $ npm run bench $ NACL_SRC=nacl-fast.min.js npm run bench To run benchmarks in a browser, open `test/benchmark/bench.html` (or `test/benchmark/bench-fast.html`). Benchmarks ---------- For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android: | | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | | ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| | salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | | poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | | hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | | secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | | box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | | scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | | sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | | sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | (You can run benchmarks on your devices by clicking on the links at the bottom of the [home page](https://tweetnacl.js.org)). In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 200 and verify 100 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications. Contributors ------------ See AUTHORS.md file. Third-party libraries based on TweetNaCl.js ------------------------------------------- * [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation * [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption * [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) * [tweetnacl-sealed-box](https://github.com/whs/tweetnacl-sealed-box) — implementation of [`sealed boxes`](https://download.libsodium.org/doc/public-key_cryptography/sealed_boxes.html) * [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules Who uses it ----------- Some notable users of TweetNaCl.js: * [GitHub](https://github.com) * [MEGA](https://github.com/meganz/webclient) * [Stellar](https://www.stellar.org/) * [miniLock](https://github.com/kaepora/miniLock) # Node Port Check Check if a port is in use. Simple as that! ``` npm install node-port-check --save ``` # Update 2.0.1 : ---------------- - Cleanup: source and test files can be found on github - Cleanup: source and test files have been removed from the npm package 2.0.0 : ---------------- - As of 2.0 this package has been rewritten to use Promises. - These 3 promises are all there is to it: getFreePorts, isFreePort, nextAvailable . - Let {getFreePorts, isFreePort, nextAvailable} = require('node-port-check'); - Read the examples below to see how to use them. # Options **Options** | **Default Values** | **Returns** ------- | -------------- | ----------- isFreePort | (port: number = 80, host: string = '0.0.0.0') | Promise\<[port, host, status]\> getFreePorts | (howMany: number = 1, host: string = "0.0.0.0", freePorts: number[] = []) | Promise\<port[]\> nextAvailable | (port: number = 80, host: string = '0.0.0.0') | Promise\<number\> # Demos ### Example 1 - Simple ```javascript /** * Demo use case: * We'll bind ports 3010 and 3011 with mockServer * It will check the availability for ports 3010, 3011 and 3012 * The returning port will be 3012 ( assuming you don't have that port bound by another application * or else a higher port will be returned ) * * #1 - this lines won't exist in your code, their purpose it's just for testing */ let mockServer = require('./mockServer.js'); // #1 mockServer(3010); // #1 mockServer(3011); // #1 /** * EXAMPLE 1 */ /** * Returns the current port if available or the next one available by incrementing the port * @param {number} port * @param {string} host * @returns {Promise<number>} */ let {nextAvailable} = require('node-port-check'); nextAvailable(3010, '0.0.0.0').then((nextAvailablePort) => { console.log('Available port:', nextAvailablePort); process.exit(0); }); ``` **Output:** ``` Mock Server started on port 3010 Mock Server started on port 3011 Available port: 3012 ``` ### Example 2 - Multiple Ports ```javascript /** * Demo use case: * We'll bind ports 3010, 4500 and 9921 with mockServer * Since we have maxRetries = 0 now in 'yourConfig' no incrementation will be done ( see example 3 for multiple ports and maxRetries > 0 ) * the returning port will be the first encountered free port, that is 5195 * ( assuming you don't have that port bound by another application ) * */ /** * EXAMPLE 2 */ /** * Get a number of guaranteed free ports available for a host * @param {number} howMany * @param {string} host * @param {number[]} freePorts * @returns {Promise<number[]>} */ let {getFreePorts} = require('node-port-check'); getFreePorts(10, '0.0.0.0').then((freePortsList) => { console.log('Free ports:', freePortsList); process.exit(0); }); ``` **Output:** ``` Free ports: [ 5187, 15281, 18800, 26123, 32221, 36763, 45031, 53605, 61096, 63011 ] ``` ### Example 3 - Multiple Ports - Part 2 ```javascript /** * Demo use case: * These demo will generate 10 ports. * If you use the third parameter the returned free ports will contain the reserved list of ports. * * NOTE: When you reserve ports, "free ports" is not valid anymore because * the reserved ports won't be checked if they are free or in use, * only the ports that ARE NOT in your reserved list are the free ports. */ /** * EXAMPLE 3 */ /** * Get a number of guaranteed free ports available for a host * @param {number} howMany * @param {string} host * @param {number[]} freePorts * @returns {Promise<number[]>} */ let {getFreePorts} = require('node-port-check'); /** * Use the third parameter to reserve your port. */ getFreePorts(10, '0.0.0.0', [3000, 3001, 3002, 3003, 3009]).then((freePortsList) => { console.log('Free ports:', freePortsList); process.exit(0); }); ``` **Output:** ``` Free ports: [ 3000, 3001, 3002, 3003, 3009, 8185, 9240, 10462, 35187, 47349 ] ``` ### Example 4 - Check for a free port ```javascript /** * Demo use case: * We'll bind ports 3010, 4500 and 9921 with mockServer * We want 10 free ports and we want to reserve the ports 2018, 3010, 4500 and 9921 * This example will show you how to check if your ports are in use. * * NOTE: When you reserve ports, "free ports" is not valid anymore because * the reserved ports won't be checked if they are free or in use, * only the ports that ARE NOT in your reserved list are the free ports. */ /** * EXAMPLE 4 */ let mockServer = require('./mockServer.js'); // #4 mockServer(3010); // #4 mockServer(4500); // #4 mockServer(9921); // #4 /** * Get a number of guaranteed free ports available for a host * @param {number} howMany * @param {string} host * @param {number[]} freePorts * @returns {Promise<number[]>} */ let {getFreePorts, isFreePort} = require('node-port-check'); /** * Use the third parameter to reserve your port. */ getFreePorts(10, '0.0.0.0', [2018, 3010, 4500, 9921]).then((freePortsList) => { console.log('Free ports:', freePortsList); let checkPorts = freePortsList.map(item => isFreePort(item)); Promise .all(checkPorts) .then(list => { list.forEach(portStatus => { let port = portStatus[0]; let host = portStatus[1]; let status = portStatus[2]; console.log('Status ' + (status ? 'available' : 'unavailable') + ':', port, host, status); }); process.exit(0); }); }); ``` **Output:** ``` Mock Server started on port 3010 Mock Server started on port 4500 Mock Server started on port 9921 Free ports: [ 2018, 3010, 4500, 9921, 3985, 5890, 15367, 19661, 22715, 36543 ] Status available: 2018 0.0.0.0 true Status unavailable: 3010 0.0.0.0 false Status unavailable: 4500 0.0.0.0 false Status unavailable: 9921 0.0.0.0 false Status available: 3985 0.0.0.0 true Status available: 5890 0.0.0.0 true Status available: 15367 0.0.0.0 true Status available: 19661 0.0.0.0 true Status available: 22715 0.0.0.0 true Status available: 36543 0.0.0.0 true ``` # `create-require` [![npm version][npm-version-src]][npm-version-href] [![npm downloads][npm-downloads-src]][npm-downloads-href] [![Github Actions][github-actions-src]][github-actions-href] [![Codecov][codecov-src]][codecov-href] Polyfill for Node.js [`module.createRequire`](https://nodejs.org/api/modules.html#modules_module_createrequire_filename) (<= v12.2.0) ## Install ```sh yarn add create-require npm install create-require ``` ## Usage ```ts function createRequire (filename: string | URL): NodeRequire; ``` ```js const createRequire = require('create-require') const myRequire = createRequire('path/to/test.js') const myModule = myRequire('./test-sibling-module') ``` ## License [MIT](./LICENSE) <!-- Badges --> [npm-version-src]: https://img.shields.io/npm/v/create-require?style=flat-square [npm-version-href]: https://npmjs.com/package/create-require [npm-downloads-src]: https://img.shields.io/npm/dm/create-require?style=flat-square [npm-downloads-href]: https://npmjs.com/package/create-require [github-actions-src]: https://img.shields.io/github/workflow/status/nuxt-contrib/create-require/test/master?style=flat-square [github-actions-href]: https://github.com/nuxt-contrib/create-require/actions?query=workflow%3Atest [codecov-src]: https://img.shields.io/codecov/c/gh/nuxt-contrib/create-require/master?style=flat-square [codecov-href]: https://codecov.io/gh/nuxt-contrib/create-require # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Sponsors [![Scout APM](./sponsors/scout-apm.png)](https://scoutapm.com/) My Open Source work is supported by [Scout APM](https://scoutapm.com/) and [other sponsors](https://github.com/sponsors/indutny). ## Notation ### Prefixes There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the end of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this trick one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # node-tar Fast and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings and Errors Tar emits warnings and errors for recoverable and unrecoverable situations, respectively. In many cases, a warning only affects a single entry in an archive, or is simply informing you that it's modifying an entry to comply with the settings provided. Unrecoverable warnings will always raise an error (ie, emit `'error'` on streaming actions, throw for non-streaming sync actions, reject the returned Promise for non-streaming async operations, or call a provided callback with an `Error` as the first argument). Recoverable errors will raise an error only if `strict: true` is set in the options. Respond to (recoverable) warnings by listening to the `warn` event. Handlers receive 3 arguments: - `code` String. One of the error codes below. This may not match `data.code`, which preserves the original error code from fs and zlib. - `message` String. More details about the error. - `data` Metadata about the error. An `Error` object for errors raised by fs and zlib. All fields are attached to errors raisd by tar. Typically contains the following fields, as relevant: - `tarCode` The tar error code. - `code` Either the tar error code, or the error code set by the underlying system. - `file` The archive file being read or written. - `cwd` Working directory for creation and extraction operations. - `entry` The entry object (if it could be created) for `TAR_ENTRY_INFO`, `TAR_ENTRY_INVALID`, and `TAR_ENTRY_ERROR` warnings. - `header` The header object (if it could be created, and the entry could not be created) for `TAR_ENTRY_INFO` and `TAR_ENTRY_INVALID` warnings. - `recoverable` Boolean. If `false`, then the warning will emit an `error`, even in non-strict mode. #### Error Codes * `TAR_ENTRY_INFO` An informative error indicating that an entry is being modified, but otherwise processed normally. For example, removing `/` or `C:\` from absolute paths if `preservePaths` is not set. * `TAR_ENTRY_INVALID` An indication that a given entry is not a valid tar archive entry, and will be skipped. This occurs when: - a checksum fails, - a `linkpath` is missing for a link type, or - a `linkpath` is provided for a non-link type. If every entry in a parsed archive raises an `TAR_ENTRY_INVALID` error, then the archive is presumed to be unrecoverably broken, and `TAR_BAD_ARCHIVE` will be raised. * `TAR_ENTRY_ERROR` The entry appears to be a valid tar archive entry, but encountered an error which prevented it from being unpacked. This occurs when: - an unrecoverable fs error happens during unpacking, - an entry has `..` in the path and `preservePaths` is not set, or - an entry is extracting through a symbolic link, when `preservePaths` is not set. * `TAR_ENTRY_UNSUPPORTED` An indication that a given entry is a valid archive entry, but of a type that is unsupported, and so will be skipped in archive creation or extracting. * `TAR_ABORT` When parsing gzipped-encoded archives, the parser will abort the parse process raise a warning for any zlib errors encountered. Aborts are considered unrecoverable for both parsing and unpacking. * `TAR_BAD_ARCHIVE` The archive file is totally hosed. This can happen for a number of reasons, and always occurs at the end of a parse or extract: - An entry body was truncated before seeing the full number of bytes. - The archive contained only invalid entries, indicating that it is likely not an archive, or at least, not an archive this library can parse. `TAR_BAD_ARCHIVE` is considered informative for parse operations, but unrecoverable for extraction. Note that, if encountered at the end of an extraction, tar WILL still have extracted as much it could from the archive, so there may be some garbage files to clean up. Errors that occur deeper in the system (ie, either the filesystem or zlib) will have their error codes left intact, and a `tarCode` matching one of the above will be added to the warning metadata or the raised error object. Errors generated by tar will have one of the above codes set as the `error.code` field as well, but since errors originating in zlib or fs will have their original codes, it's better to read `error.tarCode` if you wish to see how tar is handling the issue. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` For example, to just get the list of filenames from an archive: ```js const getEntryFilenames = async tarballFilename => { const filenames = [] await tar.t({ file: tarballFilename, onentry: entry => filenames.push(entry.path), }) return filenames } ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. ```js const getEntryFilenamesSync = tarballFilename => { const filenames = [] tar.t({ file: tarballFilename, onentry: entry => filenames.push(entry.path), sync: true, }) return filenames } ``` To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the extracted file matches the entry mode. This also suppresses the call to `process.umask()` to determine the default umask value, since tar will extract with whatever mode is provided, and let the process `umask` apply normally. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. If the `file` option is _not_ provided, then returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) If a `file` option _is_ provided, then the return value will be a promise that resolves when the file has been fully traversed in async mode, or `undefined` if `sync: true` is set. Thus, you _must_ specify an `onentry` method in order to do anything useful with the data it parses. The following options are supported: - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when `file` is set, because there is no other way to do anything useful with this method. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noChmod` Set to true to omit calling `fs.chmod()` to ensure that the extracted file matches the entry mode. This also suppresses the call to `process.umask()` to determine the default umask value, since tar will extract with whatever mode is provided, and let the process `umask` apply normally. ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") #### abort(error) Stop all parsing activities. This is called when there are zlib errors. It also emits an unrecoverable warning with the error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size`, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary for other time-based operations. Additionally, `mode` is set to a "reasonable default" for most unix systems, based on a `umask` value of `0o22`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(code, message, data)` for any warnings encountered. (See "Warnings and Errors") - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # Can I cache this? [![Build Status](https://travis-ci.org/kornelski/http-cache-semantics.svg?branch=master)](https://travis-ci.org/kornelski/http-cache-semantics) `CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. ## Usage Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. ```js const policy = new CachePolicy(request, response, options); if (!policy.storable()) { // throw the response away, it's not usable at all return; } // Cache the data AND the policy object in your cache // (this is pseudocode, roll your own cache (lru-cache package works)) letsPretendThisIsSomeCache.set( request.url, { policy, response }, policy.timeToLive() ); ``` ```js // And later, when you receive a new request: const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url); // It's not enough that it exists in the cache, it has to match the new request, too: if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { // OK, the previous response can be used to respond to the `newRequest`. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. response.headers = policy.responseHeaders(); return response; } ``` It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc. The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. ### Constructor options Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method). ```js const request = { url: '/', method: 'GET', headers: { accept: '*/*', }, }; const response = { status: 200, headers: { 'cache-control': 'public, max-age=7234', }, }; const options = { shared: true, cacheHeuristic: 0.1, immutableMinTimeToLive: 24 * 3600 * 1000, // 24h ignoreCargoCult: false, }; ``` If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). `shared: true` is recommended for HTTP clients. `options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100\*0.1 = 10 days. `options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default. If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults. ### `storable()` Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response. ### `satisfiesWithoutRevalidation(newRequest)` This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request. If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`. If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`). ### `responseHeaders()` Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time. ```js cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); ``` ### `timeToLive()` Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh). After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`. `stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale. ### `toObject()`/`fromObject(json)` Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it. ### Refreshing stale cache (revalidation) When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth. The following methods help perform the update efficiently and correctly. #### `revalidationHeaders(newRequest)` Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is. Use this method when updating cache from the origin server. ```js updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); ``` #### `revalidatedPolicy(revalidationRequest, revalidationResponse)` Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: - `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. - `modified` — Boolean indicating whether the response body has changed. - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. This is also affected by `stale-if-error`. - If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource. ```js // When serving requests from cache: const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get( newRequest.url ); if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) { // Change the request to ask the origin server if the cached response can be used newRequest.headers = oldPolicy.revalidationHeaders(newRequest); // Send request to the origin server. The server may respond with status 304 const newResponse = await makeRequest(newRequest); // Create updated policy and combined response from the old and new data const { policy, modified } = oldPolicy.revalidatedPolicy( newRequest, newResponse ); const response = modified ? newResponse : oldResponse; // Update the cache with the newer/fresher response letsPretendThisIsSomeCache.set( newRequest.url, { policy, response }, policy.timeToLive() ); // And proceed returning cached response as usual response.headers = policy.responseHeaders(); return response; } ``` # Yo, FRESH ![satisfiesWithoutRevalidation](fresh.jpg) ## Used by - [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request) ([got](https://www.npmjs.com/package/got)), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/kornelski/http-cache-semantics/network/dependents) ## Implemented - `Cache-Control` response header with all the quirks. - `Expires` with check for bad clocks. - `Pragma` response header. - `Age` response header. - `Vary` response header. - Default cacheability of statuses and methods. - Requests for stale data. - Filtering of hop-by-hop headers. - Basic revalidation request - `stale-if-error` ## Unimplemented - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable) - Revalidation of multiple representations ### Trusting server `Date` Per the RFC, the cache should take into account the time between server-supplied `Date` and the time it received the response. The RFC-mandated behavior creates two problems: * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong). * Even reasonably correct clocks may be off by a couple of seconds, breaking `max-age=1` trick (which is useful for reverse proxies on high-traffic servers). Previous versions of this library had an option to ignore the server date if it was "too inaccurate". To support the `max-age=1` trick the library also has to ignore dates that pretty accurate. There's no point of having an option to trust dates that are only a bit inaccurate, so this library won't trust any server dates. `max-age` will be interpreted from the time the response has been received, not from when it has been sent. This will affect only [RFC 1149 networks](https://tools.ietf.org/html/rfc1149). Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/buffer/master.svg [travis-url]: https://travis-ci.org/feross/buffer [npm-image]: https://img.shields.io/npm/v/buffer.svg [npm-url]: https://npmjs.org/package/buffer [downloads-image]: https://img.shields.io/npm/dm/buffer.svg [downloads-url]: https://npmjs.org/package/buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### The buffer module from [node.js](https://nodejs.org/), for the browser. [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg [saucelabs-url]: https://saucelabs.com/u/buffer With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. The goal is to provide an API that is 100% identical to [node's Buffer API](https://nodejs.org/api/buffer.html). Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. ## features - Manipulate binary data like a boss, in all browsers! - Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) - Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) - Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) - Preserves Node API exactly, with one minor difference (see below) - Square-bracket `buf[4]` notation works! - Does not modify any browser prototypes or put anything on `window` - Comprehensive test suite (including all buffer tests from node.js core) ## install To use this module directly (without browserify), install it: ```bash npm install buffer ``` This module was previously called **native-buffer-browserify**, but please use **buffer** from now on. If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). ## usage The module's API is identical to node's `Buffer` API. Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. As mentioned above, `require('buffer')` or use the `Buffer` global with [browserify](http://browserify.org) and this module will automatically be included in your bundle. Almost any npm module will work in the browser, even if it assumes that the node `Buffer` API will be available. To depend on this module explicitly (without browserify), require it like this: ```js var Buffer = require('buffer/').Buffer // note: the trailing slash is important! ``` To require this module explicitly, use `require('buffer/')` which tells the node.js module lookup algorithm (also used by browserify) to use the **npm module** named `buffer` instead of the **node.js core** module named `buffer`! ## how does it work? The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified. ## tracking the latest node api This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer API is considered **stable** in the [node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), so it is unlikely that there will ever be breaking changes. Nonetheless, when/if the Buffer API changes in node, this module's API will change accordingly. ## related packages - [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer - [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer - [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package ## conversion packages ### convert typed array to buffer Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. ### convert buffer to typed array `Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. ### convert blob to buffer Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. ### convert buffer to blob To convert a `Buffer` to a `Blob`, use the `Blob` constructor: ```js var blob = new Blob([ buffer ]) ``` Optionally, specify a mimetype: ```js var blob = new Blob([ buffer ], { type: 'text/html' }) ``` ### convert arraybuffer to buffer To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. ```js var buffer = Buffer.from(arrayBuffer) ``` ### convert buffer to arraybuffer To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): ```js var arrayBuffer = buffer.buffer.slice( buffer.byteOffset, buffer.byteOffset + buffer.byteLength ) ``` Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. ## performance See perf tests in `/perf`. `BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, which is included to compare against. NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. ### Chrome 38 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | | Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | | | | | | | BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | | Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | | Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | | Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | | Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | | Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | | DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | | | | | | | BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | | DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | | | | | | | BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | | DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | | | | | | | BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | | Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | | DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | ### Firefox 33 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | | Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | | | | | | | BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | | Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | | Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | | Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | | Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | | | | | | | BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | | Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | | DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | | DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | | DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | | | | | | | BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | | Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | | DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | ### Safari 8 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | | Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | | | | | | | BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | | Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | | Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | | | | | | | BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | | Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | | | | | | | BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | | Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | | | | | | | BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | | Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | | DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | | DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | | DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | | | | | | | BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | | Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | | DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | ### Node 0.11.14 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | | Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | | NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | | | | | | | BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | | Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | | NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | | | | | | | BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | | Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | | NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | | | | | | | BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | | Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | | NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | | | | | | | BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | | Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | | NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | | Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | | NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | | | | | | | BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | | DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | | NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | | | | | | | BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | | DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | | NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | | | | | | | BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | | DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | | NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | | | | | | | BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | | Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | | NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | | | | | | | BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | | DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | | NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | ### iojs 1.8.1 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | | Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | | NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | | | | | | | BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | | Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | | NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | | Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | | NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | | | | | | | BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | | Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | | NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | | | | | | | BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | | Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | | NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | | Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | | NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | | | | | | | BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | | DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | | NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | | | | | | | BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | | DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | | NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | | | | | | | BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | | DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | | NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | | | | | | | BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | | Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | | NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | | DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | | NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | | | | | | ## Testing the project First, install the project: npm install Then, to run tests in Node.js, run: npm run test-node To test locally in a browser, you can run: npm run test-browser-es5-local # For ES5 browsers that don't support ES6 npm run test-browser-es6-local # For ES6 compliant browsers This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: npm test This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. ## JavaScript Standard Style This module uses [JavaScript Standard Style](https://github.com/feross/standard). [![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) To test that the code conforms to the style, `npm install` and run: ./node_modules/.bin/standard ## credit This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). ## Security Policies and Procedures The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # is-typedarray [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) Detect whether or not an object is a [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). ## Usage [![NPM](https://nodei.co/npm/is-typedarray.png)](https://nodei.co/npm/is-typedarray/) ### isTypedArray(array) Returns `true` when array is a Typed Array, and `false` when it is not. ## License MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # jsdiff [![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.svg)](http://travis-ci.org/kpdecker/jsdiff) [![Sauce Test Status](https://saucelabs.com/buildstatus/jsdiff)](https://saucelabs.com/u/jsdiff) A javascript text differencing implementation. Based on the algorithm proposed in ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). ## Installation ```bash npm install diff --save ``` ## API * `JsDiff.diffChars(oldStr, newStr[, options])` - diffs two blocks of text, comparing character by character. Returns a list of change objects (See below). Options * `ignoreCase`: `true` to ignore casing difference. Defaults to `false`. * `JsDiff.diffWords(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, ignoring whitespace. Returns a list of change objects (See below). Options * `ignoreCase`: Same as in `diffChars`. * `JsDiff.diffWordsWithSpace(oldStr, newStr[, options])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. Returns a list of change objects (See below). * `JsDiff.diffLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line. Options * `ignoreWhitespace`: `true` to ignore leading and trailing whitespace. This is the same as `diffTrimmedLines` * `newlineIsToken`: `true` to treat newline characters as separate tokens. This allows for changes to the newline structure to occur independently of the line content and to be treated as such. In general this is the more human friendly form of `diffLines` and `diffLines` is better suited for patches and other computer friendly output. Returns a list of change objects (See below). * `JsDiff.diffTrimmedLines(oldStr, newStr[, options])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. Returns a list of change objects (See below). * `JsDiff.diffSentences(oldStr, newStr[, options])` - diffs two blocks of text, comparing sentence by sentence. Returns a list of change objects (See below). * `JsDiff.diffCss(oldStr, newStr[, options])` - diffs two blocks of text, comparing CSS tokens. Returns a list of change objects (See below). * `JsDiff.diffJson(oldObj, newObj[, options])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. Returns a list of change objects (See below). * `JsDiff.diffArrays(oldArr, newArr[, options])` - diffs two arrays, comparing each item for strict equality (===). Options * `comparator`: `function(left, right)` for custom equality checks Returns a list of change objects (See below). * `JsDiff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Parameters: * `oldFileName` : String to be output in the filename section of the patch for the removals * `newFileName` : String to be output in the filename section of the patch for the additions * `oldStr` : Original string value * `newStr` : New string value * `oldHeader` : Additional information to include in the old file header * `newHeader` : Additional information to include in the new file header * `options` : An object with options. Currently, only `context` is supported and describes how many lines of context should be included. * `JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. Just like JsDiff.createTwoFilesPatch, but with oldFileName being equal to newFileName. * `JsDiff.structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)` - returns an object with an array of hunk objects. This method is similar to createTwoFilesPatch, but returns a data structure suitable for further processing. Parameters are the same as createTwoFilesPatch. The data structure returned may look like this: ```js { oldFileName: 'oldfile', newFileName: 'newfile', oldHeader: 'header1', newHeader: 'header2', hunks: [{ oldStart: 1, oldLines: 3, newStart: 1, newLines: 3, lines: [' line2', ' line3', '-line4', '+line5', '\\ No newline at end of file'], }] } ``` * `JsDiff.applyPatch(source, patch[, options])` - applies a unified diff patch. Return a string containing new version of provided data. `patch` may be a string diff or the output from the `parsePatch` or `structuredPatch` methods. The optional `options` object may have the following keys: - `fuzzFactor`: Number of lines that are allowed to differ before rejecting a patch. Defaults to 0. - `compareLine(lineNumber, line, operation, patchContent)`: Callback used to compare to given lines to determine if they should be considered equal when patching. Defaults to strict equality but may be overridden to provide fuzzier comparison. Should return false if the lines should be rejected. * `JsDiff.applyPatches(patch, options)` - applies one or more patches. This method will iterate over the contents of the patch and apply to data provided through callbacks. The general flow for each patch index is: - `options.loadFile(index, callback)` is called. The caller should then load the contents of the file and then pass that to the `callback(err, data)` callback. Passing an `err` will terminate further patch execution. - `options.patched(index, content, callback)` is called once the patch has been applied. `content` will be the return value from `applyPatch`. When it's ready, the caller should call `callback(err)` callback. Passing an `err` will terminate further patch execution. Once all patches have been applied or an error occurs, the `options.complete(err)` callback is made. * `JsDiff.parsePatch(diffStr)` - Parses a patch into structured data Return a JSON object representation of the a patch, suitable for use with the `applyPatch` method. This parses to the same structure returned by `JsDiff.structuredPatch`. * `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format All methods above which accept the optional `callback` method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. This may be passed either directly as the final parameter or as the `callback` field in the `options` object. ### Change Objects Many of the methods above return change objects. These objects consist of the following fields: * `value`: Text content * `added`: True if the value was inserted into the new string * `removed`: True if the value was removed from the old string Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. ## Examples Basic example in Node ```js require('colors'); var jsdiff = require('diff'); var one = 'beep boop'; var other = 'beep boob blah'; var diff = jsdiff.diffChars(one, other); diff.forEach(function(part){ // green for additions, red for deletions // grey for common parts var color = part.added ? 'green' : part.removed ? 'red' : 'grey'; process.stderr.write(part.value[color]); }); console.log(); ``` Running the above program should yield <img src="images/node_example.png" alt="Node Example"> Basic example in a web page ```html <pre id="display"></pre> <script src="diff.js"></script> <script> var one = 'beep boop', other = 'beep boob blah', color = '', span = null; var diff = JsDiff.diffChars(one, other), display = document.getElementById('display'), fragment = document.createDocumentFragment(); diff.forEach(function(part){ // green for additions, red for deletions // grey for common parts color = part.added ? 'green' : part.removed ? 'red' : 'grey'; span = document.createElement('span'); span.style.color = color; span.appendChild(document .createTextNode(part.value)); fragment.appendChild(span); }); display.appendChild(fragment); </script> ``` Open the above .html file in a browser and you should see <img src="images/web_example.png" alt="Node Example"> **[Full online demo](http://kpdecker.github.com/jsdiff)** ## Compatibility [![Sauce Test Status](https://saucelabs.com/browser-matrix/jsdiff.svg)](https://saucelabs.com/u/jsdiff) jsdiff supports all ES3 environments with some known issues on IE8 and below. Under these browsers some diff algorithms such as word diff and others may fail due to lack of support for capturing groups in the `split` operation. ## License See [LICENSE](https://github.com/kpdecker/jsdiff/blob/master/LICENSE). # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Sponsors [![Scout APM](./sponsors/scout-apm.png)](https://scoutapm.com/) My Open Source work is supported by [Scout APM](https://scoutapm.com/) and [other sponsors](https://github.com/sponsors/indutny). ## Notation ### Prefixes There are several prefixes to instructions that affect the way they work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the end of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this trick one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime base64-js ========= `base64-js` does basic base64 encoding/decoding in pure JS. [![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. ## install With [npm](https://npmjs.org) do: `npm install base64-js` and `var base64js = require('base64-js')` For use in web browsers do: `<script src="base64js.min.js"></script>` [Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) ## methods `base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. * `byteLength` - Takes a base64 string and returns length of byte array * `toByteArray` - Takes a base64 string and returns a byte array * `fromByteArray` - Takes a byte array and returns a base64 string ## license MIT # axios-retry [![Build Status](https://travis-ci.org/softonic/axios-retry.svg?branch=master)](https://travis-ci.org/softonic/axios-retry) Axios plugin that intercepts failed requests and retries them whenever possible. ## Installation ```bash npm install axios-retry ``` ### Note Not working with `axios 0.19.0`. For details see the [bug](https://github.com/axios/axios/issues/2203). [`axios 0.19.1`](https://github.com/axios/axios/releases/tag/0.19.1) has fixed this bug. ## Usage ```js // CommonJS // const axiosRetry = require('axios-retry'); // ES6 import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3 }); axios.get('http://example.com/test') // The first request fails and the second returns 'ok' .then(result => { result.data; // 'ok' }); // Exponential back-off retry delay between requests axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay}); // Custom retry delay axiosRetry(axios, { retryDelay: (retryCount) => { return retryCount * 1000; }}); // Works with custom axios instances const client = axios.create({ baseURL: 'http://example.com' }); axiosRetry(client, { retries: 3 }); client.get('/test') // The first request fails and the second returns 'ok' .then(result => { result.data; // 'ok' }); // Allows request-specific configuration client .get('/test', { 'axios-retry': { retries: 0 } }) .catch(error => { // The first request fails error !== undefined }); ``` **Note:** Unless `shouldResetTimeout` is set, the plugin interprets the request timeout as a global value, so it is not used for each retry but for the whole request lifecycle. ## Options | Name | Type | Default | Description | | --- | --- | --- | --- | | retries | `Number` | `3` | The number of times to retry before failing. | | retryCondition | `Function` | `isNetworkOrIdempotentRequestError` | A callback to further control if a request should be retried. By default, it retries if it is a network error or a 5xx error on an idempotent request (GET, HEAD, OPTIONS, PUT or DELETE). | | shouldResetTimeout | `Boolean` | false | Defines if the timeout should be reset between retries | | retryDelay | `Function` | `function noDelay() { return 0; }` | A callback to further control the delay in milliseconds between retried requests. By default there is no delay between retries. Another option is exponentialDelay ([Exponential Backoff](https://developers.google.com/analytics/devguides/reporting/core/v3/errors#backoff)). The function is passed `retryCount` and `error`. | ## Testing Clone the repository and execute: ```bash npm test ``` ## Contribute 1. Fork it: `git clone https://github.com/softonic/axios-retry.git` 2. Create your feature branch: `git checkout -b feature/my-new-feature` 3. Commit your changes: `git commit -am 'Added some feature'` 4. Check the build: `npm run build` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # responselike > A response-like object for mocking a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/responselike.svg?branch=master)](https://travis-ci.org/lukechilds/responselike) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/responselike/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/responselike?branch=master) [![npm](https://img.shields.io/npm/dm/responselike.svg)](https://www.npmjs.com/package/responselike) [![npm](https://img.shields.io/npm/v/responselike.svg)](https://www.npmjs.com/package/responselike) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). Useful for formatting cached responses so they can be consumed by code expecting a real response. ## Install ```shell npm install --save responselike ``` Or if you're just using for testing you'll want: ```shell npm install --save-dev responselike ``` ## Usage ```js const Response = require('responselike'); const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); response.statusCode; // 200 response.headers; // { foo: 'bar' } response.body; // <Buffer 48 69 21> response.url; // 'https://example.com' response.pipe(process.stdout); // Hi! ``` ## API ### new Response(statusCode, headers, body, url) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). #### statusCode Type: `number` HTTP response status code. #### headers Type: `object` HTTP headers object. Keys will be automatically lowercased. #### body Type: `buffer` A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. #### url Type: `string` Request URL string. ## License MIT © Luke Childs # homedir-polyfill [![NPM version](https://img.shields.io/npm/v/homedir-polyfill.svg?style=flat)](https://www.npmjs.com/package/homedir-polyfill) [![NPM monthly downloads](https://img.shields.io/npm/dm/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![NPM total downloads](https://img.shields.io/npm/dt/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![Linux Build Status](https://img.shields.io/travis/doowb/homedir-polyfill.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/homedir-polyfill) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/homedir-polyfill.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/homedir-polyfill) > Node.js os.homedir polyfill for older versions of node.js. Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save homedir-polyfill ``` ## Usage ```js var homedir = require('homedir-polyfill'); console.log(homedir()); //=> /Users/doowb ``` ## Reasoning This library is a polyfill for the [node.js os.homedir](https://nodejs.org/api/os.html#os_os_homedir) method found in modern versions of node.js. This implementation tries to follow the implementation found in `libuv` by finding the current user using the `process.geteuid()` method and the `/etc/passwd` file. This should usually work in a linux environment, but will also fallback to looking at user specific environment variables to build the user's home directory if neccessary. Since `/etc/passwd` is not available on windows platforms, this implementation will use environment variables to find the home directory. In modern versions of node.js, [os.homedir](https://nodejs.org/api/os.html#os_os_homedir) is used. ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: [parse-passwd](https://www.npmjs.com/package/parse-passwd): Parse a passwd file into a list of users. | [homepage](https://github.com/doowb/parse-passwd "Parse a passwd file into a list of users.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 19 | [doowb](https://github.com/doowb) | | 2 | [martinheidegger](https://github.com/martinheidegger) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2016 - 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on February 21, 2019._ # Console Control Strings A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted. ## Usage ```js var consoleControl = require('console-control-strings') console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) process.stdout.write(consoleControl.goto(75, 10)) ``` ## Why Another? There are tons of libraries similar to this one. I wanted one that was: 1. Very clear about compatibility goals. 2. Could emit, for instance, a start color code without an end one. 3. Returned strings w/o writing to streams. 4. Was not weighed down with other unrelated baggage. ## Functions ### var code = consoleControl.up(_num = 1_) Returns the escape sequence to move _num_ lines up. ### var code = consoleControl.down(_num = 1_) Returns the escape sequence to move _num_ lines down. ### var code = consoleControl.forward(_num = 1_) Returns the escape sequence to move _num_ lines righ. ### var code = consoleControl.back(_num = 1_) Returns the escape sequence to move _num_ lines left. ### var code = consoleControl.nextLine(_num = 1_) Returns the escape sequence to move _num_ lines down and to the beginning of the line. ### var code = consoleControl.previousLine(_num = 1_) Returns the escape sequence to move _num_ lines up and to the beginning of the line. ### var code = consoleControl.eraseData() Returns the escape sequence to erase everything from the current cursor position to the bottom right of the screen. This is line based, so it erases the remainder of the current line and all following lines. ### var code = consoleControl.eraseLine() Returns the escape sequence to erase to the end of the current line. ### var code = consoleControl.goto(_x_, _y_) Returns the escape sequence to move the cursor to the designated position. Note that the origin is _1, 1_ not _0, 0_. ### var code = consoleControl.gotoSOL() Returns the escape sequence to move the cursor to the beginning of the current line. (That is, it returns a carriage return, `\r`.) ### var code = consoleControl.beep() Returns the escape sequence to cause the termianl to beep. (That is, it returns unicode character `\x0007`, a Control-G.) ### var code = consoleControl.hideCursor() Returns the escape sequence to hide the cursor. ### var code = consoleControl.showCursor() Returns the escape sequence to show the cursor. ### var code = consoleControl.color(_colors = []_) ### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) Returns the escape sequence to set the current terminal display attributes (mostly colors). Arguments can either be a list of attributes or an array of attributes. The difference between passing in an array or list of colors and calling `.color` separately for each one, is that in the former case a single escape sequence will be produced where as in the latter each change will have its own distinct escape sequence. Each attribute can be one of: * Reset: * **reset** – Reset all attributes to the terminal default. * Styles: * **bold** – Display text as bold. In some terminals this means using a bold font, in others this means changing the color. In some it means both. * **italic** – Display text as italic. This is not available in most Windows terminals. * **underline** – Underline text. This is not available in most Windows Terminals. * **inverse** – Invert the foreground and background colors. * **stopBold** – Do not display text as bold. * **stopItalic** – Do not display text as italic. * **stopUnderline** – Do not underline text. * **stopInverse** – Do not invert foreground and background. * Colors: * **white** * **black** * **blue** * **cyan** * **green** * **magenta** * **red** * **yellow** * **grey** / **brightBlack** * **brightRed** * **brightGreen** * **brightYellow** * **brightBlue** * **brightMagenta** * **brightCyan** * **brightWhite** * Background Colors: * **bgWhite** * **bgBlack** * **bgBlue** * **bgCyan** * **bgGreen** * **bgMagenta** * **bgRed** * **bgYellow** * **bgGrey** / **bgBrightBlack** * **bgBrightRed** * **bgBrightGreen** * **bgBrightYellow** * **bgBrightBlue** * **bgBrightMagenta** * **bgBrightCyan** * **bgBrightWhite** Like `chown -R`. Takes the same arguments as `fs.chown()` # fsevents [![NPM](https://nodei.co/npm/fsevents.png)](https://nodei.co/npm/fsevents/) Native access to MacOS FSEvents in [Node.js](https://nodejs.org/) The FSEvents API in MacOS allows applications to register for notifications of changes to a given directory tree. It is a very fast and lightweight alternative to kqueue. This is a low-level library. For a cross-platform file watching module that uses fsevents, check out [Chokidar](https://github.com/paulmillr/chokidar). ## Installation Supports only **Node.js v8.16 and higher**. ```sh npm install fsevents ``` ## Usage ```js const fsevents = require('fsevents'); const stop = fsevents.watch(__dirname, (path, flags, id) => { const info = fsevents.getInfo(path, flags, id); }); // To start observation stop(); // To end observation ``` The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a a change in the file system. It takes three arguments: ###### `fsevents.watch(dirname: string, (path: string, flags: number, id: string) => void): () => Promise<undefined>` * `path: string` - the item in the filesystem that have been changed * `flags: number` - a numeric value describing what the change was * `id: string` - an unique-id identifying this specific event Returns closer callback which when called returns a Promise resolving when the watcher process has been shut down. ###### `fsevents.getInfo(path: string, flags: number, id: string): FsEventInfo` The `getInfo` function takes the `path`, `flags` and `id` arguments and converts those parameters into a structure that is easier to digest to determine what the change was. The `FsEventsInfo` has the following shape: ```js /** * @typedef {'created'|'modified'|'deleted'|'moved'|'root-changed'|'cloned'|'unknown'} FsEventsEvent * @typedef {'file'|'directory'|'symlink'} FsEventsType */ { "event": "created", // {FsEventsEvent} "path": "file.txt", "type": "file", // {FsEventsType} "changes": { "inode": true, // Had iNode Meta-Information changed "finder": false, // Had Finder Meta-Data changed "access": false, // Had access permissions changed "xattrs": false // Had xAttributes changed }, "flags": 0x100000000 } ``` ## Changelog - v2.3 supports Apple Silicon ARM CPUs - v2 supports node 8.16+ and reduces package size massively - v1.2.8 supports node 6+ - v1.2.7 supports node 4+ ## Troubleshooting - I'm getting `EBADPLATFORM` `Unsupported platform for fsevents` error. - It's fine, nothing is broken. fsevents is macos-only. Other platforms are skipped. If you want to hide this warning, report a bug to NPM bugtracker asking them to hide ebadplatform warnings by default. ## License The MIT License Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller — see LICENSE file. Visit our [GitHub page](https://github.com/fsevents/fsevents) and [NPM Page](https://npmjs.org/package/fsevents) # detect-libc Node.js module to detect details of the C standard library (libc) implementation provided by a given Linux system. Currently supports detection of GNU glibc and MUSL libc. Provides asychronous and synchronous functions for the family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`). For previous v1.x releases, please see the [v1](https://github.com/lovell/detect-libc/tree/v1) branch. ## Install ```sh npm install detect-libc ``` ## API ### GLIBC ```ts const GLIBC: string = 'glibc'; ``` A String constant containing the value `glibc`. ### MUSL ```ts const MUSL: string = 'musl'; ``` A String constant containing the value `musl`. ### family ```ts function family(): Promise<string | null>; ``` Resolves asychronously with: * `glibc` or `musl` when the libc family can be determined * `null` when the libc family cannot be determined * `null` when run on a non-Linux platform ```js const { family, GLIBC, MUSL } = require('detect-libc'); switch (await family()) { case GLIBC: ... case MUSL: ... case null: ... } ``` ### familySync ```ts function familySync(): string | null; ``` Synchronous version of `family()`. ```js const { familySync, GLIBC, MUSL } = require('detect-libc'); switch (familySync()) { case GLIBC: ... case MUSL: ... case null: ... } ``` ### version ```ts function version(): Promise<string | null>; ``` Resolves asychronously with: * The version when it can be determined * `null` when the libc family cannot be determined * `null` when run on a non-Linux platform ```js const { version } = require('detect-libc'); const v = await version(); if (v) { const [major, minor, patch] = v.split('.'); } ``` ### versionSync ```ts function versionSync(): string | null; ``` Synchronous version of `version()`. ```js const { versionSync } = require('detect-libc'); const v = versionSync(); if (v) { const [major, minor, patch] = v.split('.'); } ``` ### isNonGlibcLinux ```ts function isNonGlibcLinux(): Promise<boolean>; ``` Resolves asychronously with: * `false` when the libc family is `glibc` * `true` when the libc family is not `glibc` * `false` when run on a non-Linux platform ```js const { isNonGlibcLinux } = require('detect-libc'); if (await isNonGlibcLinux()) { ... } ``` ### isNonGlibcLinuxSync ```ts function isNonGlibcLinuxSync(): boolean; ``` Synchronous version of `isNonGlibcLinux()`. ```js const { isNonGlibcLinuxSync } = require('detect-libc'); if (isNonGlibcLinuxSync()) { ... } ``` ## Licensing Copyright 2017, 2022 Lovell Fuller Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # reusify [![npm version][npm-badge]][npm-url] [![Build Status][travis-badge]][travis-url] [![Coverage Status][coveralls-badge]][coveralls-url] Reuse your objects and functions for maximum speed. This technique will make any function run ~10% faster. You call your functions a lot, and it adds up quickly in hot code paths. ``` $ node benchmarks/createNoCodeFunction.js Total time 53133 Total iterations 100000000 Iteration/s 1882069.5236482036 $ node benchmarks/reuseNoCodeFunction.js Total time 50617 Total iterations 100000000 Iteration/s 1975620.838848608 ``` The above benchmark uses fibonacci to simulate a real high-cpu load. The actual numbers might differ for your use case, but the difference should not. The benchmark was taken using Node v6.10.0. This library was extracted from [fastparallel](http://npm.im/fastparallel). ## Example ```js var reusify = require('reusify') var fib = require('reusify/benchmarks/fib') var instance = reusify(MyObject) // get an object from the cache, // or creates a new one when cache is empty var obj = instance.get() // set the state obj.num = 100 obj.func() // reset the state. // if the state contains any external object // do not use delete operator (it is slow) // prefer set them to null obj.num = 0 // store an object in the cache instance.release(obj) function MyObject () { // you need to define this property // so V8 can compile MyObject into an // hidden class this.next = null this.num = 0 var that = this // this function is never reallocated, // so it can be optimized by V8 this.func = function () { if (null) { // do nothing } else { // calculates fibonacci fib(that.num) } } } ``` The above example was intended for synchronous code, let's see async: ```js var reusify = require('reusify') var instance = reusify(MyObject) for (var i = 0; i < 100; i++) { getData(i, console.log) } function getData (value, cb) { var obj = instance.get() obj.value = value obj.cb = cb obj.run() } function MyObject () { this.next = null this.value = null var that = this this.run = function () { asyncOperation(that.value, that.handle) } this.handle = function (err, result) { that.cb(err, result) that.value = null that.cb = null instance.release(that) } } ``` Also note how in the above examples, the code, that consumes an istance of `MyObject`, reset the state to initial condition, just before storing it in the cache. That's needed so that every subsequent request for an instance from the cache, could get a clean instance. ## Why It is faster because V8 doesn't have to collect all the functions you create. On a short-lived benchmark, it is as fast as creating the nested function, but on a longer time frame it creates less pressure on the garbage collector. ## Other examples If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). ## Acknowledgements Thanks to [Trevor Norris](https://github.com/trevnorris) for getting me down the rabbit hole of performance, and thanks to [Mathias Buss](http://github.com/mafintosh) for suggesting me to share this trick. ## License MIT [npm-badge]: https://badge.fury.io/js/reusify.svg [npm-url]: https://badge.fury.io/js/reusify [travis-badge]: https://api.travis-ci.org/mcollina/reusify.svg [travis-url]: https://travis-ci.org/mcollina/reusify [coveralls-badge]: https://coveralls.io/repos/mcollina/reusify/badge.svg?branch=master&service=github [coveralls-url]: https://coveralls.io/github/mcollina/reusify?branch=master # hash-base [![NPM Package](https://img.shields.io/npm/v/hash-base.svg?style=flat-square)](https://www.npmjs.org/package/hash-base) [![Build Status](https://img.shields.io/travis/crypto-browserify/hash-base.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/hash-base) [![Dependency status](https://img.shields.io/david/crypto-browserify/hash-base.svg?style=flat-square)](https://david-dm.org/crypto-browserify/hash-base#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Abstract base class to inherit from if you want to create streams implementing the same API as node crypto [Hash][1] (for [Cipher][2] / [Decipher][3] check [crypto-browserify/cipher-base][4]). ## Example ```js const HashBase = require('hash-base') const inherits = require('inherits') // our hash function is XOR sum of all bytes function MyHash () { HashBase.call(this, 1) // in bytes this._sum = 0x00 } inherits(MyHash, HashBase) MyHash.prototype._update = function () { for (let i = 0; i < this._block.length; ++i) this._sum ^= this._block[i] } MyHash.prototype._digest = function () { return this._sum } const data = Buffer.from([ 0x00, 0x42, 0x01 ]) const hash = new MyHash().update(data).digest() console.log(hash) // => 67 ``` You also can check [source code](index.js) or [crypto-browserify/md5.js][5] ## LICENSE MIT [1]: https://nodejs.org/api/crypto.html#crypto_class_hash [2]: https://nodejs.org/api/crypto.html#crypto_class_cipher [3]: https://nodejs.org/api/crypto.html#crypto_class_decipher [4]: https://github.com/crypto-browserify/cipher-base [5]: https://github.com/crypto-browserify/md5.js JS-YAML - YAML 1.2 parser / writer for JavaScript ================================================= [![Build Status](https://travis-ci.org/nodeca/js-yaml.svg?branch=master)](https://travis-ci.org/nodeca/js-yaml) [![NPM version](https://img.shields.io/npm/v/js-yaml.svg)](https://www.npmjs.org/package/js-yaml) __[Online Demo](http://nodeca.github.com/js-yaml/)__ This is an implementation of [YAML](http://yaml.org/), a human-friendly data serialization language. Started as [PyYAML](http://pyyaml.org/) port, it was completely rewritten from scratch. Now it's very fast, and supports 1.2 spec. Installation ------------ ### YAML module for node.js ``` npm install js-yaml ``` ### CLI executable If you want to inspect your YAML files from CLI, install js-yaml globally: ``` npm install -g js-yaml ``` #### Usage ``` usage: js-yaml [-h] [-v] [-c] [-t] file Positional arguments: file File with YAML document(s) Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -c, --compact Display errors in compact mode -t, --trace Show stack trace on error ``` ### Bundled YAML library for browsers ``` html <!-- esprima required only for !!js/function --> <script src="esprima.js"></script> <script src="js-yaml.min.js"></script> <script type="text/javascript"> var doc = jsyaml.load('greeting: hello\nname: world'); </script> ``` Browser support was done mostly for the online demo. If you find any errors - feel free to send pull requests with fixes. Also note, that IE and other old browsers needs [es5-shims](https://github.com/kriskowal/es5-shim) to operate. Notes: 1. We have no resources to support browserified version. Don't expect it to be well tested. Don't expect fast fixes if something goes wrong there. 2. `!!js/function` in browser bundle will not work by default. If you really need it - load `esprima` parser first (via amd or directly). 3. `!!bin` in browser will return `Array`, because browsers do not support node.js `Buffer` and adding Buffer shims is completely useless on practice. API --- Here we cover the most 'useful' methods. If you need advanced details (creating your own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and [examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more info. ``` javascript const yaml = require('js-yaml'); const fs = require('fs'); // Get document, or throw exception on error try { const doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8')); console.log(doc); } catch (e) { console.log(e); } ``` ### safeLoad (string [ , options ]) **Recommended loading way.** Parses `string` as single YAML document. Returns either a plain object, a string or `undefined`, or throws `YAMLException` on error. By default, does not support regexps, functions and undefined. This method is safe for untrusted data. options: - `filename` _(default: null)_ - string to be used as a file path in error/warning messages. - `onWarning` _(default: null)_ - function to call on warning messages. Loader will call this function with an instance of `YAMLException` for each warning. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ - specifies a schema to use. - `FAILSAFE_SCHEMA` - only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - `JSON_SCHEMA` - all JSON-supported types: http://www.yaml.org/spec/1.2/spec.html#id2803231 - `CORE_SCHEMA` - same as `JSON_SCHEMA`: http://www.yaml.org/spec/1.2/spec.html#id2804923 - `DEFAULT_SAFE_SCHEMA` - all supported YAML types, without unsafe ones (`!!js/undefined`, `!!js/regexp` and `!!js/function`): http://yaml.org/type/ - `DEFAULT_FULL_SCHEMA` - all supported YAML types. - `json` _(default: false)_ - compatibility with JSON.parse behaviour. If true, then duplicate keys in a mapping will override values rather than throwing an error. NOTE: This function **does not** understand multi-document sources, it throws exception on those. NOTE: JS-YAML **does not** support schema-specific tag resolution restrictions. So, the JSON schema is not as strictly defined in the YAML specification. It allows numbers in any notation, use `Null` and `NULL` as `null`, etc. The core schema also has no such restrictions. It allows binary notation for integers. ### load (string [ , options ]) **Use with care with untrusted sources**. The same as `safeLoad()` but uses `DEFAULT_FULL_SCHEMA` by default - adds some JavaScript-specific types: `!!js/function`, `!!js/regexp` and `!!js/undefined`. For untrusted sources, you must additionally validate object structure to avoid injections: ``` javascript const untrusted_code = '"toString": !<tag:yaml.org,2002:js/function> "function (){very_evil_thing();}"'; // I'm just converting that string, what could possibly go wrong? require('js-yaml').load(untrusted_code) + '' ``` ### safeLoadAll (string [, iterator] [, options ]) Same as `safeLoad()`, but understands multi-document sources. Applies `iterator` to each document if specified, or returns array of documents. ``` javascript const yaml = require('js-yaml'); yaml.safeLoadAll(data, function (doc) { console.log(doc); }); ``` ### loadAll (string [, iterator] [ , options ]) Same as `safeLoadAll()` but uses `DEFAULT_FULL_SCHEMA` by default. ### safeDump (object [ , options ]) Serializes `object` as a YAML document. Uses `DEFAULT_SAFE_SCHEMA`, so it will throw an exception if you try to dump regexps or functions. However, you can disable exceptions by setting the `skipInvalid` option to `true`. options: - `indent` _(default: 2)_ - indentation width to use (in spaces). - `noArrayIndent` _(default: false)_ - when true, will not add an indentation level to array elements - `skipInvalid` _(default: false)_ - do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - `flowLevel` (default: -1) - specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - `styles` - "tag" => "style" map. Each tag may have own set of styles. - `schema` _(default: `DEFAULT_SAFE_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. - `lineWidth` _(default: `80`)_ - set max line width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 - `condenseFlow` _(default: `false`)_ - if `true` flow sequences will be condensed, omitting the space between `a, b`. Eg. `'[a,b]'`, and omitting the space between `key: value` and quoting the key. Eg. `'{"a":b}'` Can be useful when using yaml for pretty URL query params as spaces are %-encoded. The following table show availlable styles (e.g. "canonical", "binary"...) available for each tag (.e.g. !!null, !!int ...). Yaml output is shown on the right side after `=>` (default setting) or `->`: ``` none !!null "canonical" -> "~" "lowercase" => "null" "uppercase" -> "NULL" "camelcase" -> "Null" !!int "binary" -> "0b1", "0b101010", "0b1110001111010" "octal" -> "01", "052", "016172" "decimal" => "1", "42", "7290" "hexadecimal" -> "0x1", "0x2A", "0x1C7A" !!bool "lowercase" => "true", "false" "uppercase" -> "TRUE", "FALSE" "camelcase" -> "True", "False" !!float "lowercase" => ".nan", '.inf' "uppercase" -> ".NAN", '.INF' "camelcase" -> ".NaN", '.Inf' ``` Example: ``` javascript safeDump (object, { 'styles': { '!!null': 'canonical' // dump null as ~ }, 'sortKeys': true // sort object keys }); ``` ### dump (object [ , options ]) Same as `safeDump()` but without limits (uses `DEFAULT_FULL_SCHEMA` by default). Supported YAML types -------------------- The list of standard YAML tags and corresponding JavaScipt types. See also [YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and [YAML types repository](http://yaml.org/type/). ``` !!null '' # null !!bool 'yes' # bool !!int '3...' # number !!float '3.14...' # number !!binary '...base64...' # buffer !!timestamp 'YYYY-...' # date !!omap [ ... ] # array of key-value pairs !!pairs [ ... ] # array or array pairs !!set { ... } # array of objects with given keys and null values !!str '...' # string !!seq [ ... ] # array !!map { ... } # object ``` **JavaScript-specific tags** ``` !!js/regexp /pattern/gim # RegExp !!js/undefined '' # Undefined !!js/function 'function () {...}' # Function ``` Caveats ------- Note, that you use arrays or objects as key in JS-YAML. JS does not allow objects or arrays as keys, and stringifies (by calling `toString()` method) them at the moment of adding them. ``` yaml --- ? [ foo, bar ] : - baz ? { foo: bar } : - baz - baz ``` ``` javascript { "foo,bar": ["baz"], "[object Object]": ["baz", "baz"] } ``` Also, reading of properties on implicit block mapping keys is not supported yet. So, the following YAML document cannot be loaded. ``` yaml &anchor foo: foo: bar *anchor: duplicate key baz: bat *anchor: duplicate key ``` js-yaml for enterprise ---------------------- Available as part of the Tidelift Subscription The maintainers of js-yaml and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-js-yaml?utm_source=npm-js-yaml&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers has-unicode =========== Try to guess if your terminal supports unicode ```javascript var hasUnicode = require("has-unicode") if (hasUnicode()) { // the terminal probably has unicode support } ``` ```javascript var hasUnicode = require("has-unicode").tryHarder hasUnicode(function(unicodeSupported) { if (unicodeSupported) { // the terminal probably has unicode support } }) ``` ## Detecting Unicode What we actually detect is UTF-8 support, as that's what Node itself supports. If you have a UTF-16 locale then you won't be detected as unicode capable. ### Windows Since at least Windows 7, `cmd` and `powershell` have been unicode capable, but unfortunately even then it's not guaranteed. In many localizations it still uses legacy code pages and there's no facility short of running programs or linking C++ that will let us detect this. As such, we report any Windows installation as NOT unicode capable, and recommend that you encourage your users to override this via config. ### Unix Like Operating Systems We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient for most POSIX systems. While locale data can be put in `/etc/locale.conf` as well, AFAIK it's always copied into the environment. gauge ===== A nearly stateless terminal based horizontal gauge / progress bar. ```javascript var Gauge = require("gauge") var gauge = new Gauge() gauge.show("test", 0.20) gauge.pulse("this") gauge.hide() ``` ![](gauge-demo.gif) ### CHANGES FROM 1.x Gauge 2.x is breaking release, please see the [changelog] for details on what's changed if you were previously a user of this module. [changelog]: CHANGELOG.md ### THE GAUGE CLASS This is the typical interface to the module– it provides a pretty fire-and-forget interface to displaying your status information. ``` var Gauge = require("gauge") var gauge = new Gauge([stream], [options]) ``` * **stream** – *(optional, default STDERR)* A stream that progress bar updates are to be written to. Gauge honors backpressure and will pause most writing if it is indicated. * **options** – *(optional)* An option object. Constructs a new gauge. Gauges are drawn on a single line, and are not drawn if **stream** isn't a tty and a tty isn't explicitly provided. If **stream** is a terminal or if you pass in **tty** to **options** then we will detect terminal resizes and redraw to fit. We do this by watching for `resize` events on the tty. (To work around a bug in verisons of Node prior to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to larger window sizes will be clean, but shrinking the window will always result in some cruft. **IMPORTANT:** If you prevously were passing in a non-tty stream but you still want output (for example, a stream wrapped by the `ansi` module) then you need to pass in the **tty** option below, as `gauge` needs access to the underlying tty in order to do things like terminal resizes and terminal width detection. The **options** object can have the following properties, all of which are optional: * **updateInterval**: How often gauge updates should be drawn, in miliseconds. * **fixedFramerate**: Defaults to false on node 0.8, true on everything else. When this is true a timer is created to trigger once every `updateInterval` ms, when false, updates are printed as soon as they come in but updates more often than `updateInterval` are ignored. The reason 0.8 doesn't have this set to true is that it can't `unref` its timer and so it would stop your program from exiting– if you want to use this feature with 0.8 just make sure you call `gauge.disable()` before you expect your program to exit. * **themes**: A themeset to use when selecting the theme to use. Defaults to `gauge/themes`, see the [themes] documentation for details. * **theme**: Select a theme for use, it can be a: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. * **template**: Describes what you want your gauge to look like. The default is what npm uses. Detailed [documentation] is later in this document. * **hideCursor**: Defaults to true. If true, then the cursor will be hidden while the gauge is displayed. * **tty**: The tty that you're ultimately writing to. Defaults to the same as **stream**. This is used for detecting the width of the terminal and resizes. The width used is `tty.columns - 1`. If no tty is available then a width of `79` is assumed. * **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true the gauge starts enabled. If disabled then all update commands are ignored and no gauge will be printed until you call `.enable()`. * **Plumbing**: The class to use to actually generate the gauge for printing. This defaults to `require('gauge/plumbing')` and ordinarly you shouldn't need to override this. * **cleanupOnExit**: Defaults to true. Ordinarily we register an exit handler to make sure your cursor is turned back on and the progress bar erased when your process exits, even if you Ctrl-C out or otherwise exit unexpectedly. You can disable this and it won't register the exit handler. [has-unicode]: https://www.npmjs.com/package/has-unicode [themes]: #themes [documentation]: #templates #### `gauge.show(section | status, [completed])` The first argument is either the section, the name of the current thing contributing to progress, or an object with keys like **section**, **subsection** & **completed** (or any others you have types for in a custom template). If you don't want to update or set any of these you can pass `null` and it will be ignored. The second argument is the percent completed as a value between 0 and 1. Without it, completion is just not updated. You'll also note that completion can be passed in as part of a status object as the first argument. If both it and the completed argument are passed in, the completed argument wins. #### `gauge.hide([cb])` Removes the gauge from the terminal. Optionally, callback `cb` after IO has had an opportunity to happen (currently this just means after `setImmediate` has called back.) It turns out this is important when you're pausing the progress bar on one filehandle and printing to another– otherwise (with a big enough print) node can end up printing the "end progress bar" bits to the progress bar filehandle while other stuff is printing to another filehandle. These getting interleaved can cause corruption in some terminals. #### `gauge.pulse([subsection])` * **subsection** – *(optional)* The specific thing that triggered this pulse Spins the spinner in the gauge to show output. If **subsection** is included then it will be combined with the last name passed to `gauge.show`. #### `gauge.disable()` Hides the gauge and ignores further calls to `show` or `pulse`. #### `gauge.enable()` Shows the gauge and resumes updating when `show` or `pulse` is called. #### `gauge.isEnabled()` Returns true if the gauge is enabled. #### `gauge.setThemeset(themes)` Change the themeset to select a theme from. The same as the `themes` option used in the constructor. The theme will be reselected from this themeset. #### `gauge.setTheme(theme)` Change the active theme, will be displayed with the next show or pulse. This can be: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. #### `gauge.setTemplate(template)` Change the active template, will be displayed with the next show or pulse ### Tracking Completion If you have more than one thing going on that you want to track completion of, you may find the related [are-we-there-yet] helpful. It's `change` event can be wired up to the `show` method to get a more traditional progress bar interface. [are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet ### THEMES ``` var themes = require('gauge/themes') // fetch the default color unicode theme for this platform var ourTheme = themes({hasUnicode: true, hasColor: true}) // fetch the default non-color unicode theme for osx var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) // create a new theme based on the color ascii theme for this platform // that brackets the progress bar with arrows var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), { preProgressbar: '→', postProgressbar: '←' }) ``` The object returned by `gauge/themes` is an instance of the `ThemeSet` class. ``` var ThemeSet = require('gauge/theme-set') var themes = new ThemeSet() // or var themes = require('gauge/themes') var mythemes = themes.newThemeset() // creates a new themeset based on the default themes ``` #### themes(opts) #### themes.getDefault(opts) Theme objects are a function that fetches the default theme based on platform, unicode and color support. Options is an object with the following properties: * **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is available then a non-unicode theme will be used. * **hasColor** - If true, fetch a color theme, if no color theme is available a non-color theme will be used. * **platform** (optional) - Defaults to `process.platform`. If no platform match is available then `fallback` is used instead. If no compatible theme can be found then an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.addTheme(themeName, themeObj) #### themes.addTheme(themeName, [parentTheme], newTheme) Adds a named theme to the themeset. You can pass in either a theme object, as returned by `themes.newTheme` or the arguments you'd pass to `themes.newTheme`. #### themes.getThemeNames() Return a list of all of the names of the themes in this themeset. Suitable for use in `themes.getTheme(…)`. #### themes.getTheme(name) Returns the theme object from this theme set named `name`. If `name` does not exist in this themeset an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.setDefault([opts], themeName) `opts` is an object with the following properties. * **platform** - Defaults to `'fallback'`. If your theme is platform specific, specify that here with the platform from `process.platform`, eg, `win32`, `darwin`, etc. * **hasUnicode** - Defaults to `false`. If your theme uses unicode you should set this to true. * **hasColor** - Defaults to `false`. If your theme uses color you should set this to true. `themeName` is the name of the theme (as given to `addTheme`) to use for this set of `opts`. #### themes.newTheme([parentTheme,] newTheme) Create a new theme object based on `parentTheme`. If no `parentTheme` is provided then a minimal parentTheme that defines functions for rendering the activity indicator (spinner) and progress bar will be defined. (This fallback parent is defined in `gauge/base-theme`.) newTheme should be a bare object– we'll start by discussing the properties defined by the default themes: * **preProgressbar** - displayed prior to the progress bar, if the progress bar is displayed. * **postProgressbar** - displayed after the progress bar, if the progress bar is displayed. * **progressBarTheme** - The subtheme passed through to the progress bar renderer, it's an object with `complete` and `remaining` properties that are the strings you want repeated for those sections of the progress bar. * **activityIndicatorTheme** - The theme for the activity indicator (spinner), this can either be a string, in which each character is a different step, or an array of strings. * **preSubsection** - Displayed as a separator between the `section` and `subsection` when the latter is printed. More generally, themes can have any value that would be a valid value when rendering templates. The properties in the theme are used when their name matches a type in the template. Their values can be: * **strings & numbers** - They'll be included as is * **function (values, theme, width)** - Should return what you want in your output. *values* is an object with values provided via `gauge.show`, *theme* is the theme specific to this item (see below) or this theme object, and *width* is the number of characters wide your result should be. There are a couple of special prefixes: * **pre** - Is shown prior to the property, if its displayed. * **post** - Is shown after the property, if its displayed. And one special suffix: * **Theme** - Its value is passed to a function-type item as the theme. #### themes.addToAllThemes(theme) This *mixes-in* `theme` into all themes currently defined. It also adds it to the default parent theme for this themeset, so future themes added to this themeset will get the values from `theme` by default. #### themes.newThemeset() Copy the current themeset into a new one. This allows you to easily inherit one themeset from another. ### TEMPLATES A template is an array of objects and strings that, after being evaluated, will be turned into the gauge line. The default template is: ```javascript [ {type: 'progressbar', length: 20}, {type: 'activityIndicator', kerning: 1, length: 1}, {type: 'section', kerning: 1, default: ''}, {type: 'subsection', kerning: 1, default: ''} ] ``` The various template elements can either be **plain strings**, in which case they will be be included verbatum in the output, or objects with the following properties: * *type* can be any of the following plus any keys you pass into `gauge.show` plus any keys you have on a custom theme. * `section` – What big thing you're working on now. * `subsection` – What component of that thing is currently working. * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` from your active theme. * `progressbar` – A progress bar representing your current `completed` using the `progressbarTheme` from your active theme. * *kerning* – Number of spaces that must be between this item and other items, if this item is displayed at all. * *maxLength* – The maximum length for this element. If its value is longer it will be truncated. * *minLength* – The minimum length for this element. If its value is shorter it will be padded according to the *align* value. * *align* – (Default: left) Possible values "left", "right" and "center". Works as you'd expect from word processors. * *length* – Provides a single value for both *minLength* and *maxLength*. If both *length* and *minLength or *maxLength* are specifed then the latter take precedence. * *value* – A literal value to use for this template item. * *default* – A default value to use for this template item if a value wasn't otherwise passed in. ### PLUMBING This is the super simple, assume nothing, do no magic internals used by gauge to implement its ordinary interface. ``` var Plumbing = require('gauge/plumbing') var gauge = new Plumbing(theme, template, width) ``` * **theme**: The theme to use. * **template**: The template to use. * **width**: How wide your gauge should be #### `gauge.setTheme(theme)` Change the active theme. #### `gauge.setTemplate(template)` Change the active template. #### `gauge.setWidth(width)` Change the width to render at. #### `gauge.hide()` Return the string necessary to hide the progress bar #### `gauge.hideCursor()` Return a string to hide the cursor. #### `gauge.showCursor()` Return a string to show the cursor. #### `gauge.show(status)` Using `status` for values, render the provided template with the theme and return a string that is suitable for printing to update the gauge. # fastq ![ci][ci-url] [![npm version][npm-badge]][npm-url] [![Dependency Status][david-badge]][david-url] Fast, in memory work queue. Benchmarks (1 million tasks): * setImmediate: 812ms * fastq: 854ms * async.queue: 1298ms * neoAsync.queue: 1249ms Obtained on node 12.16.1, on a dedicated server. If you need zero-overhead series function call, check out [fastseries](http://npm.im/fastseries). For zero-overhead parallel function call, check out [fastparallel](http://npm.im/fastparallel). [![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard) * <a href="#install">Installation</a> * <a href="#usage">Usage</a> * <a href="#api">API</a> * <a href="#license">Licence &amp; copyright</a> ## Install `npm i fastq --save` ## Usage (callback API) ```js 'use strict' const queue = require('fastq')(worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log('the result is', result) }) function worker (arg, cb) { cb(null, arg * 2) } ``` ## Usage (promise API) ```js const queue = require('fastq').promise(worker, 1) async function worker (arg) { return arg * 2 } async function run () { const result = await queue.push(42) console.log('the result is', result) } run() ``` ### Setting "this" ```js 'use strict' const that = { hello: 'world' } const queue = require('fastq')(that, worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log(this) console.log('the result is', result) }) function worker (arg, cb) { console.log(this) cb(null, arg * 2) } ``` ### Using with TypeScript (callback API) ```ts 'use strict' import * as fastq from "fastq"; import type { queue, done } from "fastq"; type Task = { id: number } const q: queue<Task> = fastq(worker, 1) q.push({ id: 42}) function worker (arg: Task, cb: done) { console.log(arg.id) cb(null) } ``` ### Using with TypeScript (promise API) ```ts 'use strict' import * as fastq from "fastq"; import type { queueAsPromised } from "fastq"; type Task = { id: number } const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1) q.push({ id: 42}).catch((err) => console.error(err)) async function asyncWorker (arg: Task): Promise<void> { // No need for a try-catch block, fastq handles errors automatically console.log(arg.id) } ``` ## API * <a href="#fastqueue"><code>fastqueue()</code></a> * <a href="#push"><code>queue#<b>push()</b></code></a> * <a href="#unshift"><code>queue#<b>unshift()</b></code></a> * <a href="#pause"><code>queue#<b>pause()</b></code></a> * <a href="#resume"><code>queue#<b>resume()</b></code></a> * <a href="#idle"><code>queue#<b>idle()</b></code></a> * <a href="#length"><code>queue#<b>length()</b></code></a> * <a href="#getQueue"><code>queue#<b>getQueue()</b></code></a> * <a href="#kill"><code>queue#<b>kill()</b></code></a> * <a href="#killAndDrain"><code>queue#<b>killAndDrain()</b></code></a> * <a href="#error"><code>queue#<b>error()</b></code></a> * <a href="#concurrency"><code>queue#<b>concurrency</b></code></a> * <a href="#drain"><code>queue#<b>drain</b></code></a> * <a href="#empty"><code>queue#<b>empty</b></code></a> * <a href="#saturated"><code>queue#<b>saturated</b></code></a> * <a href="#promise"><code>fastqueue.promise()</code></a> ------------------------------------------------------- <a name="fastqueue"></a> ### fastqueue([that], worker, concurrency) Creates a new queue. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. * `concurrency`, number of concurrent tasks that could be executed in parallel. ------------------------------------------------------- <a name="push"></a> ### queue.push(task, done) Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="unshift"></a> ### queue.unshift(task, done) Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="pause"></a> ### queue.pause() Pause the processing of tasks. Currently worked tasks are not stopped. ------------------------------------------------------- <a name="resume"></a> ### queue.resume() Resume the processing of tasks. ------------------------------------------------------- <a name="idle"></a> ### queue.idle() Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. ------------------------------------------------------- <a name="length"></a> ### queue.length() Returns the number of tasks waiting to be processed (in the queue). ------------------------------------------------------- <a name="getQueue"></a> ### queue.getQueue() Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks ------------------------------------------------------- <a name="kill"></a> ### queue.kill() Removes all tasks waiting to be processed, and reset `drain` to an empty function. ------------------------------------------------------- <a name="killAndDrain"></a> ### queue.killAndDrain() Same than `kill` but the `drain` function will be called before reset to empty. ------------------------------------------------------- <a name="error"></a> ### queue.error(handler) Set a global error handler. `handler(err, task)` will be called when any of the tasks return an error. ------------------------------------------------------- <a name="concurrency"></a> ### queue.concurrency Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. ------------------------------------------------------- <a name="drain"></a> ### queue.drain Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. ------------------------------------------------------- <a name="empty"></a> ### queue.empty Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. ------------------------------------------------------- <a name="saturated"></a> ### queue.saturated Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. ------------------------------------------------------- <a name="promise"></a> ### fastqueue.promise([that], worker(arg), concurrency) Creates a new queue with `Promise` apis. It also offers all the methods and properties of the object returned by [`fastqueue`](#fastqueue) with the modified [`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. Node v10+ is required to use the promisified version. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. It MUST return a `Promise`. * `concurrency`, number of concurrent tasks that could be executed in parallel. <a name="pushPromise"></a> #### queue.push(task) => Promise Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="unshiftPromise"></a> #### queue.unshift(task) => Promise Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="drained"></a> #### queue.drained() => Promise Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. This promise could be ignored as it will not lead to a `'unhandledRejection'`. ## License ISC [ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg [npm-badge]: https://badge.fury.io/js/fastq.svg [npm-url]: https://badge.fury.io/js/fastq [david-badge]: https://david-dm.org/mcollina/fastq.svg [david-url]: https://david-dm.org/mcollina/fastq # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) Minimal async jobs utility library, with streams support. [![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) [![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) [![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) [![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) <!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) --> AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. | compression | size | | :----------------- | -------: | | asynckit.js | 12.34 kB | | asynckit.min.js | 4.11 kB | | asynckit.min.js.gz | 1.47 kB | ## Install ```sh $ npm install --save asynckit ``` ## Examples ### Parallel Jobs Runs iterator over provided array in parallel. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will terminate rest of the active jobs (if abort function is provided) and return error along with salvaged data to the main callback function. #### Input Array ```javascript var parallel = require('asynckit').parallel , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , target = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // async job accepts one element from the array // and a callback function function asyncJob(item, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var parallel = require('asynckit/parallel') , assert = require('assert') ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] , target = [] , keys = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); assert.deepEqual(keys, expectedKeys); }); // supports full value, key, callback (shortcut) interface function asyncJob(item, key, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { keys.push(key); target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). ### Serial Jobs Runs iterator over provided array sequentially. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will not proceed to the rest of the items in the list and return error along with salvaged data to the main callback function. #### Input Array ```javascript var serial = require('asynckit/serial') , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // extended interface (item, key, callback) // also supported for arrays function asyncJob(item, key, cb) { target.push(key); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var serial = require('asynckit').serial , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // shortcut interface (item, callback) // works for object as well as for the arrays function asyncJob(item, cb) { target.push(item); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). _Note: Since _object_ is an _unordered_ collection of properties, it may produce unexpected results with sequential iterations. Whenever order of the jobs' execution is important please use `serialOrdered` method._ ### Ordered Serial Iterations TBD For example [compare-property](compare-property) package. ### Streaming interface TBD ## Want to Know More? More examples can be found in [test folder](test/). Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. ## License AsyncKit is licensed under the MIT license. # simple-get [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [ci-image]: https://img.shields.io/github/workflow/status/feross/simple-get/ci/master [ci-url]: https://github.com/feross/simple-get/actions [npm-image]: https://img.shields.io/npm/v/simple-get.svg [npm-url]: https://npmjs.org/package/simple-get [downloads-image]: https://img.shields.io/npm/dm/simple-get.svg [downloads-url]: https://npmjs.org/package/simple-get [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Simplest way to make http get requests ## features This module is the lightest possible wrapper on top of node.js `http`, but supporting these essential features: - follows redirects - automatically handles gzip/deflate responses - supports HTTPS - supports specifying a timeout - supports convenience `url` key so there's no need to use `url.parse` on the url when specifying options - composes well with npm packages for features like cookies, proxies, form data, & OAuth All this in < 100 lines of code. ## install ``` npm install simple-get ``` ## usage Note, all these examples also work in the browser with [browserify](http://browserify.org/). ### simple GET request Doesn't get easier than this: ```js const get = require('simple-get') get('http://example.com', function (err, res) { if (err) throw err console.log(res.statusCode) // 200 res.pipe(process.stdout) // `res` is a stream }) ``` ### even simpler GET request If you just want the data, and don't want to deal with streams: ```js const get = require('simple-get') get.concat('http://example.com', function (err, res, data) { if (err) throw err console.log(res.statusCode) // 200 console.log(data) // Buffer('this is the server response') }) ``` ### POST, PUT, PATCH, HEAD, DELETE support For `POST`, call `get.post` or use option `{ method: 'POST' }`. ```js const get = require('simple-get') const opts = { url: 'http://example.com', body: 'this is the POST body' } get.post(opts, function (err, res) { if (err) throw err res.pipe(process.stdout) // `res` is a stream }) ``` #### A more complex example: ```js const get = require('simple-get') get({ url: 'http://example.com', method: 'POST', body: 'this is the POST body', // simple-get accepts all options that node.js `http` accepts // See: http://nodejs.org/api/http.html#http_http_request_options_callback headers: { 'user-agent': 'my cool app' } }, function (err, res) { if (err) throw err // All properties/methods from http.IncomingResponse are available, // even if a gunzip/inflate transform stream was returned. // See: http://nodejs.org/api/http.html#http_http_incomingmessage res.setTimeout(10000) console.log(res.headers) res.on('data', function (chunk) { // `chunk` is the decoded response, after it's been gunzipped or inflated // (if applicable) console.log('got a chunk of the response: ' + chunk) })) }) ``` ### JSON You can serialize/deserialize request and response with JSON: ```js const get = require('simple-get') const opts = { method: 'POST', url: 'http://example.com', body: { key: 'value' }, json: true } get.concat(opts, function (err, res, data) { if (err) throw err console.log(data.key) // `data` is an object }) ``` ### Timeout You can set a timeout (in milliseconds) on the request with the `timeout` option. If the request takes longer than `timeout` to complete, then the entire request will fail with an `Error`. ```js const get = require('simple-get') const opts = { url: 'http://example.com', timeout: 2000 // 2 second timeout } get(opts, function (err, res) {}) ``` ### One Quick Tip It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. ```js const get = require('simple-get') const pkg = require('./package.json') get('http://example.com', { headers: { 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)` } }) ``` ### Proxies You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies: ```js const get = require('simple-get') const tunnel = require('tunnel') const opts = { url: 'http://example.com', agent: tunnel.httpOverHttp({ proxy: { host: 'localhost' } }) } get(opts, function (err, res) {}) ``` ### Cookies You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request: ```js const get = require('simple-get') const cookie = require('cookie') const opts = { url: 'http://example.com', headers: { cookie: cookie.serialize('foo', 'bar') } } get(opts, function (err, res) {}) ``` ### Form data You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data: ```js const fs = require('fs') const get = require('simple-get') const FormData = require('form-data') const form = new FormData() form.append('my_file', fs.createReadStream('/foo/bar.jpg')) const opts = { url: 'http://example.com', body: form } get.post(opts, function (err, res) {}) ``` #### Or, include `application/x-www-form-urlencoded` form data manually: ```js const get = require('simple-get') const opts = { url: 'http://example.com', form: { key: 'value' } } get.post(opts, function (err, res) {}) ``` ### Specifically disallowing redirects ```js const get = require('simple-get') const opts = { url: 'http://example.com/will-redirect-elsewhere', followRedirects: false } // res.statusCode will be 301, no error thrown get(opts, function (err, res) {}) ``` ### Basic Auth ```js const user = 'someuser' const pass = 'pa$$word' const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64') get('http://example.com', { headers: { authorization: `Basic ${encodedAuth}` } }) ``` ### OAuth You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request: ```js const get = require('simple-get') const crypto = require('crypto') const OAuth = require('oauth-1.0a') const oauth = OAuth({ consumer: { key: process.env.CONSUMER_KEY, secret: process.env.CONSUMER_SECRET }, signature_method: 'HMAC-SHA1', hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64') }) const token = { key: process.env.ACCESS_TOKEN, secret: process.env.ACCESS_TOKEN_SECRET } const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' const opts = { url: url, headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)), json: true } get(opts, function (err, res) {}) ``` ### Throttle requests You can use [limiter](https://github.com/jhurliman/node-rate-limiter) to throttle requests. This is useful when calling an API that is rate limited. ```js const simpleGet = require('simple-get') const RateLimiter = require('limiter').RateLimiter const limiter = new RateLimiter(1, 'second') const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb)) get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb)) var opts = { url: 'http://example.com' } get.concat(opts, processResult) get.concat(opts, processResult) function processResult (err, res, data) { if (err) throw err console.log(data.toString()) } ``` ## license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). Deep Extend =========== Recursive object extending. [![Build Status](https://api.travis-ci.org/unclechu/node-deep-extend.svg?branch=master)](https://travis-ci.org/unclechu/node-deep-extend) [![NPM](https://nodei.co/npm/deep-extend.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/deep-extend/) Install ------- ```bash $ npm install deep-extend ``` Usage ----- ```javascript var deepExtend = require('deep-extend'); var obj1 = { a: 1, b: 2, d: { a: 1, b: [], c: { test1: 123, test2: 321 } }, f: 5, g: 123, i: 321, j: [1, 2] }; var obj2 = { b: 3, c: 5, d: { b: { first: 'one', second: 'two' }, c: { test2: 222 } }, e: { one: 1, two: 2 }, f: [], g: (void 0), h: /abc/g, i: null, j: [3, 4] }; deepExtend(obj1, obj2); console.log(obj1); /* { a: 1, b: 3, d: { a: 1, b: { first: 'one', second: 'two' }, c: { test1: 123, test2: 222 } }, f: [], g: undefined, c: 5, e: { one: 1, two: 2 }, h: /abc/g, i: null, j: [3, 4] } */ ``` Unit testing ------------ ```bash $ npm test ``` Changelog --------- [CHANGELOG.md](./CHANGELOG.md) Any issues? ----------- Please, report about issues [here](https://github.com/unclechu/node-deep-extend/issues). License ------- [MIT](./LICENSE) # queue-microtask [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [ci-image]: https://img.shields.io/github/workflow/status/feross/queue-microtask/ci/master [ci-url]: https://github.com/feross/queue-microtask/actions [npm-image]: https://img.shields.io/npm/v/queue-microtask.svg [npm-url]: https://npmjs.org/package/queue-microtask [downloads-image]: https://img.shields.io/npm/dm/queue-microtask.svg [downloads-url]: https://npmjs.org/package/queue-microtask [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### fast, tiny [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) shim for modern engines - Use [`queueMicrotask`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/queueMicrotask) in all modern JS engines. - No dependencies. Less than 10 lines. No shims or complicated fallbacks. - Optimal performance in all modern environments - Uses `queueMicrotask` in modern environments - Fallback to `Promise.resolve().then(fn)` in Node.js 10 and earlier, and old browsers (same performance as `queueMicrotask`) ## install ``` npm install queue-microtask ``` ## usage ```js const queueMicrotask = require('queue-microtask') queueMicrotask(() => { /* this will run soon */ }) ``` ## What is `queueMicrotask` and why would one use it? The `queueMicrotask` function is a WHATWG standard. It queues a microtask to be executed prior to control returning to the event loop. A microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the event loop. The code `queueMicrotask(fn)` is equivalent to the code `Promise.resolve().then(fn)`. It is also very similar to [`process.nextTick(fn)`](https://nodejs.org/api/process.html#process_process_nexttick_callback_args) in Node. Using microtasks lets code run without interfering with any other, potentially higher priority, code that is pending, but before the JS engine regains control over the execution context. See the [spec](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#microtask-queuing) or [Node documentation](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback) for more information. ## Who is this package for? This package allows you to use `queueMicrotask` safely in all modern JS engines. Use it if you prioritize small JS bundle size over support for old browsers. If you just need to support Node 12 and later, use `queueMicrotask` directly. If you need to support all versions of Node, use this package. ## Why not use `process.nextTick`? In Node, `queueMicrotask` and `process.nextTick` are [essentially equivalent](https://nodejs.org/api/globals.html#globals_queuemicrotask_callback), though there are [subtle differences](https://github.com/YuzuJS/setImmediate#macrotasks-and-microtasks) that don't matter in most situations. You can think of `queueMicrotask` as a standardized version of `process.nextTick` that works in the browser. No need to rely on your browser bundler to shim `process` for the browser environment. ## Why not use `setTimeout(fn, 0)`? This approach is the most compatible, but it has problems. Modern browsers throttle timers severely, so `setTimeout(…, 0)` usually takes at least 4ms to run. Furthermore, the throttling gets even worse if the page is backgrounded. If you have many `setTimeout` calls, then this can severely limit the performance of your program. ## Why not use a microtask library like [`immediate`](https://www.npmjs.com/package/immediate) or [`asap`](https://www.npmjs.com/package/asap)? These packages are great! However, if you prioritize small JS bundle size over optimal performance in old browsers then you may want to consider this package. This package (`queue-microtask`) is four times smaller than `immediate`, twice as small as `asap`, and twice as small as using `process.nextTick` and letting the browser bundler shim it automatically. Note: This package throws an exception in JS environments which lack `Promise` support -- which are usually very old browsers and Node.js versions. Since the `queueMicrotask` API is supported in Node.js, Chrome, Firefox, Safari, Opera, and Edge, **the vast majority of users will get optimal performance**. Any JS environment with `Promise`, which is almost all of them, also get optimal performance. If you need support for JS environments which lack `Promise` support, use one of the alternative packages. ## What is a shim? > In computer programming, a shim is a library that transparently intercepts API calls and changes the arguments passed, handles the operation itself or redirects the operation elsewhere. – [Wikipedia](https://en.wikipedia.org/wiki/Shim_(computing)) This package could also be described as a "ponyfill". > A ponyfill is almost the same as a polyfill, but not quite. Instead of patching functionality for older browsers, a ponyfill provides that functionality as a standalone module you can use. – [PonyFoo](https://ponyfoo.com/articles/polyfills-or-ponyfills) ## API ### `queueMicrotask(fn)` The `queueMicrotask()` method queues a microtask. The `fn` argument is a function to be executed after all pending tasks have completed but before yielding control to the browser's event loop. ## license MIT. Copyright (c) [Feross Aboukhadijeh](https://feross.org). # JSON5 – JSON for Humans [![Build Status](https://travis-ci.com/json5/json5.svg)][Build Status] [![Coverage Status](https://coveralls.io/repos/github/json5/json5/badge.svg)][Coverage Status] The JSON5 Data Interchange Format (JSON5) is a superset of [JSON] that aims to alleviate some of the limitations of JSON by expanding its syntax to include some productions from [ECMAScript 5.1]. This JavaScript library is the official reference implementation for JSON5 parsing and serialization libraries. [Build Status]: https://travis-ci.com/json5/json5 [Coverage Status]: https://coveralls.io/github/json5/json5 [JSON]: https://tools.ietf.org/html/rfc7159 [ECMAScript 5.1]: https://www.ecma-international.org/ecma-262/5.1/ ## Summary of Features The following ECMAScript 5.1 features, which are not supported in JSON, have been extended to JSON5. ### Objects - Object keys may be an ECMAScript 5.1 _[IdentifierName]_. - Objects may have a single trailing comma. ### Arrays - Arrays may have a single trailing comma. ### Strings - Strings may be single quoted. - Strings may span multiple lines by escaping new line characters. - Strings may include character escapes. ### Numbers - Numbers may be hexadecimal. - Numbers may have a leading or trailing decimal point. - Numbers may be [IEEE 754] positive infinity, negative infinity, and NaN. - Numbers may begin with an explicit plus sign. ### Comments - Single and multi-line comments are allowed. ### White Space - Additional white space characters are allowed. [IdentifierName]: https://www.ecma-international.org/ecma-262/5.1/#sec-7.6 [IEEE 754]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 ## Short Example ```js { // comments unquoted: 'and you can quote me on that', singleQuotes: 'I can use "double quotes" here', lineBreaks: "Look, Mom! \ No \\n's!", hexadecimal: 0xdecaf, leadingDecimalPoint: .8675309, andTrailing: 8675309., positiveSign: +1, trailingComma: 'in objects', andIn: ['arrays',], "backwardsCompatible": "with JSON", } ``` ## Specification For a detailed explanation of the JSON5 format, please read the [official specification](https://json5.github.io/json5-spec/). ## Installation ### Node.js ```sh npm install json5 ``` ```js const JSON5 = require('json5') ``` ### Browsers ```html <script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script> ``` This will create a global `JSON5` variable. ## API The JSON5 API is compatible with the [JSON API]. [JSON API]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON ### JSON5.parse() Parses a JSON5 string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. #### Syntax JSON5.parse(text[, reviver]) #### Parameters - `text`: The string to parse as JSON5. - `reviver`: If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. #### Return value The object corresponding to the given JSON5 text. ### JSON5.stringify() Converts a JavaScript value to a JSON5 string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified. #### Syntax JSON5.stringify(value[, replacer[, space]]) JSON5.stringify(value[, options]) #### Parameters - `value`: The value to convert to a JSON5 string. - `replacer`: A function that alters the behavior of the stringification process, 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 JSON5 string. If this value is null or not provided, all properties of the object are included in the resulting JSON5 string. - `space`: A String or Number object that's used to insert white space into the output JSON5 string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used. If white space is used, trailing commas will be used in objects and arrays. - `options`: An object with the following properties: - `replacer`: Same as the `replacer` parameter. - `space`: Same as the `space` parameter. - `quote`: A String representing the quote character to use when serializing strings. #### Return value A JSON5 string representing the value. ### Node.js `require()` JSON5 files When using Node.js, you can `require()` JSON5 files by adding the following statement. ```js require('json5/lib/register') ``` Then you can load a JSON5 file with a Node.js `require()` statement. For example: ```js const config = require('./config.json5') ``` ## CLI Since JSON is more widely used than JSON5, this package includes a CLI for converting JSON5 to JSON and for validating the syntax of JSON5 documents. ### Installation ```sh npm install --global json5 ``` ### Usage ```sh json5 [options] <file> ``` If `<file>` is not provided, then STDIN is used. #### Options: - `-s`, `--space`: The number of spaces to indent or `t` for tabs - `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT - `-v`, `--validate`: Validate JSON5 but do not output JSON - `-V`, `--version`: Output the version number - `-h`, `--help`: Output usage information ## Contributing ### Development ```sh git clone https://github.com/json5/json5 cd json5 npm install ``` When contributing code, please write relevant tests and run `npm test` and `npm run lint` before submitting pull requests. Please use an editor that supports [EditorConfig](http://editorconfig.org/). ### Issues To report bugs or request features regarding the JSON5 data format, please submit an issue to the [official specification repository](https://github.com/json5/json5-spec). To report bugs or request features regarding the JavaScript implementation of JSON5, please submit an issue to this repository. ## License MIT. See [LICENSE.md](./LICENSE.md) for details. ## Credits [Assem Kishore](https://github.com/aseemk) founded this project. [Michael Bolin](http://bolinfest.com/) independently arrived at and published some of these same ideas with awesome explanations and detail. Recommended reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html) [Douglas Crockford](http://www.crockford.com/) of course designed and built JSON, but his state machine diagrams on the [JSON website](http://json.org/), as cheesy as it may sound, gave us motivation and confidence that building a new parser to implement these ideas was within reach! The original implementation of JSON5 was also modeled directly off of Doug’s open-source [json_parse.js] parser. We’re grateful for that clean and well-documented code. [json_parse.js]: https://github.com/douglascrockford/JSON-js/blob/03157639c7a7cddd2e9f032537f346f1a87c0f6d/json_parse.js [Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific supporter, contributing multiple patches and ideas. [Andrew Eisenberg](https://github.com/aeisenberg) contributed the original `stringify` method. [Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely with ES5, wrote the official JSON5 specification, completely rewrote the codebase from the ground up, and is actively maintaining this project. node-fetch ========== [![npm version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![coverage status][codecov-image]][codecov-url] [![install size][install-size-image]][install-size-url] [![Discord][discord-image]][discord-url] A light-weight module that brings `window.fetch` to Node.js (We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) [![Backers][opencollective-image]][opencollective-url] <!-- TOC --> - [Motivation](#motivation) - [Features](#features) - [Difference from client-side fetch](#difference-from-client-side-fetch) - [Installation](#installation) - [Loading and configuring the module](#loading-and-configuring-the-module) - [Common Usage](#common-usage) - [Plain text or HTML](#plain-text-or-html) - [JSON](#json) - [Simple Post](#simple-post) - [Post with JSON](#post-with-json) - [Post with form parameters](#post-with-form-parameters) - [Handling exceptions](#handling-exceptions) - [Handling client and server errors](#handling-client-and-server-errors) - [Advanced Usage](#advanced-usage) - [Streams](#streams) - [Buffer](#buffer) - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) - [Extract Set-Cookie Header](#extract-set-cookie-header) - [Post data using a file stream](#post-data-using-a-file-stream) - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) - [API](#api) - [fetch(url[, options])](#fetchurl-options) - [Options](#options) - [Class: Request](#class-request) - [Class: Response](#class-response) - [Class: Headers](#class-headers) - [Interface: Body](#interface-body) - [Class: FetchError](#class-fetcherror) - [License](#license) - [Acknowledgement](#acknowledgement) <!-- /TOC --> ## Motivation Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). ## Features - Stay consistent with `window.fetch` API. - Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. - Use native promise but allow substituting it with [insert your favorite promise library]. - Use native Node streams for body on both request and response. - Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. - Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. ## Difference from client-side fetch - See [Known Differences](LIMITS.md) for details. - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. - Pull requests are welcomed too! ## Installation Current stable release (`2.x`) ```sh $ npm install node-fetch ``` ## Loading and configuring the module We suggest you load the module via `require` until the stabilization of ES modules in node: ```js const fetch = require('node-fetch'); ``` If you are using a Promise library other than native, set it through `fetch.Promise`: ```js const Bluebird = require('bluebird'); fetch.Promise = Bluebird; ``` ## Common Usage NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. #### Plain text or HTML ```js fetch('https://github.com/') .then(res => res.text()) .then(body => console.log(body)); ``` #### JSON ```js fetch('https://api.github.com/users/github') .then(res => res.json()) .then(json => console.log(json)); ``` #### Simple Post ```js fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) .then(res => res.json()) // expecting a json response .then(json => console.log(json)); ``` #### Post with JSON ```js const body = { a: 1 }; fetch('https://httpbin.org/post', { method: 'post', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' }, }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form parameters `URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: ```js const { URLSearchParams } = require('url'); const params = new URLSearchParams(); params.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: params }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Handling exceptions NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. ```js fetch('https://domain.invalid/') .catch(err => console.error(err)); ``` #### Handling client and server errors It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: ```js function checkStatus(res) { if (res.ok) { // res.status >= 200 && res.status < 300 return res; } else { throw MyCustomError(res.statusText); } } fetch('https://httpbin.org/status/400') .then(checkStatus) .then(res => console.log('will not get here...')) ``` ## Advanced Usage #### Streams The "Node.js way" is to use streams when possible: ```js fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => { const dest = fs.createWriteStream('./octocat.png'); res.body.pipe(dest); }); ``` #### Buffer If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) ```js const fileType = require('file-type'); fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => res.buffer()) .then(buffer => fileType(buffer)) .then(type => { /* ... */ }); ``` #### Accessing Headers and other Meta data ```js fetch('https://github.com/') .then(res => { console.log(res.ok); console.log(res.status); console.log(res.statusText); console.log(res.headers.raw()); console.log(res.headers.get('content-type')); }); ``` #### Extract Set-Cookie Header Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. ```js fetch(url).then(res => { // returns an array of values, instead of a string of comma-separated values console.log(res.headers.raw()['set-cookie']); }); ``` #### Post data using a file stream ```js const { createReadStream } = require('fs'); const stream = createReadStream('input.txt'); fetch('https://httpbin.org/post', { method: 'POST', body: stream }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form-data (detect multipart) ```js const FormData = require('form-data'); const form = new FormData(); form.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: form }) .then(res => res.json()) .then(json => console.log(json)); // OR, using custom headers // NOTE: getHeaders() is non-standard API const form = new FormData(); form.append('a', 1); const options = { method: 'POST', body: form, headers: form.getHeaders() } fetch('https://httpbin.org/post', options) .then(res => res.json()) .then(json => console.log(json)); ``` #### Request cancellation with AbortSignal > NOTE: You may cancel streamed requests only on Node >= v8.0.0 You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). An example of timing out a request after 150ms could be achieved as the following: ```js import AbortController from 'abort-controller'; const controller = new AbortController(); const timeout = setTimeout( () => { controller.abort(); }, 150, ); fetch(url, { signal: controller.signal }) .then(res => res.json()) .then( data => { useData(data) }, err => { if (err.name === 'AbortError') { // request was aborted } }, ) .finally(() => { clearTimeout(timeout); }); ``` See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. ## API ### fetch(url[, options]) - `url` A string representing the URL for fetching - `options` [Options](#fetch-options) for the HTTP(S) request - Returns: <code>Promise&lt;[Response](#class-response)&gt;</code> Perform an HTTP(S) fetch. `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. <a id="fetch-options"></a> ### Options The default values are shown after each option key. ```js { // These properties are part of the Fetch Standard method: 'GET', headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect signal: null, // pass an instance of AbortSignal to optionally abort requests // The following properties are node-fetch extensions follow: 20, // maximum redirect count. 0 to not follow redirect timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. compress: true, // support gzip/deflate content encoding. false to disable size: 0, // maximum response body size in bytes. 0 to disable agent: null // http(s).Agent instance or function that returns an instance (see below) } ``` ##### Default Headers If no values are set, the following request headers will be sent automatically: Header | Value ------------------- | -------------------------------------------------------- `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ `Accept` | `*/*` `Connection` | `close` _(when no `options.agent` is present)_ `Content-Length` | _(automatically calculated, if possible)_ `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ `User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` Note: when `body` is a `Stream`, `Content-Length` is not set automatically. ##### Custom Agent The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: - Support self-signed certificate - Use only IPv4 or IPv6 - Custom DNS Lookup See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. ```js const httpAgent = new http.Agent({ keepAlive: true }); const httpsAgent = new https.Agent({ keepAlive: true }); const options = { agent: function (_parsedURL) { if (_parsedURL.protocol == 'http:') { return httpAgent; } else { return httpsAgent; } } } ``` <a id="class-request"></a> ### Class: Request An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. Due to the nature of Node.js, the following properties are not implemented at this moment: - `type` - `destination` - `referrer` - `referrerPolicy` - `mode` - `credentials` - `cache` - `integrity` - `keepalive` The following node-fetch extension properties are provided: - `follow` - `compress` - `counter` - `agent` See [options](#fetch-options) for exact meaning of these extensions. #### new Request(input[, options]) <small>*(spec-compliant)*</small> - `input` A string representing a URL, or another `Request` (which will be cloned) - `options` [Options][#fetch-options] for the HTTP(S) request Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. <a id="class-response"></a> ### Class: Response An HTTP(S) response. This class implements the [Body](#iface-body) interface. The following properties are not implemented in node-fetch at this moment: - `Response.error()` - `Response.redirect()` - `type` - `trailer` #### new Response([body[, options]]) <small>*(spec-compliant)*</small> - `body` A `String` or [`Readable` stream][node-readable] - `options` A [`ResponseInit`][response-init] options dictionary Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. #### response.ok <small>*(spec-compliant)*</small> Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. #### response.redirected <small>*(spec-compliant)*</small> Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. <a id="class-headers"></a> ### Class: Headers This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. #### new Headers([init]) <small>*(spec-compliant)*</small> - `init` Optional argument to pre-fill the `Headers` object Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. ```js // Example adapted from https://fetch.spec.whatwg.org/#example-headers-class const meta = { 'Content-Type': 'text/xml', 'Breaking-Bad': '<3' }; const headers = new Headers(meta); // The above is equivalent to const meta = [ [ 'Content-Type', 'text/xml' ], [ 'Breaking-Bad', '<3' ] ]; const headers = new Headers(meta); // You can in fact use any iterable objects, like a Map or even another Headers const meta = new Map(); meta.set('Content-Type', 'text/xml'); meta.set('Breaking-Bad', '<3'); const headers = new Headers(meta); const copyOfHeaders = new Headers(headers); ``` <a id="iface-body"></a> ### Interface: Body `Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. The following methods are not yet implemented in node-fetch at this moment: - `formData()` #### body.body <small>*(deviation from spec)*</small> * Node.js [`Readable` stream][node-readable] Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. #### body.bodyUsed <small>*(spec-compliant)*</small> * `Boolean` A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. #### body.arrayBuffer() #### body.blob() #### body.json() #### body.text() <small>*(spec-compliant)*</small> * Returns: <code>Promise</code> Consume the body and return a promise that will resolve to one of these formats. #### body.buffer() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;Buffer&gt;</code> Consume the body and return a promise that will resolve to a Buffer. #### body.textConverted() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;String&gt;</code> Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. (This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) <a id="class-fetcherror"></a> ### Class: FetchError <small>*(node-fetch extension)*</small> An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. <a id="class-aborterror"></a> ### Class: AbortError <small>*(node-fetch extension)*</small> An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. ## Acknowledgement Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. `node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). ## License MIT [npm-image]: https://flat.badgen.net/npm/v/node-fetch [npm-url]: https://www.npmjs.com/package/node-fetch [travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch [travis-url]: https://travis-ci.org/bitinn/node-fetch [codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master [codecov-url]: https://codecov.io/gh/bitinn/node-fetch [install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch [install-size-url]: https://packagephobia.now.sh/result?p=node-fetch [discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square [discord-url]: https://discord.gg/Zxbndcm [opencollective-image]: https://opencollective.com/node-fetch/backers.svg [opencollective-url]: https://opencollective.com/node-fetch [whatwg-fetch]: https://fetch.spec.whatwg.org/ [response-init]: https://fetch.spec.whatwg.org/#responseinit [node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams [mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers [LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md [ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md [UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md # http-errors [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][node-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] Create HTTP errors for Express, Koa, Connect, etc. with ease. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install http-errors ``` ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ## API This is the current API, currently extracted from Koa and subject to change. ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ### createError([status], [message], [properties]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ### createError([status], [error], [properties]) Extend the given `error` object with `createError.HttpError` properties. This will not alter the inheritance of the given `error` object, and the modified `error` object is the return value. <!-- eslint-disable no-redeclare --> ```js fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` - `status` - the status code as a number - `error` - the error object to extend - `properties` - custom properties to attach to the object ### createError.isHttpError(val) Determine if the provided `val` is an `HttpError`. This will return `true` if the error inherits from the `HttpError` constructor of this module or matches the "duck type" for an error this module creates. All outputs from the `createError` factory will return `true` for this function, including if an non-`HttpError` was passed into the factory. ### new createError\[code || name\](\[msg]\)) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. #### List of all constructors |Status Code|Constructor Name | |-----------|-----------------------------| |400 |BadRequest | |401 |Unauthorized | |402 |PaymentRequired | |403 |Forbidden | |404 |NotFound | |405 |MethodNotAllowed | |406 |NotAcceptable | |407 |ProxyAuthenticationRequired | |408 |RequestTimeout | |409 |Conflict | |410 |Gone | |411 |LengthRequired | |412 |PreconditionFailed | |413 |PayloadTooLarge | |414 |URITooLong | |415 |UnsupportedMediaType | |416 |RangeNotSatisfiable | |417 |ExpectationFailed | |418 |ImATeapot | |421 |MisdirectedRequest | |422 |UnprocessableEntity | |423 |Locked | |424 |FailedDependency | |425 |UnorderedCollection | |426 |UpgradeRequired | |428 |PreconditionRequired | |429 |TooManyRequests | |431 |RequestHeaderFieldsTooLarge | |451 |UnavailableForLegalReasons | |500 |InternalServerError | |501 |NotImplemented | |502 |BadGateway | |503 |ServiceUnavailable | |504 |GatewayTimeout | |505 |HTTPVersionNotSupported | |506 |VariantAlsoNegotiates | |507 |InsufficientStorage | |508 |LoopDetected | |509 |BandwidthLimitExceeded | |510 |NotExtended | |511 |NetworkAuthenticationRequired| ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci [ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master [coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master [node-image]: https://badgen.net/npm/node/http-errors [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/http-errors [npm-url]: https://npmjs.org/package/http-errors [npm-version-image]: https://badgen.net/npm/v/http-errors [travis-image]: https://badgen.net/travis/jshttp/http-errors/master [travis-url]: https://travis-ci.org/jshttp/http-errors # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Current Status whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). ## API ### The `URL` Constructor The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish) > Determines if an object can be used like an Array ## Example ```javascript var isArrayish = require('is-arrayish'); isArrayish([]); // true isArrayish({__proto__: []}); // true isArrayish({}); // false isArrayish({length:10}); // false ``` ## License Licensed under the [MIT License](http://opensource.org/licenses/MIT). You can find a copy of it in [LICENSE](LICENSE). # is-yarn-global [![](https://img.shields.io/travis/LitoMore/is-yarn-global/master.svg)](https://travis-ci.org/LitoMore/is-yarn-global) [![](https://img.shields.io/npm/v/is-yarn-global.svg)](https://www.npmjs.com/package/is-yarn-global) [![](https://img.shields.io/npm/l/is-yarn-global.svg)](https://github.com/LitoMore/is-yarn-global/blob/master/LICENSE) [![](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo) Check if installed by yarn globally without any `fs` calls ## Install ```bash $ npm install is-yarn-global ``` ## Usage Just require it in your package. ```javascript const isYarnGlobal = require('is-yarn-global'); console.log(isYarnGlobal()); ``` ## License MIT © [LitoMore](https://github.com/LitoMore) # is-reference Utility for determining whether an AST node is a reference. `foo` is a reference in these cases: ```js console.log( foo ); var foo; function foo () {} function bar ( foo ) {} export { foo as x }; ``` `foo` is *not* a reference in these cases: ```js var obj = { foo: 1 }; console.log( obj.foo ); export { x as foo }; ``` In all cases, `foo` is an `Identifier` node, but the two kinds must be treated differently for the purposes of scope analysis etc. (The examples are non-exhaustive.) ## Installation ```bash npm install is-reference ``` ## Usage Example using [Acorn](https://github.com/ternjs/acorn) and [estree-walker](https://github.com/Rich-Harris/estree-walker): ```js const { parse } = require( 'acorn' ); const { walk } = require( 'estree-walker' ); const isReference = require( 'is-reference' ); const identifiers = []; const references = []; const ast = parse( `var a = b.c;` ); walk( ast, { enter ( node, parent ) { if ( node.type === 'Identifier' ) identifiers.push( node ); if ( isReference( node, parent ) ) references.push( node ); } }); identifiers.forEach( node => console.log( node.name ) ); // a, b, c references.forEach( node => console.log( node.name ) ); // a, b ``` ## License MIT # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # Is Module Check whether a source string looks like an ES6 module. This doesn't actually execute the code, and doesn't check other module types. So source strings without any module loaders returns `false`. This is just what I need from https://github.com/yahoo/js-module-formats, which actually executes the sauce string in a subcontext. ## API ```js var isES6Module = require('is-module'); console.log(isES6Module('import * from "emitter";')) // => true ``` ## License (The MIT License) Copyright (c) 2014 segmentio &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # pump pump is a small node module that pipes streams together and destroys all of them if one of them closes. ``` npm install pump ``` [![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) ## What problem does it solve? When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. You are also not able to provide a callback to tell when then pipe has finished. pump does these two things for you ## Usage Simply pass the streams you want to pipe together to pump and add an optional callback ``` js var pump = require('pump') var fs = require('fs') var source = fs.createReadStream('/dev/random') var dest = fs.createWriteStream('/dev/null') pump(source, dest, function(err) { console.log('pipe finished', err) }) setTimeout(function() { dest.destroy() // when dest is closed pump will destroy source }, 1000) ``` You can use pump to pipe more than two streams together as well ``` js var transform = someTransformStream() pump(source, transform, anotherTransform, dest, function(err) { console.log('pipe finished', err) }) ``` If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: ``` return pump(s1, s2) // returns s2 ``` If you want to return a stream that combines *both* s1 and s2 to a single stream use [pumpify](https://github.com/mafintosh/pumpify) instead. ## License MIT ## Related `pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # minimist <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] parse argument options This module is the guts of optimist's argument parser without all the fanciful decoration. # example ``` js var argv = require('minimist')(process.argv.slice(2)); console.log(argv); ``` ``` $ node example/parse.js -a beep -b boop { _: [], a: 'beep', b: 'boop' } ``` ``` $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz { _: [ 'foo', 'bar', 'baz' ], x: 3, y: 4, n: 5, a: true, b: true, c: true, beep: 'boop' } ``` # security Previous versions had a prototype pollution bug that could cause privilege escalation in some circumstances when handling untrusted user input. Please use version 1.2.6 or later: * https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) * https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) # methods ``` js var parseArgs = require('minimist') ``` ## var argv = parseArgs(args, opts={}) Return an argument object `argv` populated with the array arguments from `args`. `argv._` contains all the arguments that didn't have an option associated with them. Numeric-looking arguments will be returned as numbers unless `opts.string` or `opts.boolean` is set for that argument name. Any arguments after `'--'` will not be parsed and will end up in `argv._`. options can be: * `opts.string` - a string or array of strings argument names to always treat as strings * `opts.boolean` - a boolean, string or array of strings to always treat as booleans. if `true` will treat all double hyphenated arguments without equal signs as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) * `opts.alias` - an object mapping string names to strings or arrays of string argument names to use as aliases * `opts.default` - an object mapping string argument names to default values * `opts.stopEarly` - when true, populate `argv._` with everything after the first non-option * `opts['--']` - when true, populate `argv._` with everything before the `--` and `argv['--']` with everything after the `--`. Here's an example: ``` > require('./')('one two three -- four five --six'.split(' '), { '--': true }) { _: [ 'one', 'two', 'three' ], '--': [ 'four', 'five', '--six' ] } ``` Note that with `opts['--']` set, parsing for arguments still stops after the `--`. * `opts.unknown` - a function which is invoked with a command line parameter not defined in the `opts` configuration object. If the function returns `false`, the unknown option is not added to `argv`. # install With [npm](https://npmjs.org) do: ``` npm install minimist ``` # license MIT [package-url]: https://npmjs.org/package/minimist [npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg [npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/minimist.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/minimist.svg [downloads-url]: https://npm-stat.com/charts.html?package=minimist [codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist [actions-url]: https://github.com/minimistjs/minimist/actions # capability.js - javascript environment capability detection [![Build Status](https://travis-ci.org/inf3rno/capability.png?branch=master)](https://travis-ci.org/inf3rno/capability) The capability.js library provides capability detection for different javascript environments. ## Documentation This project is empty yet. ### Installation ```bash npm install capability ``` ```bash bower install capability ``` #### Environment compatibility The lib requires only basic javascript features, so it will run in every js environments. #### Requirements If you want to use the lib in browser, you'll need a node module loader, e.g. browserify, webpack, etc... #### Usage In this documentation I used the lib as follows: ```js var capability = require("capability"); ``` ### Capabilities API #### Defining a capability You can define a capability by using the `define(name, test)` function. ```js capability.define("Object.create", function () { return Object.create; }); ``` The `name` parameter should contain the identifier of the capability and the `test` parameter should contain a function, which can detect the capability. If the capability is supported by the environment, then the `test()` should return `true`, otherwise it should return `false`. You don't have to convert the return value into a `Boolean`, the library will do that for you, so you won't have memory leaks because of this. #### Testing a capability The `test(name)` function will return a `Boolean` about whether the capability is supported by the actual environment. ```js console.log(capability.test("Object.create")); // true - in recent environments // false - by pre ES5 environments without Object.create ``` You can use `capability(name)` instead of `capability.test(name)` if you want a short code by optional requirements. #### Checking a capability The `check(name)` function will throw an Error when the capability is not supported by the actual environment. ```js capability.check("Object.create"); // this will throw an Error by pre ES5 environments without Object.create ``` #### Checking capability with require and modules It is possible to check the environments with `require()` by adding a module, which calls the `check(name)` function. By the capability definitions in this lib I added such modules by each definition, so you can do for example `require("capability/es5")`. Ofc. you can do fun stuff if you want, e.g. you can call multiple `check`s from a single `requirements.js` file in your lib, etc... ### Definitions Currently the following definitions are supported by the lib: - strict mode - `arguments.callee.caller` - es5 - `Array.prototype.forEach` - `Array.prototype.map` - `Function.prototype.bind` - `Object.create` - `Object.defineProperties` - `Object.defineProperty` - `Object.prototype.hasOwnProperty` - `Error.captureStackTrace` - `Error.prototype.stack` ## License MIT - 2016 Jánszky László Lajos # readdirp [![Weekly downloads](https://img.shields.io/npm/dw/readdirp.svg)](https://github.com/paulmillr/readdirp) Recursive version of [fs.readdir](https://nodejs.org/api/fs.html#fs_fs_readdir_path_options_callback). Exposes a **stream API** and a **promise API**. ```sh npm install readdirp ``` ```javascript const readdirp = require('readdirp'); // Use streams to achieve small RAM & CPU footprint. // 1) Streams example with for-await. for await (const entry of readdirp('.')) { const {path} = entry; console.log(`${JSON.stringify({path})}`); } // 2) Streams example, non for-await. // Print out all JS files along with their size within the current folder & subfolders. readdirp('.', {fileFilter: '*.js', alwaysStat: true}) .on('data', (entry) => { const {path, stats: {size}} = entry; console.log(`${JSON.stringify({path, size})}`); }) // Optionally call stream.destroy() in `warn()` in order to abort and cause 'close' to be emitted .on('warn', error => console.error('non-fatal error', error)) .on('error', error => console.error('fatal error', error)) .on('end', () => console.log('done')); // 3) Promise example. More RAM and CPU than streams / for-await. const files = await readdirp.promise('.'); console.log(files.map(file => file.path)); // Other options. readdirp('test', { fileFilter: '*.js', directoryFilter: ['!.git', '!*modules'] // directoryFilter: (di) => di.basename.length === 9 type: 'files_directories', depth: 1 }); ``` For more examples, check out `examples` directory. ## API `const stream = readdirp(root[, options])` — **Stream API** - Reads given root recursively and returns a `stream` of [entry infos](#entryinfo) - Optionally can be used like `for await (const entry of stream)` with node.js 10+ (`asyncIterator`). - `on('data', (entry) => {})` [entry info](#entryinfo) for every file / dir. - `on('warn', (error) => {})` non-fatal `Error` that prevents a file / dir from being processed. Example: inaccessible to the user. - `on('error', (error) => {})` fatal `Error` which also ends the stream. Example: illegal options where passed. - `on('end')` — we are done. Called when all entries were found and no more will be emitted. - `on('close')` — stream is destroyed via `stream.destroy()`. Could be useful if you want to manually abort even on a non fatal error. At that point the stream is no longer `readable` and no more entries, warning or errors are emitted - To learn more about streams, consult the very detailed [nodejs streams documentation](https://nodejs.org/api/stream.html) or the [stream-handbook](https://github.com/substack/stream-handbook) `const entries = await readdirp.promise(root[, options])` — **Promise API**. Returns a list of [entry infos](#entryinfo). First argument is awalys `root`, path in which to start reading and recursing into subdirectories. ### options - `fileFilter: ["*.js"]`: filter to include or exclude files. A `Function`, Glob string or Array of glob strings. - **Function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry - **Glob string**: a string (e.g., `*.js`) which is matched using [picomatch](https://github.com/micromatch/picomatch), so go there for more information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. - **Array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. `['*.json', '*.js']` includes all JavaScript and Json files. `['!.git', '!node_modules']` includes all directories except the '.git' and 'node_modules'. - Directories that do not pass a filter will not be recursed into. - `directoryFilter: ['!.git']`: filter to include/exclude directories found and to recurse into. Directories that do not pass a filter will not be recursed into. - `depth: 5`: depth at which to stop recursing even if more subdirectories are found - `type: 'files'`: determines if data events on the stream should be emitted for `'files'` (default), `'directories'`, `'files_directories'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. - `alwaysStat: false`: always return `stats` property for every file. Default is `false`, readdirp will return `Dirent` entries. Setting it to `true` can double readdir execution time - use it only when you need file `size`, `mtime` etc. Cannot be enabled on node <10.10.0. - `lstat: false`: include symlink entries in the stream along with files. When `true`, `fs.lstat` would be used instead of `fs.stat` ### `EntryInfo` Has the following properties: - `path: 'assets/javascripts/react.js'`: path to the file/directory (relative to given root) - `fullPath: '/Users/dev/projects/app/assets/javascripts/react.js'`: full path to the file/directory found - `basename: 'react.js'`: name of the file/directory - `dirent: fs.Dirent`: built-in [dir entry object](https://nodejs.org/api/fs.html#fs_class_fs_dirent) - only with `alwaysStat: false` - `stats: fs.Stats`: built in [stat object](https://nodejs.org/api/fs.html#fs_class_fs_stats) - only with `alwaysStat: true` ## Changelog - 3.5 (Oct 13, 2020) disallows recursive directory-based symlinks. Before, it could have entered infinite loop. - 3.4 (Mar 19, 2020) adds support for directory-based symlinks. - 3.3 (Dec 6, 2019) stabilizes RAM consumption and enables perf management with `highWaterMark` option. Fixes race conditions related to `for-await` looping. - 3.2 (Oct 14, 2019) improves performance by 250% and makes streams implementation more idiomatic. - 3.1 (Jul 7, 2019) brings `bigint` support to `stat` output on Windows. This is backwards-incompatible for some cases. Be careful. It you use it incorrectly, you'll see "TypeError: Cannot mix BigInt and other types, use explicit conversions". - 3.0 brings huge performance improvements and stream backpressure support. - Upgrading 2.x to 3.x: - Signature changed from `readdirp(options)` to `readdirp(root, options)` - Replaced callback API with promise API. - Renamed `entryType` option to `type` - Renamed `entryType: 'both'` to `'files_directories'` - `EntryInfo` - Renamed `stat` to `stats` - Emitted only when `alwaysStat: true` - `dirent` is emitted instead of `stats` by default with `alwaysStat: false` - Renamed `name` to `basename` - Removed `parentDir` and `fullParentDir` properties - Supported node.js versions: - 3.x: node 8+ - 2.x: node 0.6+ ## License Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (<https://paulmillr.com>) MIT License, see [LICENSE](LICENSE) file. randombytes === [![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues ```js var randomBytes = require('randombytes'); randomBytes(16);//get 16 random bytes randomBytes(16, function (err, resp) { // resp is 16 random bytes }); ``` # fsevents [![NPM](https://nodei.co/npm/fsevents.png)](https://nodei.co/npm/fsevents/) Native access to MacOS FSEvents in [Node.js](https://nodejs.org/) The FSEvents API in MacOS allows applications to register for notifications of changes to a given directory tree. It is a very fast and lightweight alternative to kqueue. This is a low-level library. For a cross-platform file watching module that uses fsevents, check out [Chokidar](https://github.com/paulmillr/chokidar). ## Installation Supports only **Node.js v8.16 and higher**. ```sh npm install fsevents ``` ## Usage ```js const fsevents = require('fsevents'); const stop = fsevents.watch(__dirname, (path, flags, id) => { const info = fsevents.getInfo(path, flags, id); }); // To start observation stop(); // To end observation ``` The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a a change in the file system. It takes three arguments: ###### `fsevents.watch(dirname: string, (path: string, flags: number, id: string) => void): () => Promise<undefined>` * `path: string` - the item in the filesystem that have been changed * `flags: number` - a numeric value describing what the change was * `id: string` - an unique-id identifying this specific event Returns closer callback which when called returns a Promise resolving when the watcher process has been shut down. ###### `fsevents.getInfo(path: string, flags: number, id: string): FsEventInfo` The `getInfo` function takes the `path`, `flags` and `id` arguments and converts those parameters into a structure that is easier to digest to determine what the change was. The `FsEventsInfo` has the following shape: ```js /** * @typedef {'created'|'modified'|'deleted'|'moved'|'root-changed'|'cloned'|'unknown'} FsEventsEvent * @typedef {'file'|'directory'|'symlink'} FsEventsType */ { "event": "created", // {FsEventsEvent} "path": "file.txt", "type": "file", // {FsEventsType} "changes": { "inode": true, // Had iNode Meta-Information changed "finder": false, // Had Finder Meta-Data changed "access": false, // Had access permissions changed "xattrs": false // Had xAttributes changed }, "flags": 0x100000000 } ``` ## Changelog - v2.3 supports Apple Silicon ARM CPUs - v2 supports node 8.16+ and reduces package size massively - v1.2.8 supports node 6+ - v1.2.7 supports node 4+ ## Troubleshooting - I'm getting `EBADPLATFORM` `Unsupported platform for fsevents` error. - It's fine, nothing is broken. fsevents is macos-only. Other platforms are skipped. If you want to hide this warning, report a bug to NPM bugtracker asking them to hide ebadplatform warnings by default. ## License The MIT License Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller — see LICENSE file. Visit our [GitHub page](https://github.com/fsevents/fsevents) and [NPM Page](https://npmjs.org/package/fsevents) # core-util-is The `util.is*` functions introduced in Node v0.12. <!-- -- This file is auto-generated from README_js.md. Changes should be made there. --> # uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs - **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs - **Cross-platform** - Support for ... - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) - Node 8, 10, 12, 14 - Chrome, Safari, Firefox, Edge, IE 11 browsers - Webpack and rollup.js module bundlers - [React Native / Expo](#react-native--expo) - **Secure** - Cryptographically-strong random values - **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers - **CLI** - Includes the [`uuid` command line](#command-line) utility **Upgrading from `[email protected]`?** Your code is probably okay, but check out [Upgrading From `[email protected]`](#upgrading-from-uuid3x) for details. ## Quickstart To create a random UUID... **1. Install** ```shell npm install uuid ``` **2. Create a UUID** (ES6 module syntax) ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' ``` ... or using CommonJS syntax: ```javascript const { v4: uuidv4 } = require('uuid'); uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` For timestamp UUIDs, namespace UUIDs, and other options read on ... ## API Summary | | | | | --- | --- | --- | | [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `[email protected]` | | [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `[email protected]` | | [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `[email protected]` | | [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | | [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | | [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | | [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | | [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `[email protected]` | | [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `[email protected]` | ## API ### uuid.NIL The nil UUID string (all zeros). Example: ```javascript import { NIL as NIL_UUID } from 'uuid'; NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' ``` ### uuid.parse(str) Convert UUID string to array of bytes | | | | --------- | ---------------------------------------- | | `str` | A valid UUID `String` | | _returns_ | `Uint8Array[16]` | | _throws_ | `TypeError` if `str` is not a valid UUID | Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below. Example: ```javascript import { parse as uuidParse } from 'uuid'; // Parse a UUID const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // Convert to hex strings to show byte order (for documentation purposes) [...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ // [ // '6e', 'c0', 'bd', '7f', // '11', 'c0', '43', 'da', // '97', '5e', '2a', '8a', // 'd9', 'eb', 'ae', '0b' // ] ``` ### uuid.stringify(arr[, offset]) Convert array of bytes to UUID string | | | | -------------- | ---------------------------------------------------------------------------- | | `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | | [`offset` = 0] | `Number` Starting index in the Array | | _returns_ | `String` | | _throws_ | `TypeError` if a valid UUID string cannot be generated | Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below. Example: ```javascript import { stringify as uuidStringify } from 'uuid'; const uuidBytes = [ 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, ]; uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' ``` ### uuid.v1([options[, buffer[, offset]]]) Create an RFC version 1 (timestamp) UUID | | | | --- | --- | | [`options`] | `Object` with one or more of the following properties: | | [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | | [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | | [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | | [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) | | [`options.random`] | `Array` of 16 random bytes (0-255) | | [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | | _throws_ | `Error` if more than 10M UUIDs/sec are requested | Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. Example: ```javascript import { v1 as uuidv1 } from 'uuid'; uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' ``` Example using `options`: ```javascript import { v1 as uuidv1 } from 'uuid'; const v1options = { node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], clockseq: 0x1234, msecs: new Date('2011-11-01').getTime(), nsecs: 5678, }; uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' ``` ### uuid.v3(name, namespace[, buffer[, offset]]) Create an RFC version 3 (namespace w/ MD5) UUID API is identical to `v5()`, but uses "v3" instead. &#x26a0;&#xfe0f; Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." ### uuid.v4([options[, buffer[, offset]]]) Create an RFC version 4 (random) UUID | | | | --- | --- | | [`options`] | `Object` with one or more of the following properties: | | [`options.random`] | `Array` of 16 random bytes (0-255) | | [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | Example: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` Example using predefined `random` values: ```javascript import { v4 as uuidv4 } from 'uuid'; const v4options = { random: [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, ], }; uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' ``` ### uuid.v5(name, namespace[, buffer[, offset]]) Create an RFC version 5 (namespace w/ SHA-1) UUID | | | | --- | --- | | `name` | `String \| Array` | | `namespace` | `String \| Array[16]` Namespace UUID | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. Example with custom namespace: ```javascript import { v5 as uuidv5 } from 'uuid'; // Define a custom namespace. Readers, create your own using something like // https://www.uuidgenerator.net/ const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' ``` Example with RFC `URL` namespace: ```javascript import { v5 as uuidv5 } from 'uuid'; uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' ``` ### uuid.validate(str) Test a string to see if it is a valid UUID | | | | --------- | --------------------------------------------------- | | `str` | `String` to validate | | _returns_ | `true` if string is a valid UUID, `false` otherwise | Example: ```javascript import { validate as uuidValidate } from 'uuid'; uuidValidate('not a UUID'); // ⇨ false uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true ``` Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. ```javascript import { version as uuidVersion } from 'uuid'; import { validate as uuidValidate } from 'uuid'; function uuidValidateV4(uuid) { return uuidValidate(uuid) && uuidVersion(uuid) === 4; } const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; uuidValidateV4(v4Uuid); // ⇨ true uuidValidateV4(v1Uuid); // ⇨ false ``` ### uuid.version(str) Detect RFC version of a UUID | | | | --------- | ---------------------------------------- | | `str` | A valid UUID `String` | | _returns_ | `Number` The RFC version of the UUID | | _throws_ | `TypeError` if `str` is not a valid UUID | Example: ```javascript import { version as uuidVersion } from 'uuid'; uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 ``` ## Command Line UUIDs can be generated from the command line using `uuid`. ```shell $ uuid ddeb27fb-d9a0-4624-be4d-4615062daed4 ``` The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: ```shell $ uuid --help Usage: uuid uuid v1 uuid v3 <name> <namespace uuid> uuid v4 uuid v5 <name> <namespace uuid> uuid --help Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122 ``` ## ECMAScript Modules This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` To run the examples you must first create a dist build of this library in the module root: ```shell npm run build ``` ## CDN Builds ### ECMAScript Modules To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): ```html <script type="module"> import { v4 as uuidv4 } from 'https://jspm.dev/uuid'; console.log(uuidv4()); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' </script> ``` ### UMD To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs: **Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**: ```html <script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script> ``` **Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**: ```html <script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script> ``` **Using [cdnjs](https://cdnjs.com/libraries/uuid)**: ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.1.0/uuidv4.min.js"></script> ``` These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method: ```html <script> uuidv4(); // ⇨ '55af1e37-0734-46d8-b070-a1e42e4fc392' </script> ``` Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively. ## "getRandomValues() not supported" This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: ### React Native / Expo 1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) 1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: ```javascript import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; ``` Note: If you are using Expo, you must be using at least `[email protected]` and `[email protected]`. ### Web Workers / Service Workers (Edge <= 18) [In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). ## Upgrading From `[email protected]` ### Only Named Exports Supported When Using with Node.js ESM `[email protected]` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. Instead of doing: ```javascript import uuid from 'uuid'; uuid.v4(); ``` you will now have to use the named exports: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); ``` ### Deep Requires No Longer Supported Deep requires like `require('uuid/v4')` [which have been deprecated in `[email protected]`](#deep-requires-now-deprecated) are no longer supported. ## Upgrading From `[email protected]` "_Wait... what happened to `[email protected]` - `[email protected]`?!?_" In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. ### Deep Requires Now Deprecated `[email protected]` encouraged the use of deep requires to minimize the bundle size of browser builds: ```javascript const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! uuidv4(); ``` As of `[email protected]` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); ``` ... or for CommonJS: ```javascript const { v4: uuidv4 } = require('uuid'); uuidv4(); ``` ### Default Export Removed `[email protected]` was exporting the Version 4 UUID method as a default export: ```javascript const uuid = require('uuid'); // <== REMOVED! ``` This usage pattern was already discouraged in `[email protected]` and has been removed in `[email protected]`. ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # tar-stream tar-stream is a streaming tar parser and generator and nothing else. It is streams2 and operates purely using streams which means you can easily extract/parse tarballs without ever hitting the file system. Note that you still need to gunzip your data if you have a `.tar.gz`. We recommend using [gunzip-maybe](https://github.com/mafintosh/gunzip-maybe) in conjunction with this. ``` npm install tar-stream ``` [![build status](https://secure.travis-ci.org/mafintosh/tar-stream.png)](http://travis-ci.org/mafintosh/tar-stream) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](http://opensource.org/licenses/MIT) ## Usage tar-stream exposes two streams, [pack](https://github.com/mafintosh/tar-stream#packing) which creates tarballs and [extract](https://github.com/mafintosh/tar-stream#extracting) which extracts tarballs. To [modify an existing tarball](https://github.com/mafintosh/tar-stream#modifying-existing-tarballs) use both. It implementes USTAR with additional support for pax extended headers. It should be compatible with all popular tar distributions out there (gnutar, bsdtar etc) ## Related If you want to pack/unpack directories on the file system check out [tar-fs](https://github.com/mafintosh/tar-fs) which provides file system bindings to this module. ## Packing To create a pack stream use `tar.pack()` and call `pack.entry(header, [callback])` to add tar entries. ``` js var tar = require('tar-stream') var pack = tar.pack() // pack is a streams2 stream // add a file called my-test.txt with the content "Hello World!" pack.entry({ name: 'my-test.txt' }, 'Hello World!') // add a file called my-stream-test.txt from a stream var entry = pack.entry({ name: 'my-stream-test.txt', size: 11 }, function(err) { // the stream was added // no more entries pack.finalize() }) entry.write('hello') entry.write(' ') entry.write('world') entry.end() // pipe the pack stream somewhere pack.pipe(process.stdout) ``` ## Extracting To extract a stream use `tar.extract()` and listen for `extract.on('entry', (header, stream, next) )` ``` js var extract = tar.extract() extract.on('entry', function(header, stream, next) { // header is the tar header // stream is the content body (might be an empty stream) // call next when you are done with this entry stream.on('end', function() { next() // ready for next entry }) stream.resume() // just auto drain the stream }) extract.on('finish', function() { // all entries read }) pack.pipe(extract) ``` The tar archive is streamed sequentially, meaning you **must** drain each entry's stream as you get them or else the main extract stream will receive backpressure and stop reading. ## Headers The header object using in `entry` should contain the following properties. Most of these values can be found by stat'ing a file. ``` js { name: 'path/to/this/entry.txt', size: 1314, // entry size. defaults to 0 mode: 0o644, // entry mode. defaults to to 0o755 for dirs and 0o644 otherwise mtime: new Date(), // last modified date for entry. defaults to now. type: 'file', // type of entry. defaults to file. can be: // file | link | symlink | directory | block-device // character-device | fifo | contiguous-file linkname: 'path', // linked file name uid: 0, // uid of entry owner. defaults to 0 gid: 0, // gid of entry owner. defaults to 0 uname: 'maf', // uname of entry owner. defaults to null gname: 'staff', // gname of entry owner. defaults to null devmajor: 0, // device major version. defaults to 0 devminor: 0 // device minor version. defaults to 0 } ``` ## Modifying existing tarballs Using tar-stream it is easy to rewrite paths / change modes etc in an existing tarball. ``` js var extract = tar.extract() var pack = tar.pack() var path = require('path') extract.on('entry', function(header, stream, callback) { // let's prefix all names with 'tmp' header.name = path.join('tmp', header.name) // write the new entry to the pack stream stream.pipe(pack.entry(header, callback)) }) extract.on('finish', function() { // all entries done - lets finalize it pack.finalize() }) // pipe the old tarball to the extractor oldTarballStream.pipe(extract) // pipe the new tarball the another stream pack.pipe(newTarballStream) ``` ## Saving tarball to fs ``` js var fs = require('fs') var tar = require('tar-stream') var pack = tar.pack() // pack is a streams2 stream var path = 'YourTarBall.tar' var yourTarball = fs.createWriteStream(path) // add a file called YourFile.txt with the content "Hello World!" pack.entry({name: 'YourFile.txt'}, 'Hello World!', function (err) { if (err) throw err pack.finalize() }) // pipe the pack stream to your file pack.pipe(yourTarball) yourTarball.on('close', function () { console.log(path + ' has been written') fs.stat(path, function(err, stats) { if (err) throw err console.log(stats) console.log('Got file info successfully!') }) }) ``` ## Performance [See tar-fs for a performance comparison with node-tar](https://github.com/mafintosh/tar-fs/blob/master/README.md#performance) # License MIT <h1 align="center"> <img width="250" src="https://jaredwray.com/images/keyv.svg" alt="keyv"> <br> <br> </h1> > Simple key-value storage with support for multiple backends [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv) [![npm](https://img.shields.io/npm/dm/keyv.svg)](https://www.npmjs.com/package/keyv) [![npm](https://img.shields.io/npm/v/keyv.svg)](https://www.npmjs.com/package/keyv) Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store. ## Features There are a few existing modules similar to Keyv, however Keyv is different because it: - Isn't bloated - Has a simple Promise based API - Suitable as a TTL based cache or persistent key-value store - [Easily embeddable](#add-cache-support-to-your-module) inside another module - Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API - Handles all JSON types plus `Buffer` - Supports namespaces - Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters - Connection errors are passed through (db failures won't kill your app) - Supports the current active LTS version of Node.js or higher ## Usage Install Keyv. ``` npm install --save keyv ``` By default everything is stored in memory, you can optionally also install a storage adapter. ``` npm install --save @keyv/redis npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql npm install --save @keyv/etcd ``` Create a new Keyv instance, passing your connection string if applicable. Keyv will automatically load the correct storage adapter. ```js const Keyv = require('keyv'); // One of the following const keyv = new Keyv(); const keyv = new Keyv('redis://user:pass@localhost:6379'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); const keyv = new Keyv('sqlite://path/to/database.sqlite'); const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); const keyv = new Keyv('etcd://localhost:2379'); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); await keyv.set('foo', 'expires in 1 second', 1000); // true await keyv.set('foo', 'never expires'); // true await keyv.get('foo'); // 'never expires' await keyv.delete('foo'); // true await keyv.clear(); // undefined ``` ### Namespaces You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database. ```js const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' }); const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' }); await users.set('foo', 'users'); // true await cache.set('foo', 'cache'); // true await users.get('foo'); // 'users' await cache.get('foo'); // 'cache' await users.clear(); // undefined await users.get('foo'); // undefined await cache.get('foo'); // 'cache' ``` ### Custom Serializers Keyv uses [`json-buffer`](https://github.com/dominictarr/json-buffer) for data serialization to ensure consistency across different backends. You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON. ```js const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); ``` **Warning:** Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine. ## Official Storage Adapters The official storage adapters are covered by [over 150 integration tests](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml) to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available. Database | Adapter | Native TTL ---|---|--- Redis | [@keyv/redis](https://github.com/jaredwray/keyv/tree/master/packages/redis) | Yes MongoDB | [@keyv/mongo](https://github.com/jaredwray/keyv/tree/master/packages/mongo) | Yes SQLite | [@keyv/sqlite](https://github.com/jaredwray/keyv/tree/master/packages/sqlite) | No PostgreSQL | [@keyv/postgres](https://github.com/jaredwray/keyv/tree/master/packages/postgres) | No MySQL | [@keyv/mysql](https://github.com/jaredwray/keyv/tree/master/packages/mysql) | No Etcd | [@keyv/etcd](https://github.com/jaredwray/keyv/tree/master/packages/etcd) | Yes Memcache | [@keyv/memcache](https://github.com/jaredwray/keyv/tree/master/packages/memcache) | Yes ## Third-party Storage Adapters You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally. ```js const Keyv = require('keyv'); const myAdapter = require('./my-storage-adapter'); const keyv = new Keyv({ store: myAdapter }); ``` Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work. ```js new Keyv({ store: new Map() }); ``` For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API. ```js const Keyv = require('keyv'); const QuickLRU = require('quick-lru'); const lru = new QuickLRU({ maxSize: 1000 }); const keyv = new Keyv({ store: lru }); ``` The following are third-party storage adapters compatible with Keyv: - [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple "Least Recently Used" (LRU) cache - [keyv-file](https://github.com/zaaack/keyv-file) - File system storage adapter for Keyv - [keyv-dynamodb](https://www.npmjs.com/package/keyv-dynamodb) - DynamoDB storage adapter for Keyv - [keyv-lru](https://www.npmjs.com/package/keyv-lru) - LRU storage adapter for Keyv - [keyv-null](https://www.npmjs.com/package/keyv-null) - Null storage adapter for Keyv - [keyv-firestore ](https://github.com/goto-bus-stop/keyv-firestore) – Firebase Cloud Firestore adapter for Keyv - [keyv-mssql](https://github.com/pmorgan3/keyv-mssql) - Microsoft Sql Server adapter for Keyv - [keyv-azuretable](https://github.com/howlowck/keyv-azuretable) - Azure Table Storage/API adapter for Keyv ## Add Cache Support to your Module Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a `cache` option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string, or any other storage that implements the `Map` API. You should also set a namespace for your module so you can safely call `.clear()` without clearing unrelated app data. Inside your module: ```js class AwesomeModule { constructor(opts) { this.cache = new Keyv({ uri: typeof opts.cache === 'string' && opts.cache, store: typeof opts.cache !== 'string' && opts.cache, namespace: 'awesome-module' }); } } ``` Now it can be consumed like this: ```js const AwesomeModule = require('awesome-module'); // Caches stuff in memory by default const awesomeModule = new AwesomeModule(); // After npm install --save keyv-redis const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' }); // Some third-party module that implements the Map API const awesomeModule = new AwesomeModule({ cache: some3rdPartyStore }); ``` ## Compression Keyv supports `gzip` and `brotli` compression. To enable compression, pass the `compress` option to the constructor. ```js const KeyvGzip = require('@keyv/compress-gzip'); const Keyv = require('keyv'); const keyvGzip = new KeyvGzip(); const keyv = new Keyv({ compression: KeyvGzip }); ``` You can also pass a custom compression function to the `compression` option. Following the pattern of the official compression adapters. ### Want to build your own? Great! Keyv is designed to be easily extended. You can build your own compression adapter by following the pattern of the official compression adapters based on this interface: ```typescript interface CompressionAdapter { async compress(value: any, options?: any); async decompress(value: any, options?: any); async serialize(value: any); async deserialize(value: any); } ``` In addition to the interface, you can test it with our compression test suite using @keyv/test-suite: ```js const {keyvCompresstionTests} = require('@keyv/test-suite'); const KeyvGzip = require('@keyv/compress-gzip'); keyvCompresstionTests(test, new KeyvGzip()); ``` ## API ### new Keyv([uri], [options]) Returns a new Keyv instance. The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails. ### uri Type: `String`<br> Default: `undefined` The connection string URI. Merged into the options object as options.uri. ### options Type: `Object` The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. #### options.namespace Type: `String`<br> Default: `'keyv'` Namespace for the current instance. #### options.ttl Type: `Number`<br> Default: `undefined` Default TTL. Can be overridden by specififying a TTL on `.set()`. #### options.compression Type: `@keyv/compress-<compression_package_name>`<br> Default: `undefined` Compression package to use. See [Compression](#compression) for more details. #### options.serialize Type: `Function`<br> Default: `JSONB.stringify` A custom serialization function. #### options.deserialize Type: `Function`<br> Default: `JSONB.parse` A custom deserialization function. #### options.store Type: `Storage adapter instance`<br> Default: `new Map()` The storage adapter instance to be used by Keyv. #### options.adapter Type: `String`<br> Default: `undefined` Specify an adapter to use. e.g `'redis'` or `'mongodb'`. ### Instance Keys must always be strings. Values can be of any type. #### .set(key, value, [ttl]) Set a value. By default keys are persistent. You can set an expiry TTL in milliseconds. Returns a promise which resolves to `true`. #### .get(key, [options]) Returns a promise which resolves to the retrieved value. ##### options.raw Type: `Boolean`<br> Default: `false` If set to true the raw DB object Keyv stores internally will be returned instead of just the value. This contains the TTL timestamp. #### .delete(key) Deletes an entry. Returns a promise which resolves to `true` if the key existed, `false` if not. #### .clear() Delete all entries in the current namespace. Returns a promise which is resolved when the entries have been cleared. #### .iterator() Iterate over all entries of the current namespace. Returns a iterable that can be iterated by for-of loops. For example: ```js // please note that the "await" keyword should be used here for await (const [key, value] of this.keyv.iterator()) { console.log(key, value); }; ``` # How to Contribute In this section of the documentation we will cover: 1) How to set up this repository locally 2) How to get started with running commands 3) How to contribute changes using Pull Requests ## Dependencies This package requires the following dependencies to run: 1) [Yarn V1](https://yarnpkg.com/getting-started/install) 3) [Docker](https://docs.docker.com/get-docker/) ## Setting up your workspace To contribute to this repository, start by setting up this project locally: 1) Fork this repository into your Git account 2) Clone the forked repository to your local directory using `git clone` 3) Install any of the above missing dependencies ## Launching the project Once the project is installed locally, you are ready to start up its services: 1) Ensure that your Docker service is running. 2) From the root directory of your project, run the `yarn` command in the command prompt to install yarn. 3) Run the `yarn bootstrap` command to install any necessary dependencies. 4) Run `yarn test:services:start` to start up this project's Docker container. The container will launch all services within your workspace. ## Available Commands Once the project is running, you can execute a variety of commands. The root workspace and each subpackage contain a `package.json` file with a `scripts` field listing all the commands that can be executed from that directory. This project also supports native `yarn`, and `docker` commands. Here, we'll cover the primary commands that can be executed from the root directory. Unless otherwise noted, these commands can also be executed from a subpackage. If executed from a subpackage, they will only affect that subpackage, rather than the entire workspace. ### `yarn` The `yarn` command installs yarn in the workspace. ### `yarn bootstrap` The `yarn bootstrap` command installs all dependencies in the workspace. ### `yarn test:services:start` The `yarn test:services:start` command starts up the project's Docker container, launching all services in the workspace. This command must be executed from the root directory. ### `yarn test:services:stop` The `yarn test:services:stop` command brings down the project's Docker container, halting all services. This command must be executed from the root directory. ### `yarn test` The `yarn test` command runs all tests in the workspace. ### `yarn clean` The `yarn clean` command removes yarn and all dependencies installed by yarn. After executing this command, you must repeat the steps in *Setting up your workspace* to rebuild your workspace. ## Contributing Changes Now that you've set up your workspace, you're ready to contribute changes to the `keyv` repository. 1) Make any changes that you would like to contribute in your local workspace. 2) After making these changes, ensure that the project's tests still pass by executing the `yarn test` command in the root directory. 3) Commit your changes and push them to your forked repository. 4) Navigate to the original `keyv` repository and go the *Pull Requests* tab. 5) Click the *New pull request* button, and open a pull request for the branch in your repository that contains your changes. 6) Once your pull request is created, ensure that all checks have passed and that your branch has no conflicts with the base branch. If there are any issues, resolve these changes in your local repository, and then commit and push them to git. 7) Similarly, respond to any reviewer comments or requests for changes by making edits to your local repository and pushing them to Git. 8) Once the pull request has been reviewed, those with write access to the branch will be able to merge your changes into the `keyv` repository. If you need more information on the steps to create a pull request, you can find a detailed walkthrough in the [Github documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) ## License MIT © Jared Wray # lodash.isstring v4.0.1 The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.isstring ``` In Node.js: ```js var isString = require('lodash.isstring'); ``` See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details. # Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar) > Minimal and efficient cross-platform file watching library [![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) ## Why? Node.js `fs.watch`: * Doesn't report filenames on MacOS. * Doesn't report events at all when using editors like Sublime on MacOS. * Often reports events twice. * Emits most changes as `rename`. * Does not provide an easy way to recursively watch file trees. * Does not support recursive watching on Linux. Node.js `fs.watchFile`: * Almost as bad at event handling. * Also does not provide any recursive watching. * Results in high CPU utilization. Chokidar resolves these problems. Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in [Microsoft's Visual Studio Code](https://github.com/microsoft/vscode), [gulp](https://github.com/gulpjs/gulp/), [karma](https://karma-runner.github.io/), [PM2](https://github.com/Unitech/PM2), [browserify](http://browserify.org/), [webpack](https://webpack.github.io/), [BrowserSync](https://www.browsersync.io/), and [many others](https://www.npmjs.com/browse/depended/chokidar). It has proven itself in production environments. Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/) ## How? Chokidar does still rely on the Node.js core `fs` module, but when using `fs.watch` and `fs.watchFile` for watching, it normalizes the events it receives, often checking for truth by getting file stats and/or dir contents. On MacOS, chokidar by default uses a native extension exposing the Darwin `FSEvents` API. This provides very efficient recursive watching compared with implementations like `kqueue` available on most \*nix platforms. Chokidar still does have to do some work to normalize the events received that way as well. On most other platforms, the `fs.watch`-based implementation is the default, which avoids polling and keeps CPU usage down. Be advised that chokidar will initiate watchers recursively for everything within scope of the paths that have been specified, so be judicious about not wasting system resources by watching much more than needed. ## Getting started Install with npm: ```sh npm install chokidar ``` Then `require` and use it in your code: ```javascript const chokidar = require('chokidar'); // One-liner for current directory chokidar.watch('.').on('all', (event, path) => { console.log(event, path); }); ``` ## API ```javascript // Example of a more typical implementation structure // Initialize watcher. const watcher = chokidar.watch('file, dir, glob, or array', { ignored: /(^|[\/\\])\../, // ignore dotfiles persistent: true }); // Something to use when events are received. const log = console.log.bind(console); // Add event listeners. watcher .on('add', path => log(`File ${path} has been added`)) .on('change', path => log(`File ${path} has been changed`)) .on('unlink', path => log(`File ${path} has been removed`)); // More possible events. watcher .on('addDir', path => log(`Directory ${path} has been added`)) .on('unlinkDir', path => log(`Directory ${path} has been removed`)) .on('error', error => log(`Watcher error: ${error}`)) .on('ready', () => log('Initial scan complete. Ready for changes')) .on('raw', (event, path, details) => { // internal log('Raw event info:', event, path, details); }); // 'add', 'addDir' and 'change' events also receive stat() results as second // argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats watcher.on('change', (path, stats) => { if (stats) console.log(`File ${path} changed size to ${stats.size}`); }); // Watch new files. watcher.add('new-file'); watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); // Get list of actual paths being watched on the filesystem var watchedPaths = watcher.getWatched(); // Un-watch some files. await watcher.unwatch('new-file*'); // Stop watching. // The method is async! watcher.close().then(() => console.log('closed')); // Full list of options. See below for descriptions. // Do not use this example! chokidar.watch('file', { persistent: true, ignored: '*.txt', ignoreInitial: false, followSymlinks: true, cwd: '.', disableGlobbing: false, usePolling: false, interval: 100, binaryInterval: 300, alwaysStat: false, depth: 99, awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }, ignorePermissionErrors: false, atomic: true // or a custom 'atomicity delay', in milliseconds (default 100) }); ``` `chokidar.watch(paths, [options])` * `paths` (string or array of strings). Paths to files, dirs to be watched recursively, or glob patterns. - Note: globs must not contain windows separators (`\`), because that's how they work by the standard — you'll need to replace them with forward slashes (`/`). - Note 2: for additional glob documentation, check out low-level library: [picomatch](https://github.com/micromatch/picomatch). * `options` (object) Options object as defined below: #### Persistence * `persistent` (default: `true`). Indicates whether the process should continue to run as long as files are being watched. If set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, even if the process continues to run. #### Path filtering * `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition) Defines files/paths to be ignored. The whole relative or absolute path is tested, not just filename. If a function with two arguments is provided, it gets called twice per path - once with a single argument (the path), second time with two arguments (the path and the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). * `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while instantiating the watching as chokidar discovers these file paths (before the `ready` event). * `followSymlinks` (default: `true`). When `false`, only the symlinks themselves will be watched for changes instead of following the link references and bubbling events through the link's path. * `cwd` (no default). The base directory from which watch `paths` are to be derived. Paths emitted with events will be relative to this. * `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as literal path names, even if they look like globs. #### Performance * `usePolling` (default: `false`). Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU utilization, consider setting this to `false`. It is typically necessary to **set this to `true` to successfully watch files over a network**, and it may be necessary to successfully watch files in other non-standard situations. Setting to `true` explicitly on MacOS overrides the `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable to true (1) or false (0) in order to override this option. * _Polling-specific settings_ (effective when `usePolling: true`) * `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also set the CHOKIDAR_INTERVAL env variable to override this option. * `binaryInterval` (default: `300`). Interval of file system polling for binary files. ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) * `useFsEvents` (default: `true` on MacOS). Whether to use the `fsevents` watching interface if available. When set to `true` explicitly and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on MacOS, `usePolling: true` becomes the default. * `alwaysStat` (default: `false`). If relying upon the [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object that may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is provided even in cases where it wasn't already available from the underlying watch events. * `depth` (default: `undefined`). If set, limits how many levels of subdirectories will be traversed. * `awaitWriteFinish` (default: `false`). By default, the `add` event will fire when a file first appears on disk, before the entire file has been written. Furthermore, in some cases some `change` events will be emitted while the file is being written. In some cases, especially when watching for large files there will be a need to wait for the write operation to finish before responding to a file creation or modification. Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size, holding its `add` and `change` events until the size does not change for a configurable amount of time. The appropriate duration setting is heavily dependent on the OS and hardware. For accurate detection this parameter should be relatively high, making file watching much less responsive. Use with caution. * *`options.awaitWriteFinish` can be set to an object in order to adjust timing params:* * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in milliseconds for a file size to remain constant before emitting its event. * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds. #### Errors * `ignorePermissionErrors` (default: `false`). Indicates whether to watch files that don't have read permissions if possible. If watching fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed silently. * `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts that occur when using editors that use "atomic writes" instead of writing directly to the source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, you can override it by setting `atomic` to a custom value, in milliseconds. ### Methods & Events `chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`: * `.add(path / paths)`: Add files, directories, or glob patterns for tracking. Takes an array of strings or just one string. * `.on(event, callback)`: Listen for an FS event. Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, `raw`, `error`. Additionally `all` is available which gets emitted with the underlying event name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully. * `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. Takes an array of strings or just one string. * `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen. * `.getWatched()`: Returns an object representing all the paths on the file system being watched by this `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless the `cwd` option was used), and the values are arrays of the names of the items contained in each directory. ## CLI If you need a CLI interface for your file watching, check out [chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to execute a command on each change, or get a stdio stream of change events. ## Install Troubleshooting * `npm WARN optional dep failed, continuing [email protected]` * This message is normal part of how `npm` handles optional dependencies and is not indicative of a problem. Even if accompanied by other related error messages, Chokidar should function properly. * `TypeError: fsevents is not a constructor` * Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar. * Chokidar is producing `ENOSP` error on Linux, like this: * `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell` `Error: watch /home/ ENOSPC` * This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal: `echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p` ## Changelog For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md). - **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks. - **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement. - **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method. - **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions. - **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%. - **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher. - **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes. - **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported - **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66) ## Also Why was chokidar named this way? What's the meaning behind it? >Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). ## License MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file. <div align="center"> <h1>NEAR Workspaces (TypeScript/JavaScript Edition)</h1> [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![NPM version](https://img.shields.io/npm/v/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/near-workspaces.svg?style=flat-square)](https://npmjs.com/near-workspaces) </div> `NEAR Workspaces` is a library for automating workflows and writing tests for NEAR smart contracts. You can use it as is or integrate with test runner of your choise (AVA, Jest, Mocha, etc.). If you don't have a preference, we suggest you to use AVA. Quick Start (without testing frameworks) =========== To get started with `Near Workspaces` you need to do only two things: 1. Initialize a `Worker`. ```ts const worker = await Worker.init(); const root = worker.rootAccount; const alice = await root.createSubAccount('alice'); const contract = await root.devDeploy('path/to/compiled.wasm'); ``` 2. Writing tests. `near-workspaces` is designed for concurrency. Here's a simple way to get concurrent runs using plain JS: ```ts import {strict as assert} from 'assert'; await Promise.all([ async () => { await alice.call( contract, 'some_update_function', {some_string_argument: 'cool', some_number_argument: 42} ); const result = await contract.view( 'some_view_function', {account_id: alice} ); assert.equal(result, 'whatever'); }, async () => { const result = await contract.view( 'some_view_function', {account_id: alice} ); /* Note that we expect the value returned from `some_view_function` to be a default here, because this `fork` runs *at the same time* as the previous, in a separate local blockchain */ assert.equal(result, 'some default'); } ]); ``` ``` More info in our main README: https://github.com/near/workspaces-js # responselike > A response-like object for mocking a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/responselike.svg?branch=master)](https://travis-ci.org/lukechilds/responselike) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/responselike/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/responselike?branch=master) [![npm](https://img.shields.io/npm/dm/responselike.svg)](https://www.npmjs.com/package/responselike) [![npm](https://img.shields.io/npm/v/responselike.svg)](https://www.npmjs.com/package/responselike) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). Useful for formatting cached responses so they can be consumed by code expecting a real response. ## Install ```shell npm install --save responselike ``` Or if you're just using for testing you'll want: ```shell npm install --save-dev responselike ``` ## Usage ```js const Response = require('responselike'); const response = new Response(200, { foo: 'bar' }, Buffer.from('Hi!'), 'https://example.com'); response.statusCode; // 200 response.headers; // { foo: 'bar' } response.body; // <Buffer 48 69 21> response.url; // 'https://example.com' response.pipe(process.stdout); // Hi! ``` ## API ### new Response(statusCode, headers, body, url) Returns a streamable response object similar to a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage). #### statusCode Type: `number` HTTP response status code. #### headers Type: `object` HTTP headers object. Keys will be automatically lowercased. #### body Type: `buffer` A Buffer containing the response body. The Buffer contents will be streamable but is also exposed directly as `response.body`. #### url Type: `string` Request URL string. ## License MIT © Luke Childs # typedarray-to-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/typedarray-to-buffer/master.svg [travis-url]: https://travis-ci.org/feross/typedarray-to-buffer [npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg [npm-url]: https://npmjs.org/package/typedarray-to-buffer [downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg [downloads-url]: https://npmjs.org/package/typedarray-to-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg [saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or [browserify](http://browserify.org/) and you're working with lots of binary data. Unfortunately, sometimes the browser or someone else's API gives you a typed array like `Uint8Array` to work with and you need to convert it to a `Buffer`. What do you do? Of course: `Buffer.from(uint8array)` But, alas, every time you do `Buffer.from(uint8array)` **the entire array gets copied**. The `Buffer` constructor does a copy; this is defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module matches the node API exactly. So, how can we avoid this expensive copy in [performance critical applications](https://github.com/feross/buffer/issues/22)? ***Simply use this module, of course!*** If you have an `ArrayBuffer`, you don't need this module, because `Buffer.from(arrayBuffer)` [is already efficient](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length). ## install ```bash npm install typedarray-to-buffer ``` ## usage To convert a typed array to a `Buffer` **without a copy**, do this: ```js var toBuffer = require('typedarray-to-buffer') var arr = new Uint8Array([1, 2, 3]) arr = toBuffer(arr) // arr is a buffer now! arr.toString() // '\u0001\u0002\u0003' arr.readUInt16BE(0) // 258 ``` ## how it works If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you pass in with the `Buffer` methods and return it. See [how does Buffer work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation works. This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't require a copy. If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` object, copy the data into it, and return it. There's no simple performance optimization we can do for old browsers. Oh well. If this module is used in node, then it will just call `Buffer.from`. This is just for the convenience of modules that work in both node and the browser. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). # fastq ![ci][ci-url] [![npm version][npm-badge]][npm-url] [![Dependency Status][david-badge]][david-url] Fast, in memory work queue. Benchmarks (1 million tasks): * setImmediate: 812ms * fastq: 854ms * async.queue: 1298ms * neoAsync.queue: 1249ms Obtained on node 12.16.1, on a dedicated server. If you need zero-overhead series function call, check out [fastseries](http://npm.im/fastseries). For zero-overhead parallel function call, check out [fastparallel](http://npm.im/fastparallel). [![js-standard-style](https://raw.githubusercontent.com/feross/standard/master/badge.png)](https://github.com/feross/standard) * <a href="#install">Installation</a> * <a href="#usage">Usage</a> * <a href="#api">API</a> * <a href="#license">Licence &amp; copyright</a> ## Install `npm i fastq --save` ## Usage (callback API) ```js 'use strict' const queue = require('fastq')(worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log('the result is', result) }) function worker (arg, cb) { cb(null, arg * 2) } ``` ## Usage (promise API) ```js const queue = require('fastq').promise(worker, 1) async function worker (arg) { return arg * 2 } async function run () { const result = await queue.push(42) console.log('the result is', result) } run() ``` ### Setting "this" ```js 'use strict' const that = { hello: 'world' } const queue = require('fastq')(that, worker, 1) queue.push(42, function (err, result) { if (err) { throw err } console.log(this) console.log('the result is', result) }) function worker (arg, cb) { console.log(this) cb(null, arg * 2) } ``` ### Using with TypeScript (callback API) ```ts 'use strict' import * as fastq from "fastq"; import type { queue, done } from "fastq"; type Task = { id: number } const q: queue<Task> = fastq(worker, 1) q.push({ id: 42}) function worker (arg: Task, cb: done) { console.log(arg.id) cb(null) } ``` ### Using with TypeScript (promise API) ```ts 'use strict' import * as fastq from "fastq"; import type { queueAsPromised } from "fastq"; type Task = { id: number } const q: queueAsPromised<Task> = fastq.promise(asyncWorker, 1) q.push({ id: 42}).catch((err) => console.error(err)) async function asyncWorker (arg: Task): Promise<void> { // No need for a try-catch block, fastq handles errors automatically console.log(arg.id) } ``` ## API * <a href="#fastqueue"><code>fastqueue()</code></a> * <a href="#push"><code>queue#<b>push()</b></code></a> * <a href="#unshift"><code>queue#<b>unshift()</b></code></a> * <a href="#pause"><code>queue#<b>pause()</b></code></a> * <a href="#resume"><code>queue#<b>resume()</b></code></a> * <a href="#idle"><code>queue#<b>idle()</b></code></a> * <a href="#length"><code>queue#<b>length()</b></code></a> * <a href="#getQueue"><code>queue#<b>getQueue()</b></code></a> * <a href="#kill"><code>queue#<b>kill()</b></code></a> * <a href="#killAndDrain"><code>queue#<b>killAndDrain()</b></code></a> * <a href="#error"><code>queue#<b>error()</b></code></a> * <a href="#concurrency"><code>queue#<b>concurrency</b></code></a> * <a href="#drain"><code>queue#<b>drain</b></code></a> * <a href="#empty"><code>queue#<b>empty</b></code></a> * <a href="#saturated"><code>queue#<b>saturated</b></code></a> * <a href="#promise"><code>fastqueue.promise()</code></a> ------------------------------------------------------- <a name="fastqueue"></a> ### fastqueue([that], worker, concurrency) Creates a new queue. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. * `concurrency`, number of concurrent tasks that could be executed in parallel. ------------------------------------------------------- <a name="push"></a> ### queue.push(task, done) Add a task at the end of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="unshift"></a> ### queue.unshift(task, done) Add a task at the beginning of the queue. `done(err, result)` will be called when the task was processed. ------------------------------------------------------- <a name="pause"></a> ### queue.pause() Pause the processing of tasks. Currently worked tasks are not stopped. ------------------------------------------------------- <a name="resume"></a> ### queue.resume() Resume the processing of tasks. ------------------------------------------------------- <a name="idle"></a> ### queue.idle() Returns `false` if there are tasks being processed or waiting to be processed. `true` otherwise. ------------------------------------------------------- <a name="length"></a> ### queue.length() Returns the number of tasks waiting to be processed (in the queue). ------------------------------------------------------- <a name="getQueue"></a> ### queue.getQueue() Returns all the tasks be processed (in the queue). Returns empty array when there are no tasks ------------------------------------------------------- <a name="kill"></a> ### queue.kill() Removes all tasks waiting to be processed, and reset `drain` to an empty function. ------------------------------------------------------- <a name="killAndDrain"></a> ### queue.killAndDrain() Same than `kill` but the `drain` function will be called before reset to empty. ------------------------------------------------------- <a name="error"></a> ### queue.error(handler) Set a global error handler. `handler(err, task)` will be called when any of the tasks return an error. ------------------------------------------------------- <a name="concurrency"></a> ### queue.concurrency Property that returns the number of concurrent tasks that could be executed in parallel. It can be altered at runtime. ------------------------------------------------------- <a name="drain"></a> ### queue.drain Function that will be called when the last item from the queue has been processed by a worker. It can be altered at runtime. ------------------------------------------------------- <a name="empty"></a> ### queue.empty Function that will be called when the last item from the queue has been assigned to a worker. It can be altered at runtime. ------------------------------------------------------- <a name="saturated"></a> ### queue.saturated Function that will be called when the queue hits the concurrency limit. It can be altered at runtime. ------------------------------------------------------- <a name="promise"></a> ### fastqueue.promise([that], worker(arg), concurrency) Creates a new queue with `Promise` apis. It also offers all the methods and properties of the object returned by [`fastqueue`](#fastqueue) with the modified [`push`](#pushPromise) and [`unshift`](#unshiftPromise) methods. Node v10+ is required to use the promisified version. Arguments: * `that`, optional context of the `worker` function. * `worker`, worker function, it would be called with `that` as `this`, if that is specified. It MUST return a `Promise`. * `concurrency`, number of concurrent tasks that could be executed in parallel. <a name="pushPromise"></a> #### queue.push(task) => Promise Add a task at the end of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="unshiftPromise"></a> #### queue.unshift(task) => Promise Add a task at the beginning of the queue. The returned `Promise` will be fulfilled (rejected) when the task is completed successfully (unsuccessfully). This promise could be ignored as it will not lead to a `'unhandledRejection'`. <a name="drained"></a> #### queue.drained() => Promise Wait for the queue to be drained. The returned `Promise` will be resolved when all tasks in the queue have been processed by a worker. This promise could be ignored as it will not lead to a `'unhandledRejection'`. ## License ISC [ci-url]: https://github.com/mcollina/fastq/workflows/ci/badge.svg [npm-badge]: https://badge.fury.io/js/fastq.svg [npm-url]: https://badge.fury.io/js/fastq [david-badge]: https://david-dm.org/mcollina/fastq.svg [david-url]: https://david-dm.org/mcollina/fastq # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # cacheable-request > Wrap native HTTP requests with RFC compliant cache support [![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters. **Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. ## Features - Only stores cacheable responses as defined by RFC 7234 - Fresh cache entries are served directly from cache - Stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers - 304 responses from revalidation requests use cached body - Updates `Age` header on cached responses - Can completely bypass cache on a per request basis - In memory cache by default - Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters - Easily plug in your own or third-party storage adapters - If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) - Adds cache support to any existing HTTP code with minimal changes - Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance ## Install ```shell npm install cacheable-request ``` ## Usage ```js const http = require('http'); const CacheableRequest = require('cacheable-request'); // Then instead of const req = http.request('http://example.com', cb); req.end(); // You can do const cacheableRequest = new CacheableRequest(http.request); const cacheReq = cacheableRequest('http://example.com', cb); cacheReq.on('request', req => req.end()); // Future requests to 'example.com' will be returned from cache if still valid // You pass in any other http.request API compatible method to be wrapped with cache support: const cacheableRequest = new CacheableRequest(https.request); const cacheableRequest = new CacheableRequest(electron.net); ``` ## Storage Adapters `cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: ``` npm install @keyv/redis ``` And then you can pass `CacheableRequest` your connection string: ```js const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); ``` [View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. e.g The following are all valid storage adapters ```js const storageAdapter = new Map(); // or const storageAdapter = require('./my-storage-adapter'); // or const QuickLRU = require('quick-lru'); const storageAdapter = new QuickLRU({ maxSize: 1000 }); const cacheableRequest = new CacheableRequest(http.request, storageAdapter); ``` View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. ## API ### new cacheableRequest(request, [storageAdapter]) Returns the provided request function wrapped with cache support. #### request Type: `function` Request function to wrap with cache support. Should be [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) or a similar API compatible request function. #### storageAdapter Type: `Keyv storage adapter`<br> Default: `new Map()` A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. ### Instance #### cacheableRequest(opts, [cb]) Returns an event emitter. ##### opts Type: `object`, `string` - Any of the default request functions options. - Any [`http-cache-semantics`](https://github.com/kornelski/http-cache-semantics#constructor-options) options. - Any of the following: ###### opts.cache Type: `boolean`<br> Default: `true` If the cache should be used. Setting this to false will completely bypass the cache for the current request. ###### opts.strictTtl Type: `boolean`<br> Default: `false` If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. If set to `false` (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with `If-None-Match`/`If-Modified-Since` headers. ###### opts.maxTtl Type: `number`<br> Default: `undefined` Limits TTL. The `number` represents milliseconds. ###### opts.automaticFailover Type: `boolean`<br> Default: `false` When set to `true`, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed. ###### opts.forceRefresh Type: `boolean`<br> Default: `false` Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead. ##### cb Type: `function` The callback function which will receive the response as an argument. The response can be either a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) or a [responselike object](https://github.com/lukechilds/responselike). The response will also have a `fromCache` property set with a boolean value. ##### .on('request', request) `request` event to get the request object of the request. **Note:** This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the `request` event to end the request and handle any potential request errors. ##### .on('response', response) `response` event to get the response object from the HTTP request or cache. ##### .on('error', error) `error` event emitted in case of an error with the cache. Errors emitted here will be an instance of `CacheableRequest.RequestError` or `CacheableRequest.CacheError`. You will only ever receive a `RequestError` if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the `request` event. To properly handle all error scenarios you should use the following pattern: ```js cacheableRequest('example.com', cb) .on('error', err => { if (err instanceof CacheableRequest.CacheError) { handleCacheError(err); // Cache error } else if (err instanceof CacheableRequest.RequestError) { handleRequestError(err); // Request function thrown } }) .on('request', req => { req.on('error', handleRequestError); // Request error emitted req.end(); }); ``` **Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. ## License MIT © Luke Childs # near-api-js [![Build Status](https://travis-ci.com/near/near-api-js.svg?branch=master)](https://travis-ci.com/near/near-api-js) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-api-js) A JavaScript/TypeScript library for development of DApps on the NEAR platform # Documentation [Read the TypeDoc API documentation](https://near.github.io/near-api-js/) --- # Examples ## [Quick Reference](https://github.com/near/near-api-js/blob/master/examples/quick-reference.md) _(Cheat sheet / quick reference)_ ## [Cookbook](https://github.com/near/near-api-js/blob/master/examples/cookbook/README.md) _(Common use cases / more complex examples)_ --- # Contribute to this library 1. Install dependencies yarn 2. Run continuous build with: yarn build -- -w # Publish Prepare `dist` version by running: yarn dist When publishing to npm use [np](https://github.com/sindresorhus/np). --- # Integration Test Start the node by following instructions from [nearcore](https://github.com/nearprotocol/nearcore), then yarn test Tests use sample contract from `near-hello` npm package, see https://github.com/nearprotocol/near-hello # Update error schema Follow next steps: 1. [Change hash for the commit with errors in the nearcore](https://github.com/near/near-api-js/blob/master/gen_error_types.js#L7-L9) 2. Fetch new schema: `node fetch_error_schema.js` 3. `yarn build` to update `lib/**.js` files # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # Javascript Error Polyfill [![Build Status](https://travis-ci.org/inf3rno/error-polyfill.png?branch=master)](https://travis-ci.org/inf3rno/error-polyfill) Implementing the [V8 Stack Trace API](https://github.com/v8/v8/wiki/Stack-Trace-API) in non-V8 environments as much as possible ## Installation ```bash npm install error-polyfill ``` ```bash bower install error-polyfill ``` ### Environment compatibility Tested on the following environments: Windows 7 - **Node.js** 9.6 - **Chrome** 64.0 - **Firefox** 58.0 - **Internet Explorer** 10.0, 11.0 - **PhantomJS** 2.1 - **Opera** 51.0 Travis - **Node.js** 8, 9 - **Chrome** - **Firefox** - **PhantomJS** The polyfill might work on other environments too due to its adaptive design. I use [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. ### Requirements ES5 support is required, without that the lib throws an Error and stops working. The ES5 features are tested by the [capability](https://github.com/inf3rno/capability) lib run time. Classes are created by the [o3](https://github.com/inf3rno/o3) lib. Utility functions are implemented in the [u3](https://github.com/inf3rno/u3) lib. ## API documentation ### Usage In this documentation I used the framework as follows: ```js require("error-polyfill"); // <- your code here ``` It is recommended to require the polyfill in your main script. ### Getting a past stack trace with `Error.getStackTrace` This static method is not part of the V8 Stack Trace API, but it is recommended to **use `Error.getStackTrace(throwable)` instead of `throwable.stack`** to get the stack trace of Error instances! Explanation: By non-V8 environments we cannot replace the default stack generation algorithm, so we need a workaround to generate the stack when somebody tries to access it. So the original stack string will be parsed and the result will be properly formatted by accessing the stack using the `Error.getStackTrace` method. Arguments and return values: - The `throwable` argument should be an `Error` (descendant) instance, but it can be an `Object` instance as well. - The return value is the generated `stack` of the `throwable` argument. Example: ```js try { theNotDefinedFunction(); } catch (error) { console.log(Error.getStackTrace(error)); // ReferenceError: theNotDefinedFunction is not defined // at ... // ... } ``` ### Capturing the present stack trace with `Error.captureStackTrace` The `Error.captureStackTrace(throwable [, terminator])` sets the present stack above the `terminator` on the `throwable`. Arguments and return values: - The `throwable` argument should be an instance of an `Error` descendant, but it can be an `Object` instance as well. It is recommended to use `Error` descendant instances instead of inline objects, because we can recognize them by type e.g. `error instanceof UserError`. - The optional `terminator` argument should be a `Function`. Only the calls before this function will be reported in the stack, so without a `terminator` argument, the last call in the stack will be the call of the `Error.captureStackTrace`. - There is no return value, the `stack` will be set on the `throwable` so you will be able to access it using `Error.getStackTrace`. The format of the stack depends on the `Error.prepareStackTrace` implementation. Example: ```js var UserError = function (message){ this.name = "UserError"; this.message = message; Error.captureStackTrace(this, this.constructor); }; UserError.prototype = Object.create(Error.prototype); function codeSmells(){ throw new UserError("What's going on?!"); } codeSmells(); // UserError: What's going on?! // at codeSmells (myModule.js:23:1) // ... ``` Limitations: By the current implementation the `terminator` can be only the `Error.captureStackTrace` caller function. This will change soon, but in certain conditions, e.g. by using strict mode (`"use strict";`) it is not possible to access the information necessary to implement this feature. You will get an empty `frames` array and a `warning` in the `Error.prepareStackTrace` when the stack parser meets with such conditions. ### Formatting the stack trace with `Error.prepareStackTrace` The `Error.prepareStackTrace(throwable, frames [, warnings])` formats the stack `frames` and returns the `stack` value for `Error.captureStackTrace` or `Error.getStackTrace`. The native implementation returns a stack string, but you can override that by setting a new function value. Arguments and return values: - The `throwable` argument is an `Error` or `Object` instance coming from the `Error.captureStackTrace` or from the creation of a new `Error` instance. Be aware that in some environments you need to throw that instance to get a parsable stack. Without that you will get only a `warning` by trying to access the stack with `Error.getStackTrace`. - The `frames` argument is an array of `Frame` instances. Each `frame` represents a function call in the stack. You can use these frames to build a stack string. To access information about individual frames you can use the following methods. - `frame.toString()` - Returns the string representation of the frame, e.g. `codeSmells (myModule.js:23:1)`. - `frame.getThis()` - **Cannot be supported.** Returns the context of the call, only V8 environments support this natively. - `frame.getTypeName()` - **Not implemented yet.** Returns the type name of the context, by the global namespace it is `Window` in Chrome. - `frame.getFunction()` - Returns the called function or `undefined` by strict mode. - `frame.getFunctionName()` - **Not implemented yet.** Returns the name of the called function. - `frame.getMethodName()` - **Not implemented yet.** Returns the method name of the called function is a method of an object. - `frame.getFileName()` - **Not implemented yet.** Returns the file name where the function was called. - `frame.getLineNumber()` - **Not implemented yet.** Returns at which line the function was called in the file. - `frame.getColumnNumber()` - **Not implemented yet.** Returns at which column the function was called in the file. This information is not always available. - `frame.getEvalOrigin()` - **Not implemented yet.** Returns the original of an `eval` call. - `frame.isTopLevel()` - **Not implemented yet.** Returns whether the function was called from the top level. - `frame.isEval()` - **Not implemented yet.** Returns whether the called function was `eval`. - `frame.isNative()` - **Not implemented yet.** Returns whether the called function was native. - `frame.isConstructor()` - **Not implemented yet.** Returns whether the called function was a constructor. - The optional `warnings` argument contains warning messages coming from the stack parser. It is not part of the V8 Stack Trace API. - The return value will be the stack you can access with `Error.getStackTrace(throwable)`. If it is an object, it is recommended to add a `toString` method, so you will be able to read it in the console. Example: ```js Error.prepareStackTrace = function (throwable, frames, warnings) { var string = ""; string += throwable.name || "Error"; string += ": " + (throwable.message || ""); if (warnings instanceof Array) for (var warningIndex in warnings) { var warning = warnings[warningIndex]; string += "\n # " + warning; } for (var frameIndex in frames) { var frame = frames[frameIndex]; string += "\n at " + frame.toString(); } return string; }; ``` ### Stack trace size limits with `Error.stackTraceLimit` **Not implemented yet.** You can set size limits on the stack trace, so you won't have any problems because of too long stack traces. Example: ```js Error.stackTraceLimit = 10; ``` ### Handling uncaught errors and rejections **Not implemented yet.** ## Differences between environments and modes Since there is no Stack Trace API standard, every browsers solves this problem differently. I try to document what I've found about these differences as detailed as possible, so it will be easier to follow the code. Overriding the `error.stack` property with custom Stack instances - by Node.js and Chrome the `Error.prepareStackTrace()` can override every `error.stack` automatically right by creation - by Firefox, Internet Explorer and Opera you cannot automatically override every `error.stack` by native errors - by PhantomJS you cannot override the `error.stack` property of native errors, it is not configurable Capturing the current stack trace - by Node.js, Chrome, Firefox and Opera the stack property is added by instantiating a native error - by Node.js and Chrome the stack creation is lazy loaded and cached, so the `Error.prepareStackTrace()` is called only by the first access - by Node.js and Chrome the current stack can be added to any object with `Error.captureStackTrace()` - by Internet Explorer the stack is created by throwing a native error - by PhantomJS the stack is created by throwing any object, but not a primitive Accessing the stack - by Node.js, Chrome, Firefox, Internet Explorer, Opera and PhantomJS you can use the `error.stack` property - by old Opera you have to use the `error.stacktrace` property to get the stack Prefixes and postfixes on the stack string - by Node.js, Chrome, Internet Explorer and Opera you have the `error.name` and the `error.message` in a `{name}: {message}` format at the beginning of the stack string - by Firefox and PhantomJS the stack string does not contain the `error.name` and the `error.message` - by Firefox you have an empty line at the end of the stack string Accessing the stack frames array - by Node.js and Chrome you can access the frame objects directly by overriding the `Error.prepareStackTrace()` - by Firefox, Internet Explorer, PhantomJS, and Opera you need to parse the stack string in order to get the frames The structure of the frame string - by Node.js and Chrome - the frame string of calling a function from a module: `thirdFn (http://localhost/myModule.js:45:29)` - the frame strings contain an ` at ` prefix, which is not present by the `frame.toString()` output, so it is added by the `stack.toString()` - by Firefox - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Internet Explorer - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45:29)` - by PhantomJS - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Opera - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45)` Accessing information by individual frames - by Node.js and Chrome the `frame.getThis()` and the `frame.getFunction()` returns `undefined` by frames originate from [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) code - by Firefox, Internet Explorer, PhantomJS, and Opera the context of the function calls is not accessible, so the `frame.getThis()` cannot be implemented - by Firefox, Internet Explorer, PhantomJS, and Opera functions are not accessible with `arguments.callee.caller` by frames originate from strict mode, so by these frames `frame.getFunction()` can return only `undefined` (this is consistent with V8 behavior) ## License MIT - 2016 Jánszky László Lajos ## Follow Redirects Drop-in replacement for Node's `http` and `https` modules that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://github.com/follow-redirects/follow-redirects/workflows/CI/badge.svg)](https://github.com/follow-redirects/follow-redirects/actions) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Sponsor on GitHub](https://img.shields.io/static/v1?label=Sponsor&message=%F0%9F%92%96&logo=GitHub)](https://github.com/sponsors/RubenVerborgh) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript const { http, https } = require('follow-redirects'); http.get('http://bit.ly/900913', response => { response.on('data', chunk => { console.log(chunk); }); }).on('error', err => { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript const request = https.request({ host: 'bitly.com', path: '/UHfDGO', }, response => { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); request.end(); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript const followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript const url = require('url'); const { http, https } = require('follow-redirects'); const options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; options.beforeRedirect = (options, response, request) => { // Use this to adjust the request options upon redirecting, // to inspect the latest response headers, // or to cancel the request by throwing an error // response.headers = the redirect response headers // response.statusCode = the redirect response code (eg. 301, 307, etc.) // request.url = the requested URL that resulted in a redirect // request.headers = the headers in the request that resulted in a redirect // request.method = the method of the request that resulted in a redirect if (options.hostname === "example.com") { options.auth = "user:password"; } }; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `beforeRedirect` (default: `undefined`) – optionally change the request `options` on redirects, or abort the request by throwing an error. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript const { http, https } = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browser Usage Due to the way the browser works, the `http` and `https` browser equivalents perform redirects by default. By requiring `follow-redirects` this way: ```javascript const http = require('follow-redirects/http'); const https = require('follow-redirects/https'); ``` you can easily tell webpack and friends to replace `follow-redirect` by the built-in versions: ```json { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - [Ruben Verborgh](https://ruben.verborgh.org/) - [Olivier Lalonde](mailto:[email protected]) - [James Talmage](mailto:[email protected]) ## License [MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE) # jest-mock ## API ```js import {ModuleMocker} from 'jest-mock'; ``` ### `constructor(global)` Creates a new module mocker that generates mocks as if they were created in an environment with the given global object. ### `generateFromMetadata(metadata)` Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the getMetadata method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn` in this module. One important note: function prototypes are handled specially by this mocking framework. For functions with prototypes, when called as a constructor, the mock will install mocked function members on the instance. This allows different instances of the same constructor to have different values for its mocks member and its return values. ### `getMetadata(component)` Inspects the argument and returns its schema in the following recursive format: ``` { type: ... members: {} } ``` Where type is one of `array`, `object`, `function`, or `ref`, and members is an optional dictionary where the keys are member names and the values are metadata objects. Function prototypes are defined by defining metadata for the `member.prototype` of the function. The type of a function prototype should always be `object`. For instance, a class might be defined like this: ```js const classDef = { type: 'function', members: { staticMethod: {type: 'function'}, prototype: { type: 'object', members: { instanceMethod: {type: 'function'}, }, }, }, }; ``` Metadata may also contain references to other objects defined within the same metadata object. The metadata for the referent must be marked with `refID` key and an arbitrary value. The referrer must be marked with a `ref` key that has the same value as object with refID that it refers to. For instance, this metadata blob: ```js const refID = { type: 'object', refID: 1, members: { self: {ref: 1}, }, }; ``` defines an object with a slot named `self` that refers back to the object. ### `fn` Generates a stand-alone function with members that help drive unit tests or confirm expectations. Specifically, functions returned by this method have the following members: ##### `.mock` An object with three members, `calls`, `instances` and `invocationCallOrder`, which are all lists. The items in the `calls` list are the arguments with which the function was called. The "instances" list stores the value of 'this' for each call to the function. This is useful for retrieving instances from a constructor. The `invocationCallOrder` lists the order in which the mock was called in relation to all mock calls, starting at 1. ##### `.mockReturnValueOnce(value)` Pushes the given value onto a FIFO queue of return values for the function. ##### `.mockReturnValue(value)` Sets the default return value for the function. ##### `.mockImplementationOnce(function)` Pushes the given mock implementation onto a FIFO queue of mock implementations for the function. ##### `.mockImplementation(function)` Sets the default mock implementation for the function. ##### `.mockReturnThis()` Syntactic sugar for .mockImplementation(function() {return this;}) In case both `mockImplementationOnce()/mockImplementation()` and `mockReturnValueOnce()/mockReturnValue()` are called. The priority of which to use is based on what is the last call: - if the last call is mockReturnValueOnce() or mockReturnValue(), use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try mockImplementation(); - if the last call is mockImplementationOnce() or mockImplementation(), run the specific implementation and return the result or run default implementation and return the result. [![npm version][npm-image]][npm-url] [![build status][travis-image]][travis-url] # u2f-api U2F API for browsers ## API ### Support U2F has for a long time been supported in Chrome, although not with the standard `window.u2f` methods, but through a built-in extension. Nowadays, browsers seem to use `window.u2f` to expose the functionality. Supported browsers are: * Chrome, using Chrome-specific hacks * Opera, using Chrome-specific hacks Firefox, Safari and other browsers still lack U2F support. Since 0.1.0, this library supports the standard `window.u2f` methods. The library should be complemented with server-side functionality, e.g. using the [`u2f`](https://www.npmjs.com/package/u2f) package. ### Basics `u2f-api` exports two main functions and an error "enum". The main functions are `register()` and `sign()`, although since U2F isn't widely supported, the functions `isSupported()` as well as `ensureSupport()` helps you build applications which can use U2F only when the client supports it. The `register()` and `sign()` functions return *cancellable promises*, i.e. promises you can cancel manually. This helps you to ensure your code doesn't continue in success flow and by mistake accept a registration or authentification request. The returned promise has a function `cancel()` which will immediately reject the promise. #### Check or ensure support ```ts import { isSupported } from 'u2f-api' isSupported(): Promise< Boolean > // Doesn't throw/reject ``` ```ts import { ensureSupport } from 'u2f-api' ensureSupport(): Promise< void > // Throws/rejects if not supported ``` #### Register ```ts import { register } from 'u2f-api' register( registerRequests: RegisterRequest[], signRequests: SignRequest[], // optional timeout: number // optional ): Promise< RegisterResponse > ``` The `registerRequests` can be either a RegisterRequest or an array of such. The optional `signRequests` must be, unless ignored, an array of SignRequests. The optional `timeout` is in seconds, and will default to an implementation specific value, e.g. 30. #### Sign ```ts import { sign } from 'u2f-api' sign( signRequests: SignRequest[], timeout: number // optional ): Promise< SignResponse > ``` The values and interpretation of the arguments are the same as with `register( )`. #### Errors `register()` and `sign()` can return rejected promises. The rejection error is an `Error` object with a `metaData` property containing `code` and `type`. The `code` is a numerical value describing the type of the error, and `type` is the name of the error, as defined by the `ErrorCodes` enum in the "FIDO U2F Javascript API" specification. They are: ```js OK = 0 // u2f-api will never throw errors with this code OTHER_ERROR = 1 BAD_REQUEST = 2 CONFIGURATION_UNSUPPORTED = 3 DEVICE_INELIGIBLE = 4 TIMEOUT = 5 CANCELLED = -1 // Added by this library ``` ## Usage ### Loading the library The library is promisified and will use the built-in native promises of the browser, unless another promise library is injected. The following are valid ways to load the library: ```js var u2fApi = require( 'u2f-api' ); // Will use the native Promise // ... or var u2fApi = require( 'u2f-api' )( require( 'bluebird' ) ); // Will use bluebird for promises ``` ### Registering a passkey With `registerRequestsFromServer` somehow received from the server, the client code becomes: ```js u2fApi.register( registerRequestsFromServer ) .then( sendRegisterResponseToServer ) .catch( ... ); ``` ### Signing a passkey With `signRequestsFromServer` also received from the server somehow: ```js u2fApi.sign( signRequestsFromServer ) .then( sendSignResponseToServer ) .catch( ... ); ``` ### Example with checks for client support ```js u2fApi.isSupported( ) .then( function( supported ) { if ( supported ) { return u2fApi.sign( signRequestsFromServer ) .then( sendSignResponseToServer ); } else { ... // Other authentication method } } ) .catch( ... ); ``` ### Canceling As mentioned in the API section above, the returned promises from `register()` and `sign()` have a method `cancel()` which will cancel the request. This is nothing more than a helper function. ## Example implementation U2F is a *challenge-response protocol*. The server sends a `challenge` to the client, which responds with a `response`. This library is intended to be used in the client (the browser). There is another package intended for server-side: https://www.npmjs.com/package/u2f ## Common problems If you get `BAD_REQUEST`, the most common situations are that you either don't use `https` (which you must), or that the AppID doesn't match the server URI. In fact, the AppID must be exactly the base URI to your server (such as `https://your-server.com`), including the port if it isn't 443. For more information, please see https://developers.yubico.com/U2F/Libraries/Client_error_codes.html and https://developers.yubico.com/U2F/App_ID.html [npm-image]: https://img.shields.io/npm/v/u2f-api.svg [npm-url]: https://npmjs.org/package/u2f-api [travis-image]: https://img.shields.io/travis/grantila/u2f-api.svg [travis-url]: https://travis-ci.org/grantila/u2f-api # BIP39 [![Build Status](https://travis-ci.org/bitcoinjs/bip39.png?branch=master)](https://travis-ci.org/bitcoinjs/bip39) [![NPM](https://img.shields.io/npm/v/bip39.svg)](https://www.npmjs.org/package/bip39) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) JavaScript implementation of [Bitcoin BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki): Mnemonic code for generating deterministic keys ## Reminder for developers ***Please remember to allow recovery from mnemonic phrases that have invalid checksums (or that you don't have the wordlist)*** When a checksum is invalid, warn the user that the phrase is not something generated by your app, and ask if they would like to use it anyway. This way, your app only needs to hold the wordlists for your supported languages, but you can recover phrases made by other apps in other languages. However, there should be other checks in place, such as checking to make sure the user is inputting 12 words or more separated by a space. ie. `phrase.trim().split(/\s+/g).length >= 12` ## Removing wordlists from webpack/browserify Browserify/Webpack bundles can get very large if you include all the wordlists, so you can now exclude wordlists to make your bundle lighter. For example, if we want to exclude all wordlists besides chinese_simplified, you could build using the browserify command below. ```bash $ browserify -r bip39 -s bip39 \ --exclude=./wordlists/english.json \ --exclude=./wordlists/japanese.json \ --exclude=./wordlists/spanish.json \ --exclude=./wordlists/italian.json \ --exclude=./wordlists/french.json \ --exclude=./wordlists/korean.json \ --exclude=./wordlists/chinese_traditional.json \ > bip39.browser.js ``` This will create a bundle that only contains the chinese_simplified wordlist, and it will be the default wordlist for all calls without explicit wordlists. You can also do this in Webpack using the `IgnorePlugin`. Here is an example of excluding all non-English wordlists ```javascript ... plugins: [ new webpack.IgnorePlugin(/^\.\/(?!english)/, /bip39\/src\/wordlists$/), ], ... ``` This is how it will look in the browser console. ```javascript > bip39.entropyToMnemonic('00000000000000000000000000000000') "的 的 的 的 的 的 的 的 的 的 的 在" > bip39.wordlists.chinese_simplified Array(2048) [ "的", "一", "是", "在", "不", "了", "有", "和", "人", "这", … ] > bip39.wordlists.english undefined > bip39.wordlists.japanese undefined > bip39.wordlists.spanish undefined > bip39.wordlists.italian undefined > bip39.wordlists.french undefined > bip39.wordlists.korean undefined > bip39.wordlists.chinese_traditional undefined ``` For a list of supported wordlists check the wordlists folder. The name of the json file (minus the extension) is the name of the key to access the wordlist. You can also change the default wordlist at runtime if you dislike the wordlist you were given as default. ```javascript > bip39.entropyToMnemonic('00000000000000000000000000000fff') "あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あまい ろんり" > bip39.setDefaultWordlist('italian') undefined > bip39.entropyToMnemonic('00000000000000000000000000000fff') "abaco abaco abaco abaco abaco abaco abaco abaco abaco abaco aforisma zibetto" ``` ## Installation ``` bash npm install bip39 ``` ## Examples ``` js // Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 128-bits of entropy const mnemonic = bip39.generateMnemonic() // => 'seed sock milk update focus rotate barely fade car face mechanic mercy' bip39.mnemonicToSeedSync('basket actual').toString('hex') // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeedSync('basket actual') // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> // mnemonicToSeed has an synchronous version // mnemonicToSeedSync is less performance oriented bip39.mnemonicToSeed('basket actual').then(console.log) // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> bip39.mnemonicToSeed('basket actual').then(bytes => bytes.toString('hex')).then(console.log) // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeedSync('basket actual', 'a password') // => <Buffer 46 16 a4 4f 2c 90 b9 69 02 14 b8 fd 43 5b b4 14 62 43 de 10 7b 30 87 59 0a 3b b8 d3 1b 2f 3a ef ab 1d 4b 52 6d 21 e5 0a 04 02 3d 7a d0 66 43 ea 68 3b ... > bip39.validateMnemonic(mnemonic) // => true bip39.validateMnemonic('basket actual') // => false ``` ``` js const bip39 = require('bip39') // defaults to BIP39 English word list // uses HEX strings for entropy const mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000') // => abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about // reversible bip39.mnemonicToEntropy(mnemonic) // => '00000000000000000000000000000000' ``` # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # json-buffer JSON functions that can convert buffers! [![build status](https://secure.travis-ci.org/dominictarr/json-buffer.png)](http://travis-ci.org/dominictarr/json-buffer) [![testling badge](https://ci.testling.com/dominictarr/json-buffer.png)](https://ci.testling.com/dominictarr/json-buffer) JSON mangles buffers by converting to an array... which isn't helpful. json-buffers converts to base64 instead, and deconverts base64 to a buffer. ``` js var JSONB = require('json-buffer') var Buffer = require('buffer').Buffer var str = JSONB.stringify(Buffer.from('hello there!')) console.log(JSONB.parse(str)) //GET a BUFFER back ``` ## License MIT # parse-passwd [![NPM version](https://img.shields.io/npm/v/parse-passwd.svg?style=flat)](https://www.npmjs.com/package/parse-passwd) [![NPM downloads](https://img.shields.io/npm/dm/parse-passwd.svg?style=flat)](https://npmjs.org/package/parse-passwd) [![Linux Build Status](https://img.shields.io/travis/doowb/parse-passwd.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/parse-passwd) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/parse-passwd.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/parse-passwd) > Parse a passwd file into a list of users. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save parse-passwd ``` ## Usage ```js var parse = require('parse-passwd'); ``` ## API **Example** ```js // assuming '/etc/passwd' contains: // doowb:*:123:123:Brian Woodward:/Users/doowb:/bin/bash console.log(parse(fs.readFileSync('/etc/passwd', 'utf8'))); //=> [ //=> { //=> username: 'doowb', //=> password: '*', //=> uid: '123', //=> gid: '123', //=> gecos: 'Brian Woodward', //=> homedir: '/Users/doowb', //=> shell: '/bin/bash' //=> } //=> ] ``` **Params** * `content` **{String}**: Content of a passwd file to parse. * `returns` **{Array}**: Array of user objects parsed from the content. ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for avice on opening issues, pull requests, and coding standards. ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Brian Woodward** * [github/doowb](https://github.com/doowb) * [twitter/doowb](http://twitter.com/doowb) ### License Copyright © 2016, [Brian Woodward](https://github.com/doowb). Released under the [MIT license](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 19, 2016._ # ci-info Get details about the current Continuous Integration environment. Please [open an issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info) [![Tests](https://github.com/watson/ci-info/workflows/Tests/badge.svg)](https://github.com/watson/ci-info/actions) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install ci-info --save ``` ## Usage ```js var ci = require('ci-info') if (ci.isCI) { console.log('The name of the CI server is:', ci.name) } else { console.log('This program is not running on a CI server') } ``` ## Supported CI tools Officially supported CI servers: | Name | Constant | isPR | | ------------------------------------------------------------------------------- | -------------------- | ---- | | [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 | | [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ | | [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ | | [Appcircle](https://appcircle.io/) | `ci.APPCIRCLE` | 🚫 | | [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 | | [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ | | [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ | | [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ | | [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ | | [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ | | [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ | | [Codefresh](https://codefresh.io/) | `ci.CODEFRESH` | ✅ | | [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 | | [Drone](https://drone.io) | `ci.DRONE` | ✅ | | [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 | | [Expo Application Services](https://expo.dev/eas) | `ci.EAS` | 🚫 | | [Gerrit CI](https://www.gerritcodereview.com) | `ci.GERRIT` | 🚫 | | [GitHub Actions](https://github.com/features/actions/) | `ci.GITHUB_ACTIONS` | ✅ | | [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | ✅ | | [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 | | [Google Cloud Build](https://cloud.google.com/build) | `ci.GOOGLE_CLOUD_BUILD` | 🚫 | | [Heroku](https://www.heroku.com) | `ci.HEROKU` | 🚫 | | [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 | | [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ | | [LayerCI](https://layerci.com/) | `ci.LAYERCI` | ✅ | | [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 | | [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ | | [Nevercode](http://nevercode.io/) | `ci.NEVERCODE` | ✅ | | [ReleaseHub](https://releasehub.com/) | `ci.RELEASEHUB` | ✅ | | [Render](https://render.com/) | `ci.RENDER` | ✅ | | [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ | | [Screwdriver](https://screwdriver.cd/) | `ci.SCREWDRIVER` | ✅ | | [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ | | [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ | | [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ | | [Sourcehut](https://sourcehut.org/) | `ci.SOURCEHUT` | 🚫 | | [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 | | [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 | | [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 | | [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ | | [Vercel](https://vercel.com/) | `ci.VERCEL` | 🚫 | | [Visual Studio App Center](https://appcenter.ms/) | `ci.APPCENTER` | 🚫 | | [Woodpecker](https://woodpecker-ci.org/) | `ci.WOODPECKER` | ✅ | ## API ### `ci.name` Returns a string containing name of the CI server the code is running on. If CI server is not detected, it returns `null`. Don't depend on the value of this string not to change for a specific vendor. If you find your self writing `ci.name === 'Travis CI'`, you most likely want to use `ci.TRAVIS` instead. ### `ci.isCI` Returns a boolean. Will be `true` if the code is running on a CI server, otherwise `false`. Some CI servers not listed here might still trigger the `ci.isCI` boolean to be set to `true` if they use certain vendor neutral environment variables. In those cases `ci.name` will be `null` and no vendor specific boolean will be set to `true`. ### `ci.isPR` Returns a boolean if PR detection is supported for the current CI server. Will be `true` if a PR is being tested, otherwise `false`. If PR detection is not supported for the current CI server, the value will be `null`. ### `ci.<VENDOR-CONSTANT>` A vendor specific boolean constant is exposed for each support CI vendor. A constant will be `true` if the code is determined to run on the given CI server, otherwise `false`. Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a complete list, see the support table above. Deprecated vendor constants that will be removed in the next major release: - `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO` ## Ports ci-info has been ported to the following languages | Language | Repository | |----------|------------| | Go | https://github.com/hofstadter-io/cinful | | Rust | https://github.com/sagiegurari/ci_info | | Kotlin | https://github.com/cloudflightio/ci-info | ## License [MIT](LICENSE) # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- -- This file is auto-generated from README_js.md. Changes should be made there. --> # uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ABrowser) For the creation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDs - **Complete** - Support for RFC4122 version 1, 3, 4, and 5 UUIDs - **Cross-platform** - Support for ... - CommonJS, [ECMAScript Modules](#ecmascript-modules) and [CDN builds](#cdn-builds) - Node 8, 10, 12, 14 - Chrome, Safari, Firefox, Edge, IE 11 browsers - Webpack and rollup.js module bundlers - [React Native / Expo](#react-native--expo) - **Secure** - Cryptographically-strong random values - **Small** - Zero-dependency, small footprint, plays nice with "tree shaking" packagers - **CLI** - Includes the [`uuid` command line](#command-line) utility **Upgrading from `[email protected]`?** Your code is probably okay, but check out [Upgrading From `[email protected]`](#upgrading-from-uuid3x) for details. ## Quickstart To create a random UUID... **1. Install** ```shell npm install uuid ``` **2. Create a UUID** (ES6 module syntax) ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' ``` ... or using CommonJS syntax: ```javascript const { v4: uuidv4 } = require('uuid'); uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` For timestamp UUIDs, namespace UUIDs, and other options read on ... ## API Summary | | | | | --- | --- | --- | | [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `[email protected]` | | [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `[email protected]` | | [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `[email protected]` | | [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | | [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | | [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | | [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | | [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `[email protected]` | | [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `[email protected]` | ## API ### uuid.NIL The nil UUID string (all zeros). Example: ```javascript import { NIL as NIL_UUID } from 'uuid'; NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' ``` ### uuid.parse(str) Convert UUID string to array of bytes | | | | --------- | ---------------------------------------- | | `str` | A valid UUID `String` | | _returns_ | `Uint8Array[16]` | | _throws_ | `TypeError` if `str` is not a valid UUID | Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below. Example: ```javascript import { parse as uuidParse } from 'uuid'; // Parse a UUID const bytes = uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // Convert to hex strings to show byte order (for documentation purposes) [...bytes].map((v) => v.toString(16).padStart(2, '0')); // ⇨ // [ // '6e', 'c0', 'bd', '7f', // '11', 'c0', '43', 'da', // '97', '5e', '2a', '8a', // 'd9', 'eb', 'ae', '0b' // ] ``` ### uuid.stringify(arr[, offset]) Convert array of bytes to UUID string | | | | -------------- | ---------------------------------------------------------------------------- | | `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | | [`offset` = 0] | `Number` Starting index in the Array | | _returns_ | `String` | | _throws_ | `TypeError` if a valid UUID string cannot be generated | Note: Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left &Rarr; right order of hex-pairs in UUID strings. As shown in the example below. Example: ```javascript import { stringify as uuidStringify } from 'uuid'; const uuidBytes = [ 0x6e, 0xc0, 0xbd, 0x7f, 0x11, 0xc0, 0x43, 0xda, 0x97, 0x5e, 0x2a, 0x8a, 0xd9, 0xeb, 0xae, 0x0b, ]; uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' ``` ### uuid.v1([options[, buffer[, offset]]]) Create an RFC version 1 (timestamp) UUID | | | | --- | --- | | [`options`] | `Object` with one or more of the following properties: | | [`options.node` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | | [`options.clockseq`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | | [`options.msecs`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | | [`options.nsecs`] | RFC "timestamp" field (`Number` of nanseconds to add to `msecs`, should be 0-10,000) | | [`options.random`] | `Array` of 16 random bytes (0-255) | | [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | | _throws_ | `Error` if more than 10M UUIDs/sec are requested | Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. Note: `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. Example: ```javascript import { v1 as uuidv1 } from 'uuid'; uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d' ``` Example using `options`: ```javascript import { v1 as uuidv1 } from 'uuid'; const v1options = { node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], clockseq: 0x1234, msecs: new Date('2011-11-01').getTime(), nsecs: 5678, }; uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' ``` ### uuid.v3(name, namespace[, buffer[, offset]]) Create an RFC version 3 (namespace w/ MD5) UUID API is identical to `v5()`, but uses "v3" instead. &#x26a0;&#xfe0f; Note: Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." ### uuid.v4([options[, buffer[, offset]]]) Create an RFC version 4 (random) UUID | | | | --- | --- | | [`options`] | `Object` with one or more of the following properties: | | [`options.random`] | `Array` of 16 random bytes (0-255) | | [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | Example: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` Example using predefined `random` values: ```javascript import { v4 as uuidv4 } from 'uuid'; const v4options = { random: [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36, ], }; uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' ``` ### uuid.v5(name, namespace[, buffer[, offset]]) Create an RFC version 5 (namespace w/ SHA-1) UUID | | | | --- | --- | | `name` | `String \| Array` | | `namespace` | `String \| Array[16]` Namespace UUID | | [`buffer`] | `Array \| Buffer` If specified, uuid will be written here in byte-form, starting at `offset` | | [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | | _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | Note: The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. Example with custom namespace: ```javascript import { v5 as uuidv5 } from 'uuid'; // Define a custom namespace. Readers, create your own using something like // https://www.uuidgenerator.net/ const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' ``` Example with RFC `URL` namespace: ```javascript import { v5 as uuidv5 } from 'uuid'; uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' ``` ### uuid.validate(str) Test a string to see if it is a valid UUID | | | | --------- | --------------------------------------------------- | | `str` | `String` to validate | | _returns_ | `true` if string is a valid UUID, `false` otherwise | Example: ```javascript import { validate as uuidValidate } from 'uuid'; uuidValidate('not a UUID'); // ⇨ false uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true ``` Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. ```javascript import { version as uuidVersion } from 'uuid'; import { validate as uuidValidate } from 'uuid'; function uuidValidateV4(uuid) { return uuidValidate(uuid) && uuidVersion(uuid) === 4; } const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; uuidValidateV4(v4Uuid); // ⇨ true uuidValidateV4(v1Uuid); // ⇨ false ``` ### uuid.version(str) Detect RFC version of a UUID | | | | --------- | ---------------------------------------- | | `str` | A valid UUID `String` | | _returns_ | `Number` The RFC version of the UUID | | _throws_ | `TypeError` if `str` is not a valid UUID | Example: ```javascript import { version as uuidVersion } from 'uuid'; uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 ``` ## Command Line UUIDs can be generated from the command line using `uuid`. ```shell $ uuid ddeb27fb-d9a0-4624-be4d-4615062daed4 ``` The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: ```shell $ uuid --help Usage: uuid uuid v1 uuid v3 <name> <namespace uuid> uuid v4 uuid v5 <name> <namespace uuid> uuid --help Note: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122 ``` ## ECMAScript Modules This library comes with [ECMAScript Modules](https://www.ecma-international.org/ecma-262/6.0/#sec-modules) (ESM) support for Node.js versions that support it ([example](./examples/node-esmodules/)) as well as bundlers like [rollup.js](https://rollupjs.org/guide/en/#tree-shaking) ([example](./examples/browser-rollup/)) and [webpack](https://webpack.js.org/guides/tree-shaking/) ([example](./examples/browser-webpack/)) (targeting both, Node.js and browser environments). ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' ``` To run the examples you must first create a dist build of this library in the module root: ```shell npm run build ``` ## CDN Builds ### ECMAScript Modules To load this module directly into modern browsers that [support loading ECMAScript Modules](https://caniuse.com/#feat=es6-module) you can make use of [jspm](https://jspm.org/): ```html <script type="module"> import { v4 as uuidv4 } from 'https://jspm.dev/uuid'; console.log(uuidv4()); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' </script> ``` ### UMD To load this module directly into older browsers you can use the [UMD (Universal Module Definition)](https://github.com/umdjs/umd) builds from any of the following CDNs: **Using [UNPKG](https://unpkg.com/uuid@latest/dist/umd/)**: ```html <script src="https://unpkg.com/uuid@latest/dist/umd/uuidv4.min.js"></script> ``` **Using [jsDelivr](https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/)**: ```html <script src="https://cdn.jsdelivr.net/npm/uuid@latest/dist/umd/uuidv4.min.js"></script> ``` **Using [cdnjs](https://cdnjs.com/libraries/uuid)**: ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.1.0/uuidv4.min.js"></script> ``` These CDNs all provide the same [`uuidv4()`](#uuidv4options-buffer-offset) method: ```html <script> uuidv4(); // ⇨ '55af1e37-0734-46d8-b070-a1e42e4fc392' </script> ``` Methods for the other algorithms ([`uuidv1()`](#uuidv1options-buffer-offset), [`uuidv3()`](#uuidv3name-namespace-buffer-offset) and [`uuidv5()`](#uuidv5name-namespace-buffer-offset)) are available from the files `uuidv1.min.js`, `uuidv3.min.js` and `uuidv5.min.js` respectively. ## "getRandomValues() not supported" This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: ### React Native / Expo 1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) 1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: ```javascript import 'react-native-get-random-values'; import { v4 as uuidv4 } from 'uuid'; ``` Note: If you are using Expo, you must be using at least `[email protected]` and `[email protected]`. ### Web Workers / Service Workers (Edge <= 18) [In Edge <= 18, Web Crypto is not supported in Web Workers or Service Workers](https://caniuse.com/#feat=cryptography) and we are not aware of a polyfill (let us know if you find one, please). ## Upgrading From `[email protected]` ### Only Named Exports Supported When Using with Node.js ESM `[email protected]` did not come with native ECMAScript Module (ESM) support for Node.js. Importing it in Node.js ESM consequently imported the CommonJS source with a default export. This library now comes with true Node.js ESM support and only provides named exports. Instead of doing: ```javascript import uuid from 'uuid'; uuid.v4(); ``` you will now have to use the named exports: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); ``` ### Deep Requires No Longer Supported Deep requires like `require('uuid/v4')` [which have been deprecated in `[email protected]`](#deep-requires-now-deprecated) are no longer supported. ## Upgrading From `[email protected]` "_Wait... what happened to `[email protected]` - `[email protected]`?!?_" In order to avoid confusion with RFC [version 4](#uuidv4options-buffer-offset) and [version 5](#uuidv5name-namespace-buffer-offset) UUIDs, and a possible [version 6](http://gh.peabody.io/uuidv6/), releases 4 thru 6 of this module have been skipped. ### Deep Requires Now Deprecated `[email protected]` encouraged the use of deep requires to minimize the bundle size of browser builds: ```javascript const uuidv4 = require('uuid/v4'); // <== NOW DEPRECATED! uuidv4(); ``` As of `[email protected]` this library now provides ECMAScript modules builds, which allow packagers like Webpack and Rollup to do "tree-shaking" to remove dead code. Instead, use the `import` syntax: ```javascript import { v4 as uuidv4 } from 'uuid'; uuidv4(); ``` ... or for CommonJS: ```javascript const { v4: uuidv4 } = require('uuid'); uuidv4(); ``` ### Default Export Removed `[email protected]` was exporting the Version 4 UUID method as a default export: ```javascript const uuid = require('uuid'); // <== REMOVED! ``` This usage pattern was already discouraged in `[email protected]` and has been removed in `[email protected]`. ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # yargs-parser ![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/main/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js const argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```console $ node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js const argv = require('yargs-parser')('--foo=99 --bar=33') console.log(argv) ``` ```console { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js const parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## Deno Example As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): ```typescript import parser from "https://deno.land/x/yargs_parser/deno.ts"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` ## ESM Example As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): **Node.js:** ```js import parser from 'yargs-parser' const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) ``` **Browsers:** ```html <!doctype html> <body> <script type="module"> import parser from "https://unpkg.com/[email protected]/browser.js"; const argv = parser('--foo=99 --bar=9987930', { string: ['bar'] }) console.log(argv) </script> </body> ``` ## API ### parser(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.<br> Indicate that keys should be parsed as an array and coerced to booleans / numbers:<br> `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error). For arrays the function is called only once for the entire array:<br> `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:<br> `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.number`: keys should be treated as numbers. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion: * `boolean`: `{ fooBar: true }` * `defaulted`: any new argument created by `opts.default`, no aliases included. * `boolean`: `{ foo: true }` * `configuration`: given by default settings and `opts.configuration`. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```console $ node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```console $ node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```console $ node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```console $ node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```console $ node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```console $ node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```console $ node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```console $ node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### parse positional numbers * default: `true` * key: `parse-positional-numbers` Should positional keys that look like numbers be treated as such. ```console $ node example.js 99.3 { _: [99.3] } ``` _if disabled:_ ```console $ node example.js 99.3 { _: ['99.3'] } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```console $ node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```console $ node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```console $ node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```console $ node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```console $ node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### greedy arrays * default: `true` * key: `greedy-arrays` Should arrays consume more than one positional argument following their flag. ```console $ node example --arr 1 2 { _: [], arr: [1, 2] } ``` _if disabled:_ ```console $ node example --arr 1 2 { _: [2], arr: [1] } ``` **Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** ### nargs eats options * default: `false` * key: `nargs-eats-options` Should nargs consume dash options as well as positional arguments. ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```console $ node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```console $ node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```console $ node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```console $ node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```console $ node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```console $ node example.js -a run b -x y { _: [ 'b' ], a: 'run', x: 'y' } ``` _If enabled:_ ```console $ node example.js -a run b -x y { _: [ 'b', '-x', 'y' ], a: 'run' } ``` ### strip aliased * default: `false` * key: `strip-aliased` Should aliases be removed before returning results? _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` ### strip dashed * default: `false` * key: `strip-dashed` Should dashed keys be removed before returning results? This option has no effect if `camel-case-expansion` is disabled. _If disabled:_ ```console $ node example.js --test-field 1 { _: [], 'test-field': 1, testField: 1 } ``` _If enabled:_ ```console $ node example.js --test-field 1 { _: [], testField: 1 } ``` ### unknown options as args * default: `false` * key: `unknown-options-as-args` Should unknown options be treated like regular arguments? An unknown option is one that is not configured in `opts`. _If disabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } ``` _If enabled_ ```console $ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 { _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } ``` ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) ====== Javascript module to match a string against a regular expression, glob, string, or function that takes the string as an argument and returns a truthy or falsy value. The matcher can also be an array of any or all of these. Useful for allowing a very flexible user-defined config to define things like file paths. __Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ Usage ----- ```sh npm install anymatch ``` #### anymatch(matchers, testString, [returnIndex], [options]) * __matchers__: (_Array|String|RegExp|Function_) String to be directly matched, string with glob patterns, regular expression test, function that takes the testString as an argument and returns a truthy value if it should be matched, or an array of any number and mix of these types. * __testString__: (_String|Array_) The string to test against the matchers. If passed as an array, the first element of the array will be used as the `testString` for non-function matchers, while the entire array will be applied as the arguments for function matchers. * __options__: (_Object_ [optional]_) Any of the [picomatch](https://github.com/micromatch/picomatch#options) options. * __returnIndex__: (_Boolean [optional]_) If true, return the array index of the first matcher that that testString matched, or -1 if no match, instead of a boolean result. ```js const anymatch = require('anymatch'); const matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo.js$/, string => string.includes('bar') && string.length > 10 ] ; anymatch(matchers, 'path/to/file.js'); // true anymatch(matchers, 'path/anyjs/baz.js'); // true anymatch(matchers, 'path/to/foo.js'); // true anymatch(matchers, 'path/to/bar.js'); // true anymatch(matchers, 'bar.js'); // false // returnIndex = true anymatch(matchers, 'foo.js', {returnIndex: true}); // 2 anymatch(matchers, 'path/anyjs/foo.js', {returnIndex: true}); // 1 // any picomatc // using globs to match directories and their children anymatch('node_modules', 'node_modules'); // true anymatch('node_modules', 'node_modules/somelib/index.js'); // false anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true const matcher = anymatch(matchers); ['foo.js', 'bar.js'].filter(matcher); // [ 'foo.js' ] anymatch master* ❯ ``` #### anymatch(matchers) You can also pass in only your matcher(s) to get a curried function that has already been bound to the provided matching criteria. This can be used as an `Array#filter` callback. ```js var matcher = anymatch(matchers); matcher('path/to/file.js'); // true matcher('path/anyjs/baz.js', true); // 1 ['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] ``` Changelog ---------- [See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) - **v3.0:** Removed `startIndex` and `endIndex` arguments. Node 8.x-only. - **v2.0:** [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). - **v1.2:** anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) for glob pattern matching. Issues with glob pattern matching should be reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). License ------- [ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml) > Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> - [Install](#install) - [Quickstart](#quickstart) - [Why use micromatch?](#why-use-micromatch) * [Matching features](#matching-features) - [Switching to micromatch](#switching-to-micromatch) * [From minimatch](#from-minimatch) * [From multimatch](#from-multimatch) - [API](#api) - [Options](#options) - [Options Examples](#options-examples) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.expandRange](#optionsexpandrange) * [options.format](#optionsformat) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.noextglob](#optionsnoextglob) * [options.nonegate](#optionsnonegate) * [options.noglobstar](#optionsnoglobstar) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.onIgnore](#optionsonignore) * [options.onMatch](#optionsonmatch) * [options.onResult](#optionsonresult) * [options.posixSlashes](#optionsposixslashes) * [options.unescape](#optionsunescape) - [Extended globbing](#extended-globbing) * [Extglobs](#extglobs) * [Braces](#braces) * [Regex character classes](#regex-character-classes) * [Regex groups](#regex-groups) * [POSIX bracket expressions](#posix-bracket-expressions) - [Notes](#notes) * [Bash 4.3 parity](#bash-43-parity) * [Backslashes](#backslashes) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Latest results](#latest-results) - [Contributing](#contributing) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=8.6): ```sh $ npm install --save micromatch ``` ## Quickstart ```js const micromatch = require('micromatch'); // micromatch(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] ``` Use [.isMatch()](#ismatch) to for boolean matching: ```js console.log(micromatch.isMatch('foo', 'f*')) //=> true console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! <br> ## Why use micromatch? > micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) * More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. * **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). * **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories * **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. * **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) * **Well tested** - More than 5,000 [test assertions](./test) * **Windows support** - More reliable windows support than minimatch and multimatch. * **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. ### Matching features * Support for multiple glob patterns (no need for wrappers like multimatch) * Wildcards (`**`, `*.js`) * Negation (`'!a/*.js'`, `'*!(b).js'`) * [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) * [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) * regex character classes (`foo-[1-5].js`) * regex logical "or" (`foo/(abc|xyz).js`) You can mix and match these features to create whatever patterns you need! ## Switching to micromatch _(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ ### From minimatch Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: ```js console.log(micromatch.isMatch('foo', 'b*')); //=> false ``` Use [micromatch.match()](#match) instead of `minimatch.match()`: ```js console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' ``` ### From multimatch Same signature: ```js console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] ``` ## API **Params** * `list` **{String|Array<string>}**: List of strings to match. * `patterns` **{String|Array<string>}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) * `returns` **{Array}**: Returns an array of matches **Example** ```js const mm = require('micromatch'); // mm(list, patterns[, options]); console.log(mm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.matcher](index.js#L104) Returns a 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. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}** * `returns` **{Function}**: Returns a matcher function. **Example** ```js const mm = require('micromatch'); // mm.matcher(pattern[, options]); const isMatch = mm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.isMatch](index.js#L123) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `[options]` **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.isMatch(string, patterns[, options]); console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(mm.isMatch('a.a', 'b.*')); //=> false ``` ### [.not](index.js#L148) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js const mm = require('micromatch'); // mm.not(list, patterns[, options]); console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L188) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. **Example** ```js var mm = require('micromatch'); // mm.contains(string, pattern[, options]); console.log(mm.contains('aa/bb/cc', '*b')); //=> true console.log(mm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L230) 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. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js const mm = require('micromatch'); // mm.matchKeys(object, patterns[, options]); const obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(mm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.some](index.js#L259) Returns true if some of the strings in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.some(list, patterns[, options]); console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L295) Returns true if every string in the given `list` matches any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.every(list, patterns[, options]); console.log(mm.every('foo.js', ['foo.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.all](index.js#L334) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.all(string, patterns[, options]); console.log(mm.all('foo.js', ['foo.js'])); // true console.log(mm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(mm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.capture](index.js#L361) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `glob` **{String}**: Glob pattern to use for matching. * `input` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. **Example** ```js const mm = require('micromatch'); // mm.capture(pattern, string[, options]); console.log(mm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(mm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L387) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const mm = require('micromatch'); // mm.makeRe(pattern[, options]); console.log(mm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.scan](index.js#L403) Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const mm = require('micromatch'); const state = mm.scan(pattern[, options]); ``` ### [.parse](index.js#L419) Parse a glob pattern to create the source string for a regular expression. **Params** * `glob` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. **Example** ```js const mm = require('micromatch'); const state = mm.parse(pattern[, options]); ``` ### [.braces](index.js#L446) Process the given brace `pattern`. **Params** * `pattern` **{String}**: String with brace pattern to process. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * `returns` **{Array}** **Example** ```js const { braces } = require('micromatch'); console.log(braces('foo/{a,b,c}/bar')); //=> [ 'foo/(a|b|c)/bar' ] console.log(braces('foo/{a,b,c}/bar', { expand: true })); //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] ``` ## Options | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | | `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | ## Options Examples ### options.basename 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`. **Type**: `Boolean` **Default**: `false` **Example** ```js micromatch(['a/b.js', 'a/c.md'], '*.js'); //=> [] micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); //=> ['a/b.js'] ``` ### options.bash 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 any other star. **Type**: `Boolean` **Default**: `true` **Example** ```js const files = ['abc', 'ajz']; console.log(micromatch(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(micromatch(files, '[a-c]*', { bash: false })); ``` ### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. ```js const fill = require('fill-range'); const regex = micromatch.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex) //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` ### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')) //=> true ``` ### options.ignore String or array of glob patterns to match files to ignore. **Type**: `String|Array` **Default**: `undefined` ```js const isMatch = micromatch.matcher('*', { ignore: 'f*' }); console.log(isMatch('foo')) //=> false console.log(isMatch('bar')) //=> true console.log(isMatch('baz')) //=> true ``` ### options.matchBase Alias for [options.basename](#options-basename). ### options.noextglob Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. **Type**: `Boolean` **Default**: `undefined` **Examples** ```js console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); //=> ['a/b', 'a/!(z)'] console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); //=> ['a/!(z)'] (matches only as literal characters) ``` ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. **Type**: `Boolean` **Default**: `undefined` ### options.noglobstar Disable matching with globstars (`**`). **Type**: `Boolean` **Default**: `undefined` ```js micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` ### options.nonull Alias for [options.nullglob](#options-nullglob). ### options.nullglob 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`. **Type**: `Boolean` **Default**: `undefined` ### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } }; const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ input, output }); // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } }; const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); isMatch('some\\path'); isMatch('some\\path'); isMatch('some\\path'); ``` ### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = micromatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.posixSlashes Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. **Type**: `Boolean` **Default**: `true` on windows, `false` everywhere else. **Example** ```js console.log(micromatch.match(['a\\b\\c'], 'a/**')); //=> ['a/b/c'] console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); //=> ['a\\b\\c'] ``` ### options.unescape Remove backslashes from escaped glob characters before creating the regular expression to perform matches. **Type**: `Boolean` **Default**: `undefined` **Example** In this example we want to match a literal `*`: ```js console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); //=> ['a\\*c'] console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); //=> ['a*c'] ``` <br> <br> ## Extended globbing Micromatch supports the following extended globbing features. ### Extglobs Extended globbing, as described by the bash man page: | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | <sup><strong>*</strong></sup> Note that `@` isn't a regex character. ### Braces Brace patterns can be used to match specific ranges or sets of characters. **Example** The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. ### Regex character classes Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). ### Regex groups Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. ### POSIX bracket expressions POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. **Example** ```js console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false ``` *** ## Notes ### Bash 4.3 parity Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. ### Backslashes There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. * Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. We made this decision for micromatch for a couple of reasons: * Consistency with bash conventions. * Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. **A note about joining paths to globs** Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. ## Benchmarks ### Running benchmarks Install dependencies for running benchmarks: ```sh $ cd bench && npm install ``` Run the benchmarks: ```sh $ npm run bench ``` ### Latest results As of March 24, 2022 (longer bars are better): ```sh # .makeRe star micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) # .makeRe star; dot=true micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) # .makeRe globstar micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) # .makeRe globstars micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) # .makeRe with leading star micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) # .makeRe - braces micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) # .makeRe braces - range (expanded) micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) # .makeRe braces - range (compiled) micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) # .makeRe braces - nested ranges (expanded) micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) # .makeRe braces - nested ranges (compiled) micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) # .makeRe braces - set (compiled) micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) # .makeRe braces - nested sets (compiled) micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) ``` ## Contributing All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. **Bug reports** Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: * [research existing issues first](../../issues) (open and closed) * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js * if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. **Platform issues** It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 512 | [jonschlinkert](https://github.com/jonschlinkert) | | 12 | [es128](https://github.com/es128) | | 9 | [danez](https://github.com/danez) | | 8 | [doowb](https://github.com/doowb) | | 6 | [paulmillr](https://github.com/paulmillr) | | 5 | [mrmlnc](https://github.com/mrmlnc) | | 3 | [DrPizza](https://github.com/DrPizza) | | 2 | [TrySound](https://github.com/TrySound) | | 2 | [mceIdo](https://github.com/mceIdo) | | 2 | [Glazy](https://github.com/Glazy) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [antonyk](https://github.com/antonyk) | | 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | | 1 | [amilajack](https://github.com/amilajack) | | 1 | [Cslove](https://github.com/Cslove) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [DianeLooney](https://github.com/DianeLooney) | | 1 | [UltCombo](https://github.com/UltCombo) | | 1 | [frangio](https://github.com/frangio) | | 1 | [joyceerhl](https://github.com/joyceerhl) | | 1 | [juszczykjakub](https://github.com/juszczykjakub) | | 1 | [muescha](https://github.com/muescha) | | 1 | [sebdeckers](https://github.com/sebdeckers) | | 1 | [tomByrer](https://github.com/tomByrer) | | 1 | [fidian](https://github.com/fidian) | | 1 | [curbengh](https://github.com/curbengh) | | 1 | [simlu](https://github.com/simlu) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | | 1 | [yvele](https://github.com/yvele) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2022, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 24, 2022._ semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # create-hash [![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash) Node style hashes for use in the browser, with native hash functions in node. API is the same as hashes in node: ```js var createHash = require('create-hash') var hash = createHash('sha224') hash.update('synchronous write') // optional encoding parameter hash.digest() // synchronously get result with optional encoding parameter hash.write('write to it as a stream') hash.end() // remember it's a stream hash.read() // only if you ended it as a stream though ``` To get the JavaScript version even in node do `require('create-hash/browser')` # sprintf.js **sprintf.js** is a complete open source JavaScript sprintf implementation for the *browser* and *node.js*. Its prototype is simple: string sprintf(string format , [mixed arg1 [, mixed arg2 [ ,...]]]) The placeholders in the format string are marked by `%` and are followed by one or more of these elements, in this order: * An optional number followed by a `$` sign that selects which argument index to use for the value. If not specified, arguments will be placed in the same order as the placeholders in the input string. * An optional `+` sign that forces to preceed the result with a plus or minus sign on numeric values. By default, only the `-` sign is used on negative numbers. * An optional padding specifier that says what character to use for padding (if specified). Possible values are `0` or any other character precedeed by a `'` (single quote). The default is to pad with *spaces*. * An optional `-` sign, that causes sprintf to left-align the result of this placeholder. The default is to right-align the result. * An optional number, that says how many characters the result should have. If the value to be returned is shorter than this number, the result will be padded. When used with the `j` (JSON) type specifier, the padding length specifies the tab size used for indentation. * An optional precision modifier, consisting of a `.` (dot) followed by a number, that says how many digits should be displayed for floating point numbers. When used with the `g` type specifier, it specifies the number of significant digits. When used on a string, it causes the result to be truncated. * A type specifier that can be any of: * `%` — yields a literal `%` character * `b` — yields an integer as a binary number * `c` — yields an integer as the character with that ASCII value * `d` or `i` — yields an integer as a signed decimal number * `e` — yields a float using scientific notation * `u` — yields an integer as an unsigned decimal number * `f` — yields a float as is; see notes on precision above * `g` — yields a float as is; see notes on precision above * `o` — yields an integer as an octal number * `s` — yields a string as is * `x` — yields an integer as a hexadecimal number (lower-case) * `X` — yields an integer as a hexadecimal number (upper-case) * `j` — yields a JavaScript object or array as a JSON encoded string ## JavaScript `vsprintf` `vsprintf` is the same as `sprintf` except that it accepts an array of arguments, rather than a variable number of arguments: vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) ## Argument swapping You can also swap the arguments. That is, the order of the placeholders doesn't have to match the order of the arguments. You can do that by simply indicating in the format string which arguments the placeholders refer to: sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") And, of course, you can repeat the placeholders without having to increase the number of arguments. ## Named arguments Format strings may contain replacement fields rather than positional placeholders. Instead of referring to a certain argument, you can now refer to a certain key within an object. Replacement fields are surrounded by rounded parentheses - `(` and `)` - and begin with a keyword that refers to a key: var user = { name: "Dolly" } sprintf("Hello %(name)s", user) // Hello Dolly Keywords in replacement fields can be optionally followed by any number of keywords or indexes: var users = [ {name: "Dolly"}, {name: "Molly"}, {name: "Polly"} ] sprintf("Hello %(users[0].name)s, %(users[1].name)s and %(users[2].name)s", {users: users}) // Hello Dolly, Molly and Polly Note: mixing positional and named placeholders is not (yet) supported ## Computed values You can pass in a function as a dynamic value and it will be invoked (with no arguments) in order to compute the value on-the-fly. sprintf("Current timestamp: %d", Date.now) // Current timestamp: 1398005382890 sprintf("Current date and time: %s", function() { return new Date().toString() }) # AngularJS You can now use `sprintf` and `vsprintf` (also aliased as `fmt` and `vfmt` respectively) in your AngularJS projects. See `demo/`. # Installation ## Via Bower bower install sprintf ## Or as a node.js module npm install sprintf-js ### Usage var sprintf = require("sprintf-js").sprintf, vsprintf = require("sprintf-js").vsprintf sprintf("%2$s %3$s a %1$s", "cracker", "Polly", "wants") vsprintf("The first 4 letters of the english alphabet are: %s, %s, %s and %s", ["a", "b", "c", "d"]) # License **sprintf.js** is licensed under the terms of the 3-clause BSD license. # well-known-symbols Check whether a symbol is [well-known](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Well-known_symbols). Requires Node.js 6 or above. Note that not all Node.js versions support the same well-known symbols. ## Installation ```console $ npm install --save well-known-symbols ``` ## Usage ```js const wellKnownSymbols = require('well-known-symbols') wellKnownSymbols.isWellKnown(Symbol.iterator) // true wellKnownSymbols.isWellKnown(Symbol()) // false wellKnownSymbols.getLabel(Symbol.iterator) // 'Symbol.iterator' wellKnownSymbols.getLabel(Symbol()) // undefined ``` # ci-info Get details about the current Continuous Integration environment. Please [open an issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info) [![Tests](https://github.com/watson/ci-info/workflows/Tests/badge.svg)](https://github.com/watson/ci-info/actions) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install ci-info --save ``` ## Usage ```js var ci = require('ci-info') if (ci.isCI) { console.log('The name of the CI server is:', ci.name) } else { console.log('This program is not running on a CI server') } ``` ## Supported CI tools Officially supported CI servers: | Name | Constant | isPR | | ------------------------------------------------------------------------------- | -------------------- | ---- | | [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 | | [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ | | [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ | | [Appcircle](https://appcircle.io/) | `ci.APPCIRCLE` | 🚫 | | [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 | | [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ | | [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ | | [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ | | [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ | | [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ | | [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ | | [Codefresh](https://codefresh.io/) | `ci.CODEFRESH` | ✅ | | [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 | | [Drone](https://drone.io) | `ci.DRONE` | ✅ | | [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 | | [Expo Application Services](https://expo.dev/eas) | `ci.EAS` | 🚫 | | [Gerrit CI](https://www.gerritcodereview.com) | `ci.GERRIT` | 🚫 | | [GitHub Actions](https://github.com/features/actions/) | `ci.GITHUB_ACTIONS` | ✅ | | [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | ✅ | | [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 | | [Google Cloud Build](https://cloud.google.com/build) | `ci.GOOGLE_CLOUD_BUILD` | 🚫 | | [Heroku](https://www.heroku.com) | `ci.HEROKU` | 🚫 | | [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 | | [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ | | [LayerCI](https://layerci.com/) | `ci.LAYERCI` | ✅ | | [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 | | [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ | | [Nevercode](http://nevercode.io/) | `ci.NEVERCODE` | ✅ | | [ReleaseHub](https://releasehub.com/) | `ci.RELEASEHUB` | ✅ | | [Render](https://render.com/) | `ci.RENDER` | ✅ | | [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ | | [Screwdriver](https://screwdriver.cd/) | `ci.SCREWDRIVER` | ✅ | | [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ | | [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ | | [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ | | [Sourcehut](https://sourcehut.org/) | `ci.SOURCEHUT` | 🚫 | | [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 | | [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 | | [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 | | [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ | | [Vercel](https://vercel.com/) | `ci.VERCEL` | 🚫 | | [Visual Studio App Center](https://appcenter.ms/) | `ci.APPCENTER` | 🚫 | | [Woodpecker](https://woodpecker-ci.org/) | `ci.WOODPECKER` | ✅ | ## API ### `ci.name` Returns a string containing name of the CI server the code is running on. If CI server is not detected, it returns `null`. Don't depend on the value of this string not to change for a specific vendor. If you find your self writing `ci.name === 'Travis CI'`, you most likely want to use `ci.TRAVIS` instead. ### `ci.isCI` Returns a boolean. Will be `true` if the code is running on a CI server, otherwise `false`. Some CI servers not listed here might still trigger the `ci.isCI` boolean to be set to `true` if they use certain vendor neutral environment variables. In those cases `ci.name` will be `null` and no vendor specific boolean will be set to `true`. ### `ci.isPR` Returns a boolean if PR detection is supported for the current CI server. Will be `true` if a PR is being tested, otherwise `false`. If PR detection is not supported for the current CI server, the value will be `null`. ### `ci.<VENDOR-CONSTANT>` A vendor specific boolean constant is exposed for each support CI vendor. A constant will be `true` if the code is determined to run on the given CI server, otherwise `false`. Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a complete list, see the support table above. Deprecated vendor constants that will be removed in the next major release: - `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO` ## Ports ci-info has been ported to the following languages | Language | Repository | |----------|------------| | Go | https://github.com/hofstadter-io/cinful | | Rust | https://github.com/sagiegurari/ci_info | | Kotlin | https://github.com/cloudflightio/ci-info | ## License [MIT](LICENSE) # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # pump pump is a small node module that pipes streams together and destroys all of them if one of them closes. ``` npm install pump ``` [![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) ## What problem does it solve? When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. You are also not able to provide a callback to tell when then pipe has finished. pump does these two things for you ## Usage Simply pass the streams you want to pipe together to pump and add an optional callback ``` js var pump = require('pump') var fs = require('fs') var source = fs.createReadStream('/dev/random') var dest = fs.createWriteStream('/dev/null') pump(source, dest, function(err) { console.log('pipe finished', err) }) setTimeout(function() { dest.destroy() // when dest is closed pump will destroy source }, 1000) ``` You can use pump to pipe more than two streams together as well ``` js var transform = someTransformStream() pump(source, transform, anotherTransform, dest, function(err) { console.log('pipe finished', err) }) ``` If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: ``` return pump(s1, s2) // returns s2 ``` If you want to return a stream that combines *both* s1 and s2 to a single stream use [pumpify](https://github.com/mafintosh/pumpify) instead. ## License MIT ## Related `pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # Borsh JS [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![Travis status](https://travis-ci.com/near/borsh.svg?branch=master)](https://travis-ci.com/near/borsh-js) [![NPM version](https://img.shields.io/npm/v/borsh.svg?style=flat-square)](https://npmjs.com/borsh) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/borsh.svg?style=flat-square)](https://npmjs.com/borsh) **Borsh JS** is an implementation of the [Borsh] binary serialization format for JavaScript and TypeScript projects. Borsh stands for _Binary Object Representation Serializer for Hashing_. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification. ## Examples ### Serializing an object ```javascript const value = new Test({ x: 255, y: 20, z: '123', q: [1, 2, 3] }); const schema = new Map([[Test, { kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]); const buffer = borsh.serialize(schema, value); ``` ### Deserializing an object ```javascript const newValue = borsh.deserialize(schema, Test, buffer); ``` ## Type Mappings | Borsh | TypeScript | |-----------------------|----------------| | `u8` integer | `number` | | `u16` integer | `number` | | `u32` integer | `number` | | `u64` integer | `BN` | | `u128` integer | `BN` | | `u256` integer | `BN` | | `u512` integer | `BN` | | `f32` float | N/A | | `f64` float | N/A | | fixed-size byte array | `Uint8Array` | | UTF-8 string | `string` | | option | `null` or type | | map | N/A | | set | N/A | | structs | `any` | ## Contributing Install dependencies: ```bash yarn install ``` Continuously build with: ```bash yarn dev ``` Run tests: ```bash yarn test ``` Run linter ```bash yarn lint ``` ## Publish Prepare `dist` version by running: ```bash yarn build ``` When publishing to npm use [np](https://github.com/sindresorhus/np). # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT.txt) and [LICENSE-APACHE](LICENSE-APACHE) for details. [Borsh]: https://borsh.io write-file-atomic ----------------- This is an extension for node's `fs.writeFile` that makes its operation atomic and allows you set ownership (uid/gid of the file). ### `writeFileAtomic(filename, data, [options], [callback])` #### Description: Atomically and asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. #### Options: * filename **String** * data **String** | **Buffer** * options **Object** | **String** * chown **Object** default, uid & gid of existing file, if any * uid **Number** * gid **Number** * encoding **String** | **Null** default = 'utf8' * fsync **Boolean** default = true * mode **Number** default, from existing file, if any * tmpfileCreated **Function** called when the tmpfile is created * callback **Function** #### Usage: ```js var writeFileAtomic = require('write-file-atomic') writeFileAtomic(filename, data, [options], [callback]) ``` The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`. Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread. If writeFile completes successfully then, if passed the **chown** option it will change the ownership of the file. Finally it renames the file back to the filename you specified. If it encounters errors at any of these steps it will attempt to unlink the temporary file and then pass the error back to the caller. If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel. If provided, the **chown** option requires both **uid** and **gid** properties or else you'll get an error. If **chown** is not specified it will default to using the owner of the previous file. To prevent chown from being ran you can also pass `false`, in which case the file will be created with the current user's credentials. If **mode** is not specified, it will default to using the permissions from an existing file, if any. Expicitly setting this to `false` remove this default, resulting in a file created with the system default permissions. If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'. If the **fsync** option is **false**, writeFile will skip the final fsync call. If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created. Example: ```javascript writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) { if (err) throw err; console.log('It\'s saved!'); }); ``` This function also supports async/await: ```javascript (async () => { try { await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}); console.log('It\'s saved!'); } catch (err) { console.error(err); process.exit(1); } })(); ``` ### `writeFileAtomicSync(filename, data, [options])` #### Description: The synchronous version of **writeFileAtomic**. #### Usage: ```js var writeFileAtomicSync = require('write-file-atomic').sync writeFileAtomicSync(filename, data, [options]) ``` # create-hmac [![NPM Package](https://img.shields.io/npm/v/create-hmac.svg?style=flat-square)](https://www.npmjs.org/package/create-hmac) [![Build Status](https://img.shields.io/travis/crypto-browserify/createHmac.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/createHmac) [![Dependency status](https://img.shields.io/david/crypto-browserify/createHmac.svg?style=flat-square)](https://david-dm.org/crypto-browserify/createHmac#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style HMACs for use in the browser, with native HMAC functions in node. API is the same as HMACs in node: ```js var createHmac = require('create-hmac') var hmac = createHmac('sha224', Buffer.from('secret key')) hmac.update('synchronous write') //optional encoding parameter hmac.digest() // synchronously get result with optional encoding parameter hmac.write('write to it as a stream') hmac.end() //remember it's a stream hmac.read() //only if you ended it as a stream though ``` # js-sha256 [![Build Status](https://travis-ci.org/emn178/js-sha256.svg?branch=master)](https://travis-ci.org/emn178/js-sha256) [![Coverage Status](https://coveralls.io/repos/emn178/js-sha256/badge.svg?branch=master)](https://coveralls.io/r/emn178/js-sha256?branch=master) [![CDNJS](https://img.shields.io/cdnjs/v/js-sha256.svg)](https://cdnjs.com/libraries/js-sha256/) [![NPM](https://nodei.co/npm/js-sha256.png?stars&downloads)](https://nodei.co/npm/js-sha256/) A simple SHA-256 / SHA-224 hash function for JavaScript supports UTF-8 encoding. ## Demo [SHA256 Online](http://emn178.github.io/online-tools/sha256.html) [SHA224 Online](http://emn178.github.io/online-tools/sha224.html) ## Download [Compress](https://raw.github.com/emn178/js-sha256/master/build/sha256.min.js) [Uncompress](https://raw.github.com/emn178/js-sha256/master/src/sha256.js) ## Installation You can also install js-sha256 by using Bower. bower install js-sha256 For node.js, you can use this command to install: npm install js-sha256 ## Usage You could use like this: ```JavaScript sha256('Message to hash'); sha224('Message to hash'); var hash = sha256.create(); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.update('Message to hash'); hash2.update('Message2 to hash'); hash2.array(); // HMAC sha256.hmac('key', 'Message to hash'); sha224.hmac('key', 'Message to hash'); var hash = sha256.hmac.create('key'); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.hmac.update('key', 'Message to hash'); hash2.update('Message2 to hash'); hash2.array(); ``` If you use node.js, you should require the module first: ```JavaScript var sha256 = require('js-sha256'); ``` or ```JavaScript var sha256 = require('js-sha256').sha256; var sha224 = require('js-sha256').sha224; ``` It supports AMD: ```JavaScript require(['your/path/sha256.js'], function(sha256) { // ... }); ``` or TypeScript ```TypeScript import { sha256, sha224 } from 'js-sha256'; ``` ## Example ```JavaScript sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256('The quick brown fox jumps over the lazy dog'); // d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 sha256('The quick brown fox jumps over the lazy dog.'); // ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c sha224(''); // d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f sha224('The quick brown fox jumps over the lazy dog'); // 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 sha224('The quick brown fox jumps over the lazy dog.'); // 619cba8e8e05826e9b8c519c0a5c68f4fb653e8a3d8aa04bb2c8cd4c // It also supports UTF-8 encoding sha256('中文'); // 72726d8818f693066ceb69afa364218b692e62ea92b385782363780f47529c21 sha224('中文'); // dfbab71afdf54388af4d55f8bd3de8c9b15e0eb916bf9125f4a959d4 // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input sha256([]); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256(new Uint8Array([211, 212])); // 182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f // Different output sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.hex(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.array(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.digest(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.arrayBuffer(''); // ArrayBuffer ``` ## License The project is released under the [MIT license](http://www.opensource.org/licenses/MIT). ## Contact The project's website is located at https://github.com/emn178/js-sha256 Author: Chen, Yi-Cyuan ([email protected]) # clone-response > Clone a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/clone-response.svg?branch=master)](https://travis-ci.org/lukechilds/clone-response) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/clone-response/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/clone-response?branch=master) [![npm](https://img.shields.io/npm/dm/clone-response.svg)](https://www.npmjs.com/package/clone-response) [![npm](https://img.shields.io/npm/v/clone-response.svg)](https://www.npmjs.com/package/clone-response) Returns a new stream and copies over all properties and methods from the original response giving you a complete duplicate. This is useful in situations where you need to consume the response stream but also want to pass an unconsumed stream somewhere else to be consumed later. ## Install ```shell npm install --save clone-response ``` ## Usage ```js const http = require('http'); const cloneResponse = require('clone-response'); http.get('http://example.com', response => { const clonedResponse = cloneResponse(response); response.pipe(process.stdout); setImmediate(() => { // The response stream has already been consumed by the time this executes, // however the cloned response stream is still available. doSomethingWithResponse(clonedResponse); }); }); ``` Please bear in mind that the process of cloning a stream consumes it. However, you can consume a stream multiple times in the same tick, therefore allowing you to create multiple clones. e.g: ```js const clone1 = cloneResponse(response); const clone2 = cloneResponse(response); // response can still be consumed in this tick but cannot be consumed if passed // into any async callbacks. clone1 and clone2 can be passed around and be // consumed in the future. ``` ## API ### cloneResponse(response) Returns a clone of the passed in response. #### response Type: `stream` A [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) to clone. ## License MIT © Luke Childs # JavaScript MD5 ## Contents - [Demo](https://blueimp.github.io/JavaScript-MD5/) - [Description](#description) - [Usage](#usage) - [Client-side](#client-side) - [Server-side](#server-side) - [Requirements](#requirements) - [API](#api) - [Tests](#tests) - [License](#license) ## Description JavaScript [MD5](https://en.wikipedia.org/wiki/MD5) implementation. Compatible with server-side environments like [Node.js](https://nodejs.org/), module loaders like [RequireJS](https://requirejs.org/) or [webpack](https://webpack.js.org/) and all web browsers. ## Usage ### Client-side Install the **blueimp-md5** package with [NPM](https://www.npmjs.org/): ```sh npm install blueimp-md5 ``` Include the (minified) JavaScript [MD5](https://en.wikipedia.org/wiki/MD5) script in your HTML markup: ```html <script src="js/md5.min.js"></script> ``` In your application code, calculate the ([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded) [MD5](https://en.wikipedia.org/wiki/MD5) hash of a string by calling the **md5** method with the string as argument: ```js var hash = md5('value') // "2063c1608d6e0baf80249c42e2be5804" ``` ### Server-side The following is an example how to use the JavaScript MD5 module on the server-side with [Node.js](https://nodejs.org/). Install the **blueimp-md5** package with [NPM](https://www.npmjs.org/): ```sh npm install blueimp-md5 ``` Add a file **server.js** with the following content: ```js require('http') .createServer(function (req, res) { // The md5 module exports the md5() function: var md5 = require('./md5'), // Use the following version if you installed the package with npm: // var md5 = require("blueimp-md5"), url = require('url'), query = url.parse(req.url).query res.writeHead(200, { 'Content-Type': 'text/plain' }) // Calculate and print the MD5 hash of the url query: res.end(md5(query)) }) .listen(8080, 'localhost') console.log('Server running at http://localhost:8080/') ``` Run the application with the following command: ```sh node server.js ``` ## Requirements The JavaScript MD5 script has zero dependencies. ## API Calculate the ([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded) [MD5](https://en.wikipedia.org/wiki/MD5) hash of a given string value: ```js var hash = md5('value') // "2063c1608d6e0baf80249c42e2be5804" ``` Calculate the ([hex](https://en.wikipedia.org/wiki/Hexadecimal)-encoded) [HMAC](https://en.wikipedia.org/wiki/HMAC)-MD5 hash of a given string value and key: ```js var hash = md5('value', 'key') // "01433efd5f16327ea4b31144572c67f6" ``` Calculate the raw [MD5](https://en.wikipedia.org/wiki/MD5) hash of a given string value: ```js var hash = md5('value', null, true) ``` Calculate the raw [HMAC](https://en.wikipedia.org/wiki/HMAC)-MD5 hash of a given string value and key: ```js var hash = md5('value', 'key', true) ``` ## Tests The JavaScript MD5 project comes with [Unit Tests](https://en.wikipedia.org/wiki/Unit_testing). There are two different ways to run the tests: - Open test/index.html in your browser or - run `npm test` in the Terminal in the root path of the repository package. The first one tests the browser integration, the second one the [Node.js](https://nodejs.org/) integration. ## License The JavaScript MD5 script is released under the [MIT license](https://opensource.org/licenses/MIT). # mime-types [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] The ultimate javascript content-type utility. Similar to [the `[email protected]` module](https://www.npmjs.com/package/mime), except: - __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. - No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. - No `.define()` functionality - Bug fixes for `.lookup(path)` Otherwise, the API is compatible with `mime` 1.x. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install mime-types ``` ## Adding Types All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), so open a PR there if you'd like to add mime types. ## API ```js var mime = require('mime-types') ``` All functions return `false` if input is invalid or not found. ### mime.lookup(path) Lookup the content-type associated with a file. ```js mime.lookup('json') // 'application/json' mime.lookup('.md') // 'text/markdown' mime.lookup('file.html') // 'text/html' mime.lookup('folder/file.js') // 'application/javascript' mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` ### mime.contentType(type) Create a full content-type header given a content-type or extension. When given an extension, `mime.lookup` is used to get the matching content-type, otherwise the given content-type is used. Then if the content-type does not already have a `charset` parameter, `mime.charset` is used to get the default charset and add to the returned content-type. ```js mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' mime.contentType('file.json') // 'application/json; charset=utf-8' mime.contentType('text/html') // 'text/html; charset=utf-8' mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' // from a full path mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' ``` ### mime.extension(type) Get the default extension for a content-type. ```js mime.extension('application/octet-stream') // 'bin' ``` ### mime.charset(type) Lookup the implied default charset of a content-type. ```js mime.charset('text/markdown') // 'UTF-8' ``` ### var type = mime.types[extension] A map of content-types by extension. ### [extensions...] = mime.extensions[type] A map of extensions by content-type. ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci [ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master [node-version-image]: https://badgen.net/npm/node/mime-types [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-types [npm-url]: https://npmjs.org/package/mime-types [npm-version-image]: https://badgen.net/npm/v/mime-types # u3 - Utility Functions This lib contains utility functions for e3, dataflower and other projects. ## Documentation ### Installation ```bash npm install u3 ``` ```bash bower install u3 ``` #### Usage In this documentation I used the lib as follows: ```js var u3 = require("u3"), cache = u3.cache, eachCombination = u3.eachCombination; ``` ### Function wrappers #### cache The `cache(fn)` function caches the fn results, so by the next calls it will return the result of the first call. You can use different arguments, but they won't affect the return value. ```js var a = cache(function fn(x, y, z){ return x + y + z; }); console.log(a(1, 2, 3)); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` It is possible to cache a value too. ```js var a = cache(1 + 2 + 3); console.log(a()); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` ### Math #### eachCombination The `eachCombination(alternativesByDimension, callback)` calls the `callback(a,b,c,...)` on each combination of the `alternatives[a[],b[],c[],...]`. ```js eachCombination([ [1, 2, 3], ["a", "b"] ], console.log); /* 1, "a" 1, "b" 2, "a" 2, "b" 3, "a" 3, "b" */ ``` You can use any dimension and number of alternatives. In the current example we used 2 dimensions. By the first dimension we used 3 alternatives: `[1, 2, 3]` and by the second dimension we used 2 alternatives: `["a", "b"]`. ## License MIT - 2016 Jánszky László Lajos # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # readable-stream ***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) ```bash npm install --save readable-stream ``` This package is a mirror of the streams implementations in Node.js. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. ## Version 3.x.x v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: 1. Error codes: https://github.com/nodejs/node/pull/13310, https://github.com/nodejs/node/pull/13291, https://github.com/nodejs/node/pull/16589, https://github.com/nodejs/node/pull/15042, https://github.com/nodejs/node/pull/15665, https://github.com/nodejs/readable-stream/pull/344 2. 'readable' have precedence over flowing https://github.com/nodejs/node/pull/18994 3. make virtual methods errors consistent https://github.com/nodejs/node/pull/18813 4. updated streams error handling https://github.com/nodejs/node/pull/18438 5. writable.end should return this. https://github.com/nodejs/node/pull/18780 6. readable continues to read when push('') https://github.com/nodejs/node/pull/18211 7. add custom inspect to BufferList https://github.com/nodejs/node/pull/17907 8. always defer 'readable' with nextTick https://github.com/nodejs/node/pull/17979 ## Version 2.x.x v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. ### Big Thanks Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] # Usage You can swap your `require('stream')` with `require('readable-stream')` without any changes, if you are just using one of the main classes and functions. ```js const { Readable, Writable, Transform, Duplex, pipeline, finished } = require('readable-stream') ```` Note that `require('stream')` will return `Stream`, while `require('readable-stream')` will return `Readable`. We discourage using whatever is exported directly, but rather use one of the properties as shown in the example above. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;[email protected]&gt; [sauce]: https://saucelabs.com <h1 align="center"> <img width="250" src="https://rawgit.com/lukechilds/keyv/master/media/logo.svg" alt="keyv"> <br> <br> </h1> > Simple key-value storage with support for multiple backends [![Build Status](https://travis-ci.org/lukechilds/keyv.svg?branch=master)](https://travis-ci.org/lukechilds/keyv) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv?branch=master) [![npm](https://img.shields.io/npm/dm/keyv.svg)](https://www.npmjs.com/package/keyv) [![npm](https://img.shields.io/npm/v/keyv.svg)](https://www.npmjs.com/package/keyv) Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store. ## Features There are a few existing modules similar to Keyv, however Keyv is different because it: - Isn't bloated - Has a simple Promise based API - Suitable as a TTL based cache or persistent key-value store - [Easily embeddable](#add-cache-support-to-your-module) inside another module - Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API - Handles all JSON types plus `Buffer` - Supports namespaces - Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters - Connection errors are passed through (db failures won't kill your app) - Supports the current active LTS version of Node.js or higher ## Usage Install Keyv. ``` npm install --save keyv ``` By default everything is stored in memory, you can optionally also install a storage adapter. ``` npm install --save @keyv/redis npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql ``` Create a new Keyv instance, passing your connection string if applicable. Keyv will automatically load the correct storage adapter. ```js const Keyv = require('keyv'); // One of the following const keyv = new Keyv(); const keyv = new Keyv('redis://user:pass@localhost:6379'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); const keyv = new Keyv('sqlite://path/to/database.sqlite'); const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); await keyv.set('foo', 'expires in 1 second', 1000); // true await keyv.set('foo', 'never expires'); // true await keyv.get('foo'); // 'never expires' await keyv.delete('foo'); // true await keyv.clear(); // undefined ``` ### Namespaces You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database. ```js const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' }); const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' }); await users.set('foo', 'users'); // true await cache.set('foo', 'cache'); // true await users.get('foo'); // 'users' await cache.get('foo'); // 'cache' await users.clear(); // undefined await users.get('foo'); // undefined await cache.get('foo'); // 'cache' ``` ### Custom Serializers Keyv uses [`json-buffer`](https://github.com/dominictarr/json-buffer) for data serialization to ensure consistency across different backends. You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON. ```js const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); ``` **Warning:** Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine. ## Official Storage Adapters The official storage adapters are covered by [over 150 integration tests](https://travis-ci.org/lukechilds/keyv/jobs/260418145) to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available. Database | Adapter | Native TTL | Status ---|---|---|--- Redis | [@keyv/redis](https://github.com/lukechilds/keyv-redis) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-redis.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-redis) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-redis/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-redis?branch=master) MongoDB | [@keyv/mongo](https://github.com/lukechilds/keyv-mongo) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-mongo.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mongo) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-mongo/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-mongo?branch=master) SQLite | [@keyv/sqlite](https://github.com/lukechilds/keyv-sqlite) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-sqlite.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-sqlite) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-sqlite/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-sqlite?branch=master) PostgreSQL | [@keyv/postgres](https://github.com/lukechilds/keyv-postgres) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-postgres.svg?branch=master)](https://travis-ci.org/lukechildskeyv-postgreskeyv) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-postgres/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-postgres?branch=master) MySQL | [@keyv/mysql](https://github.com/lukechilds/keyv-mysql) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-mysql.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mysql) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-mysql/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-mysql?branch=master) ## Third-party Storage Adapters You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally. ```js const Keyv = require('keyv'); const myAdapter = require('./my-storage-adapter'); const keyv = new Keyv({ store: myAdapter }); ``` Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work. ```js new Keyv({ store: new Map() }); ``` For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API. ```js const Keyv = require('keyv'); const QuickLRU = require('quick-lru'); const lru = new QuickLRU({ maxSize: 1000 }); const keyv = new Keyv({ store: lru }); ``` The following are third-party storage adapters compatible with Keyv: - [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple "Least Recently Used" (LRU) cache - [keyv-file](https://github.com/zaaack/keyv-file) - File system storage adapter for Keyv - [keyv-dynamodb](https://www.npmjs.com/package/keyv-dynamodb) - DynamoDB storage adapter for Keyv ## Add Cache Support to your Module Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a `cache` option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string, or any other storage that implements the `Map` API. You should also set a namespace for your module so you can safely call `.clear()` without clearing unrelated app data. Inside your module: ```js class AwesomeModule { constructor(opts) { this.cache = new Keyv({ uri: typeof opts.cache === 'string' && opts.cache, store: typeof opts.cache !== 'string' && opts.cache, namespace: 'awesome-module' }); } } ``` Now it can be consumed like this: ```js const AwesomeModule = require('awesome-module'); // Caches stuff in memory by default const awesomeModule = new AwesomeModule(); // After npm install --save keyv-redis const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' }); // Some third-party module that implements the Map API const awesomeModule = new AwesomeModule({ cache: some3rdPartyStore }); ``` ## API ### new Keyv([uri], [options]) Returns a new Keyv instance. The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails. ### uri Type: `String`<br> Default: `undefined` The connection string URI. Merged into the options object as options.uri. ### options Type: `Object` The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. #### options.namespace Type: `String`<br> Default: `'keyv'` Namespace for the current instance. #### options.ttl Type: `Number`<br> Default: `undefined` Default TTL. Can be overridden by specififying a TTL on `.set()`. #### options.serialize Type: `Function`<br> Default: `JSONB.stringify` A custom serialization function. #### options.deserialize Type: `Function`<br> Default: `JSONB.parse` A custom deserialization function. #### options.store Type: `Storage adapter instance`<br> Default: `new Map()` The storage adapter instance to be used by Keyv. #### options.adapter Type: `String`<br> Default: `undefined` Specify an adapter to use. e.g `'redis'` or `'mongodb'`. ### Instance Keys must always be strings. Values can be of any type. #### .set(key, value, [ttl]) Set a value. By default keys are persistent. You can set an expiry TTL in milliseconds. Returns `true`. #### .get(key) Returns the value. #### .delete(key) Deletes an entry. Returns `true` if the key existed, `false` if not. #### .clear() Delete all entries in the current namespace. Returns `undefined`. ## License MIT © Luke Childs # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) > Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fill-range ``` ## Usage Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. ```js const fill = require('fill-range'); // fill(from, to[, step, options]); console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 ``` **Params** * `from`: **{String|Number}** the number or letter to start with * `to`: **{String|Number}** the number or letter to end with * `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. * `options`: **{Object|Function}**: See all available [options](#options) ## Examples By default, an array of values is returned. **Alphabetical ranges** ```js console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] ``` **Numerical ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] ``` **Negative ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] ``` **Steps (increments)** ```js // numerical ranges with increments console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] // alphabetical ranges with increments console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] ``` ## Options ### options.step **Type**: `number` (formatted as a string or number) **Default**: `undefined` **Description**: The increment to use for the range. Can be used with letters or numbers. **Example(s)** ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` ### options.strictRanges **Type**: `boolean` **Default**: `false` **Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. **Example(s)** The following are all invalid: ```js fill('1.1', '2'); // decimals not supported in ranges fill('a', '2'); // incompatible range values fill(1, 10, 'foo'); // invalid "step" argument ``` ### options.stringify **Type**: `boolean` **Default**: `undefined` **Description**: Cast all returned values to strings. By default, integers are returned as numbers. **Example(s)** ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] ``` ### options.toRegex **Type**: `boolean` **Default**: `undefined` **Description**: Create a regex-compatible source string, instead of expanding values to an array. **Example(s)** ```js // alphabetical range console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' // alphabetical with step console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' // numerical range console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' // numerical range with zero padding console.log(fill('000001', '100000', { toRegex: true })); //=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' ``` ### options.transform **Type**: `function` **Default**: `undefined` **Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. **Example(s)** ```js // add zero padding console.log(fill(1, 5, value => String(value).padStart(4, '0'))); //=> ['0001', '0002', '0003', '0004', '0005'] ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 116 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [paulmillr](https://github.com/paulmillr) | | 2 | [realityking](https://github.com/realityking) | | 2 | [bluelovers](https://github.com/bluelovers) | | 1 | [edorivai](https://github.com/edorivai) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ # WebIDL Type Conversions on JavaScript Values This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). The goal is that you should be able to write code like ```js const conversions = require("webidl-conversions"); function doStuff(x, y) { x = conversions["boolean"](x); y = conversions["unsigned long"](y); // actual algorithm code here } ``` and your function `doStuff` will behave the same as a WebIDL operation declared as ```webidl void doStuff(boolean x, unsigned long y); ``` ## API This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). ## Status All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. ## Background What's actually going on here, conceptually, is pretty weird. Let's try to explain. WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. ## Don't Use This Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. # tar-fs filesystem bindings for [tar-stream](https://github.com/mafintosh/tar-stream). ``` npm install tar-fs ``` [![build status](https://secure.travis-ci.org/mafintosh/tar-fs.png)](http://travis-ci.org/mafintosh/tar-fs) ## Usage tar-fs allows you to pack directories into tarballs and extract tarballs into directories. It doesn't gunzip for you, so if you want to extract a `.tar.gz` with this you'll need to use something like [gunzip-maybe](https://github.com/mafintosh/gunzip-maybe) in addition to this. ``` js var tar = require('tar-fs') var fs = require('fs') // packing a directory tar.pack('./my-directory').pipe(fs.createWriteStream('my-tarball.tar')) // extracting a directory fs.createReadStream('my-other-tarball.tar').pipe(tar.extract('./my-other-directory')) ``` To ignore various files when packing or extracting add a ignore function to the options. `ignore` is also an alias for `filter`. Additionally you get `header` if you use ignore while extracting. That way you could also filter by metadata. ``` js var pack = tar.pack('./my-directory', { ignore: function(name) { return path.extname(name) === '.bin' // ignore .bin files when packing } }) var extract = tar.extract('./my-other-directory', { ignore: function(name) { return path.extname(name) === '.bin' // ignore .bin files inside the tarball when extracing } }) var extractFilesDirs = tar.extract('./my-other-other-directory', { ignore: function(_, header) { // pass files & directories, ignore e.g. symlinks return header.type !== 'file' && header.type !== 'directory' } }) ``` You can also specify which entries to pack using the `entries` option ```js var pack = tar.pack('./my-directory', { entries: ['file1', 'subdir/file2'] // only the specific entries will be packed }) ``` If you want to modify the headers when packing/extracting add a map function to the options ``` js var pack = tar.pack('./my-directory', { map: function(header) { header.name = 'prefixed/'+header.name return header } }) var extract = tar.extract('./my-directory', { map: function(header) { header.name = 'another-prefix/'+header.name return header } }) ``` Similarly you can use `mapStream` incase you wanna modify the input/output file streams ``` js var pack = tar.pack('./my-directory', { mapStream: function(fileStream, header) { // NOTE: the returned stream HAS to have the same length as the input stream. // If not make sure to update the size in the header passed in here. if (path.extname(header.name) === '.js') { return fileStream.pipe(someTransform) } return fileStream; } }) var extract = tar.extract('./my-directory', { mapStream: function(fileStream, header) { if (path.extname(header.name) === '.js') { return fileStream.pipe(someTransform) } return fileStream; } }) ``` Set `options.fmode` and `options.dmode` to ensure that files/directories extracted have the corresponding modes ``` js var extract = tar.extract('./my-directory', { dmode: parseInt(555, 8), // all dirs should be readable fmode: parseInt(444, 8) // all files should be readable }) ``` It can be useful to use `dmode` and `fmode` if you are packing/unpacking tarballs between *nix/windows to ensure that all files/directories unpacked are readable. Alternatively you can set `options.readable` and/or `options.writable` to set the dmode and fmode to readable/writable. ``` js var extract = tar.extract('./my-directory', { readable: true, // all dirs and files should be readable writable: true, // all dirs and files should be writable }) ``` Set `options.strict` to `false` if you want to ignore errors due to unsupported entry types (like device files) To dereference symlinks (pack the contents of the symlink instead of the link itself) set `options.dereference` to `true`. ## Copy a directory Copying a directory with permissions and mtime intact is as simple as ``` js tar.pack('source-directory').pipe(tar.extract('dest-directory')) ``` ## Interaction with [`tar-stream`](https://github.com/mafintosh/tar-stream) Use `finalize: false` and the `finish` hook to leave the pack stream open for further entries (see [`tar-stream#pack`](https://github.com/mafintosh/tar-stream#packing)), and use `pack` to pass an existing pack stream. ``` js var mypack = tar.pack('./my-directory', { finalize: false, finish: function(sameAsMypack) { mypack.entry({name: 'generated-file.txt'}, "hello") tar.pack('./other-directory', { pack: sameAsMypack }) } }) ``` ## Performance Packing and extracting a 6.1 GB with 2496 directories and 2398 files yields the following results on my Macbook Air. [See the benchmark here](https://gist.github.com/mafintosh/8102201) * tar-fs: 34.261 seconds * [node-tar](https://github.com/isaacs/node-tar): 366.123 seconds (or 10x slower) ## License MIT # mustache.js - Logic-less {{mustache}} templates with JavaScript > What could be more logical awesome than no logic at all? [![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) [mustache.js](http://github.com/janl/mustache.js) is a zero-dependency implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. [Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). ## Where to use mustache.js? You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [Node.js](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. mustache.js ships with support for the [CommonJS](http://www.commonjs.org/) module API, the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API (AMD) and [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). In addition to being a package to be used programmatically, you can use it as a [command line tool](#command-line-tool). And this will be your templates after you use Mustache: !['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif) ## Install You can get Mustache via [npm](http://npmjs.com). ```bash $ npm install mustache --save ``` ## Usage Below is a quick example how to use mustache.js: ```js var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); ``` In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. ## Templates A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below. There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them: #### Include Templates If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example: ```js // file: render.js function renderHello() { var template = document.getElementById('template').innerHTML; var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; } ``` ```html <html> <body onload="renderHello()"> <div id="target">Loading...</div> <script id="template" type="x-tmpl-mustache"> Hello {{ name }}! </script> <script src="https://unpkg.com/mustache@latest"></script> <script src="render.js"></script> </body> </html> ``` #### Load External Templates If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): ```js function renderHello() { fetch('template.mustache') .then((response) => response.text()) .then((template) => { var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; }); } ``` ### Variables The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`. If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information. View: ```json { "name": "Chris", "company": "<b>GitHub</b>" } ``` Template: ``` * {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}} {{=<% %>=}} * {{company}} <%={{ }}=%> ``` Output: ```html * Chris * * &lt;b&gt;GitHub&lt;/b&gt; * <b>GitHub</b> * <b>GitHub</b> * {{company}} ``` JavaScript's dot notation may be used to access keys that are properties of objects in a view. View: ```json { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" } ``` Template: ```html * {{name.first}} {{name.last}} * {{age}} ``` Output: ```html * Michael Jackson * RIP ``` ### Sections Sections render blocks of text zero or more times, depending on the value of the key in the current context. A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". The behavior of the section is determined by the value of the key. #### False Values or Empty Lists If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered. View: ```json { "person": false } ``` Template: ```html Shown. {{#person}} Never shown! {{/person}} ``` Output: ```html Shown. ``` #### Non-Empty Lists If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. View: ```json { "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] } ``` Template: ```html {{#stooges}} <b>{{name}}</b> {{/stooges}} ``` Output: ```html <b>Moe</b> <b>Larry</b> <b>Curly</b> ``` When looping over an array of strings, a `.` can be used to refer to the current item in the list. View: ```json { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] } ``` Template: ```html {{#musketeers}} * {{.}} {{/musketeers}} ``` Output: ```html * Athos * Aramis * Porthos * D'Artagnan ``` If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. View: ```js { "beatles": [ { "firstName": "John", "lastName": "Lennon" }, { "firstName": "Paul", "lastName": "McCartney" }, { "firstName": "George", "lastName": "Harrison" }, { "firstName": "Ringo", "lastName": "Starr" } ], "name": function () { return this.firstName + " " + this.lastName; } } ``` Template: ```html {{#beatles}} * {{name}} {{/beatles}} ``` Output: ```html * John Lennon * Paul McCartney * George Harrison * Ringo Starr ``` #### Functions If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. View: ```js { "name": "Tater", "bold": function () { return function (text, render) { return "<b>" + render(text) + "</b>"; } } } ``` Template: ```html {{#bold}}Hi {{name}}.{{/bold}} ``` Output: ```html <b>Hi Tater.</b> ``` ### Inverted Sections An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list. View: ```json { "repos": [] } ``` Template: ```html {{#repos}}<b>{{name}}</b>{{/repos}} {{^repos}}No repos :({{/repos}} ``` Output: ```html No repos :( ``` ### Comments Comments begin with a bang and are ignored. The following template: ```html <h1>Today{{! ignore me }}.</h1> ``` Will render as follows: ```html <h1>Today.</h1> ``` Comments may contain newlines. ### Partials Partials begin with a greater than sign, like {{> box}}. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. They also inherit the calling context. Whereas in ERB you may have this: ```html+erb <%= partial :next_more, :start => start, :size => size %> ``` Mustache requires only this: ```html {{> next_more}} ``` Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. For example, this template and partial: base.mustache: <h2>Names</h2> {{#names}} {{> user}} {{/names}} user.mustache: <strong>{{name}}</strong> Can be thought of as a single, expanded template: ```html <h2>Names</h2> {{#names}} <strong>{{name}}</strong> {{/names}} ``` In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. ```js Mustache.render(template, view, { user: userTemplate }); ``` ### Custom Delimiters Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates. #### Setting in JavaScript The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself: ```js var customTags = [ '<%', '%>' ]; ``` ##### Pass Value into Render Method ```js Mustache.render(template, view, {}, customTags); ``` ##### Override Tags Property ```js Mustache.tags = customTags; // Subsequent parse() and render() calls will use customTags ``` #### Setting in Templates Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. Consider the following contrived example: ```html+erb * {{ default_tags }} {{=<% %>=}} * <% erb_style_tags %> <%={{ }}=%> * {{ default_tags_again }} ``` Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." Custom delimiters may not contain whitespace or the equals sign. ## Pre-parsing and Caching Templates By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`. ```js Mustache.parse(template); // Then, sometime later. Mustache.render(template, view); ``` ## Command line tool mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind ```bash $ npm install -g mustache $ mustache dataView.json myTemplate.mustache > output.html ``` also supports stdin. ```bash $ cat dataView.json | mustache - myTemplate.mustache > output.html ``` or as a package.json `devDependency` in a build process maybe? ```bash $ npm install mustache --save-dev ``` ```json { "scripts": { "build": "mustache dataView.json myTemplate.mustache > public/output.html" } } ``` ```bash $ npm run build ``` The command line tool is basically a wrapper around `Mustache.render` so you get all the features. If your templates use partials you should pass paths to partials using `-p` flag: ```bash $ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache ``` ## Plugins for JavaScript Libraries mustache.js may be built specifically for several different client libraries, including the following: - [jQuery](http://jquery.com/) - [MooTools](http://mootools.net/) - [Dojo](http://www.dojotoolkit.org/) - [YUI](http://developer.yahoo.com/yui/) - [qooxdoo](http://qooxdoo.org/) These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: ```bash $ rake jquery $ rake mootools $ rake dojo $ rake yui3 $ rake qooxdoo ``` ## TypeScript Since the source code of this package is written in JavaScript, we follow the [TypeScript publishing docs](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) preferred approach by having type definitions available via [@types/mustache](https://www.npmjs.com/package/@types/mustache). ## Testing In order to run the tests you'll need to install [Node.js](http://nodejs.org/). You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root. ```bash $ git submodule init $ git submodule update ``` Install dependencies. ```bash $ npm install ``` Then run the tests. ```bash $ npm test ``` The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: 1. Create a template file named `mytest.mustache` in the `test/_files` directory. Replace `mytest` with the name of your test. 2. Create a corresponding view file named `mytest.js` in the same directory. This file should contain a JavaScript object literal enclosed in parentheses. See any of the other view files for an example. 3. Create a file with the expected output in `mytest.txt` in the same directory. Then, you can run the test with: ```bash $ TEST=mytest npm run test-render ``` ### Browser tests Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser: ```bash $ npm run test-browser-local ``` then point your browser to `http://localhost:8080/__zuul` ## Who uses mustache.js? An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js! ## Contributing mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero. ### Your First Contribution - review a [Pull Request](https://github.com/janl/mustache.js/pulls) - fix an [Issue](https://github.com/janl/mustache.js/issues) - update the [documentation](https://github.com/janl/mustache.js#usage) - make a website - write a tutorial ## Thanks mustache.js wouldn't kick ass if it weren't for these fine souls: * Chris Wanstrath / defunkt * Alexander Lang / langalex * Sebastian Cohnen / tisba * J Chris Anderson / jchris * Tom Robinson / tlrobinson * Aaron Quint / quirkey * Douglas Crockford * Nikita Vasilyev / NV * Elise Wood / glytch * Damien Mathieu / dmathieu * Jakub Kuźma / qoobaa * Will Leinweber / will * dpree * Jason Smith / jhs * Aaron Gibralter / agibralter * Ross Boucher / boucher * Matt Sanford / mzsanford * Ben Cherry / bcherry * Michael Jackson / mjackson * Phillip Johnsen / phillipj * David da Silva Contín / dasilvacontin # create-hmac [![NPM Package](https://img.shields.io/npm/v/create-hmac.svg?style=flat-square)](https://www.npmjs.org/package/create-hmac) [![Build Status](https://img.shields.io/travis/crypto-browserify/createHmac.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/createHmac) [![Dependency status](https://img.shields.io/david/crypto-browserify/createHmac.svg?style=flat-square)](https://david-dm.org/crypto-browserify/createHmac#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style HMACs for use in the browser, with native HMAC functions in node. API is the same as HMACs in node: ```js var createHmac = require('create-hmac') var hmac = createHmac('sha224', Buffer.from('secret key')) hmac.update('synchronous write') //optional encoding parameter hmac.digest() // synchronously get result with optional encoding parameter hmac.write('write to it as a stream') hmac.end() //remember it's a stream hmac.read() //only if you ended it as a stream though ``` semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # OWH-vending-machine-js Ejemplo de contrato inteligente utilizando el SDK de JavaScript en NEAR. # Polyfill for `Object.setPrototypeOf` [![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. ## Usage: ``` $ npm install --save setprototypeof ``` ```javascript var setPrototypeOf = require('setprototypeof') var obj = {} setPrototypeOf(obj, { foo: function () { return 'bar' } }) obj.foo() // bar ``` TypeScript is also supported: ```typescript import setPrototypeOf from 'setprototypeof' ``` # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) # create-hash [![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash) Node style hashes for use in the browser, with native hash functions in node. API is the same as hashes in node: ```js var createHash = require('create-hash') var hash = createHash('sha224') hash.update('synchronous write') // optional encoding parameter hash.digest() // synchronously get result with optional encoding parameter hash.write('write to it as a stream') hash.end() // remember it's a stream hash.read() // only if you ended it as a stream though ``` To get the JavaScript version even in node do `require('create-hash/browser')` # Fast Diff [![Build Status](https://travis-ci.org/jhchen/fast-diff.svg)](https://travis-ci.org/jhchen/fast-diff) This is a simplified import of the excellent [diff-match-patch](https://code.google.com/p/google-diff-match-patch/) library by [Neil Fraser](https://neil.fraser.name/) into the Node.js environment. The match and patch parts are removed, as well as all the extra diff options. What remains is incredibly fast diffing between two strings. The diff function is an implementation of ["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.4.6927&rep=rep1&type=pdf) with the suggested divide and conquer strategy along with several [optimizations](http://neil.fraser.name/news/2007/10/09/) Neil added. ```js var diff = require('fast-diff'); var good = 'Good dog'; var bad = 'Bad dog'; var result = diff(good, bad); // [[-1, "Goo"], [1, "Ba"], [0, "d dog"]] // Respect suggested edit location (cursor position), added in v1.1 diff('aaa', 'aaaa', 1) // [[0, "a"], [1, "a"], [0, "aa"]] // For convenience diff.INSERT === 1; diff.EQUAL === 0; diff.DELETE === -1; ``` ## HIDAPI library for Windows, Linux, FreeBSD and macOS | CI instance | Status | |----------------------|--------| | `macOS master` | [![Build Status](https://travis-ci.org/libusb/hidapi.svg?branch=master)](https://travis-ci.org/libusb/hidapi) | | `Windows master` | [![Build status](https://ci.appveyor.com/api/projects/status/r482aevuigmi86rk/branch/master?svg=true)](https://ci.appveyor.com/project/Youw/hidapi/branch/master) | | `Linux/BSD, last build (branch/PR)` | [![builds.sr.ht status](https://builds.sr.ht/~qbicz/hidapi.svg)](https://builds.sr.ht/~qbicz/hidapi?) | HIDAPI is a multi-platform library which allows an application to interface with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and macOS. HIDAPI can be either built as a shared library (`.so`, `.dll` or `.dylib`) or can be embedded directly into a target application by adding a single source file (per platform) and a single header. HIDAPI library was originally developed by Alan Ott ([signal11](https://github.com/signal11)). It was moved to [libusb/hidapi](https://github.com/libusb/hidapi) on June 4th, 2019, in order to merge important bugfixes and continue development of the library. ## Table of Contents * [About](#about) * [What Does the API Look Like?](#what-does-the-api-look-like) * [License](#license) * [Download](#download) * [Build Instructions](#build-instructions) * [Prerequisites](#prerequisites) * [Linux](#linux) * [FreeBSD](#freebsd) * [Mac](#mac) * [Windows](#windows) * [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) * [Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) * [Building on Windows](#building-on-windows) * [Cross Compiling](#cross-compiling) * [Prerequisites](#prerequisites-1) * [Building HIDAPI](#building-hidapi) ## About HIDAPI has five back-ends: * Windows (using `hid.dll`) * Linux/hidraw (using the Kernel's hidraw driver) * Linux/libusb (using libusb-1.0) * FreeBSD (using libusb-1.0) * Mac (using IOHidManager) On Linux, either the hidraw or the libusb back-end can be used. There are tradeoffs, and the functionality supported is slightly different. __Linux/hidraw__ (`linux/hid.c`): This back-end uses the hidraw interface in the Linux kernel, and supports both USB and Bluetooth HID devices. It requires kernel version at least 2.6.39 to build. In addition, it will only communicate with devices which have hidraw nodes associated with them. Keyboards, mice, and some other devices which are blacklisted from having hidraw nodes will not work. Fortunately, for nearly all the uses of hidraw, this is not a problem. __Linux/FreeBSD/libusb__ (`libusb/hid.c`): This back-end uses libusb-1.0 to communicate directly to a USB device. This back-end will of course not work with Bluetooth devices. HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses Fox Toolkit <http://www.fox-toolkit.org>. It will build on every platform which HIDAPI supports. Since it relies on a 3rd party library, building it is optional but recommended because it is so useful when debugging hardware. ## What Does the API Look Like? The API provides the most commonly used HID functions including sending and receiving of input, output, and feature reports. The sample program, which communicates with a heavily hacked up version of the Microchip USB Generic HID sample looks like this (with error checking removed for simplicity): **Warning: Only run the code you understand, and only when it conforms to the device spec. Writing data at random to your HID devices can break them.** ```c #ifdef WIN32 #include <windows.h> #endif #include <stdio.h> #include <stdlib.h> #include "hidapi.h" #define MAX_STR 255 int main(int argc, char* argv[]) { int res; unsigned char buf[65]; wchar_t wstr[MAX_STR]; hid_device *handle; int i; // Initialize the hidapi library res = hid_init(); // Open the device using the VID, PID, // and optionally the Serial number. handle = hid_open(0x4d8, 0x3f, NULL); // Read the Manufacturer String res = hid_get_manufacturer_string(handle, wstr, MAX_STR); wprintf(L"Manufacturer String: %s\n", wstr); // Read the Product String res = hid_get_product_string(handle, wstr, MAX_STR); wprintf(L"Product String: %s\n", wstr); // Read the Serial Number String res = hid_get_serial_number_string(handle, wstr, MAX_STR); wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr); // Read Indexed String 1 res = hid_get_indexed_string(handle, 1, wstr, MAX_STR); wprintf(L"Indexed String 1: %s\n", wstr); // Toggle LED (cmd 0x80). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = 0x80; res = hid_write(handle, buf, 65); // Request state (cmd 0x81). The first byte is the report number (0x0). buf[0] = 0x0; buf[1] = 0x81; res = hid_write(handle, buf, 65); // Read requested state res = hid_read(handle, buf, 65); // Print out the returned buffer. for (i = 0; i < 4; i++) printf("buf[%d]: %d\n", i, buf[i]); // Close the device hid_close(handle); // Finalize the hidapi library res = hid_exit(); return 0; } ``` You can also use [hidtest/test.c](hidtest/test.c) as a starting point for your applications. ## License HIDAPI may be used by one of three licenses as outlined in [LICENSE.txt](LICENSE.txt). ## Download HIDAPI can be downloaded from GitHub ```sh git clone git://github.com/libusb/hidapi.git ``` ## Build Instructions This section is long. Don't be put off by this. It's not long because it's complicated to build HIDAPI; it's quite the opposite. This section is long because of the flexibility of HIDAPI and the large number of ways in which it can be built and used. You will likely pick a single build method. HIDAPI can be built in several different ways. If you elect to build a shared library, you will need to build it from the HIDAPI source distribution. If you choose instead to embed HIDAPI directly into your application, you can skip the building and look at the provided platform Makefiles for guidance. These platform Makefiles are located in `linux/`, `libusb/`, `mac/` and `windows/` and are called `Makefile-manual`. In addition, Visual Studio projects are provided. Even if you're going to embed HIDAPI into your project, it is still beneficial to build the example programs. ### Prerequisites: #### Linux: On Linux, you will need to install development packages for libudev, libusb and optionally Fox-toolkit (for the test GUI). On Debian/Ubuntu systems these can be installed by running: ```sh sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev ``` If you downloaded the source directly from the git repository (using git clone), you'll need Autotools: ```sh sudo apt-get install autotools-dev autoconf automake libtool ``` #### FreeBSD: On FreeBSD you will need to install GNU make, libiconv, and optionally Fox-Toolkit (for the test GUI). This is done by running the following: ```sh pkg_add -r gmake libiconv fox16 ``` If you downloaded the source directly from the git repository (using git clone), you'll need Autotools: ```sh pkg_add -r autotools ``` #### Mac: On Mac, you will need to install Fox-Toolkit if you wish to build the Test GUI. There are two ways to do this, and each has a slight complication. Which method you use depends on your use case. If you wish to build the Test GUI just for your own testing on your own computer, then the easiest method is to install Fox-Toolkit using ports: ```sh sudo port install fox ``` If you wish to build the TestGUI app bundle to redistribute to others, you will need to install Fox-toolkit from source. This is because the version of fox that gets installed using ports uses the ports X11 libraries which are not compatible with the Apple X11 libraries. If you install Fox with ports and then try to distribute your built app bundle, it will simply fail to run on other systems. To install Fox-Toolkit manually, download the source package from <http://www.fox-toolkit.org>, extract it, and run the following from within the extracted source: ```sh ./configure && make && make install ``` #### Windows: On Windows, if you want to build the test GUI, you will need to get the `hidapi-externals.zip` package from the download site. This contains pre-built binaries for Fox-toolkit. Extract `hidapi-externals.zip` just outside of hidapi, so that hidapi-externals and hidapi are on the same level, as shown: ``` Parent_Folder | +hidapi +hidapi-externals ``` Again, this step is not required if you do not wish to build the test GUI. ### Building HIDAPI into a shared library on Unix Platforms: On Unix-like systems such as Linux, FreeBSD, macOS, and even Windows, using MinGW or Cygwin, the easiest way to build a standard system-installed shared library is to use the GNU Autotools build system. If you checked out the source from the git repository, run the following: ```sh ./bootstrap ./configure make make install # as root, or using sudo ``` If you downloaded a source package (i.e.: if you did not run git clone), you can skip the `./bootstrap` step. `./configure` can take several arguments which control the build. The two most likely to be used are: ```sh --enable-testgui Enable build of the Test GUI. This requires Fox toolkit to be installed. Instructions for installing Fox-Toolkit on each platform are in the Prerequisites section above. --prefix=/usr Specify where you want the output headers and libraries to be installed. The example above will put the headers in /usr/include and the binaries in /usr/lib. The default is to install into /usr/local which is fine on most systems. ``` ### Building the manual way on Unix platforms: Manual Makefiles are provided mostly to give the user and idea what it takes to build a program which embeds HIDAPI directly inside of it. These should really be used as examples only. If you want to build a system-wide shared library, use the Autotools method described above. To build HIDAPI using the manual Makefiles, change to the directory of your platform and run make. For example, on Linux run: ```sh cd linux/ make -f Makefile-manual ``` To build the Test GUI using the manual makefiles: ```sh cd testgui/ make -f Makefile-manual ``` ### Building on Windows: To build the HIDAPI DLL on Windows using Visual Studio, build the `.sln` file in the `windows/` directory. To build the Test GUI on windows using Visual Studio, build the `.sln` file in the `testgui/` directory. To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions in the section [Building HIDAPI into a shared library on Unix Platforms](#building-hidapi-into-a-shared-library-on-unix-platforms) above. Note that building the Test GUI with MinGW or Cygwin will require the Windows procedure in the [Prerequisites](#prerequisites-1) section above (i.e.: `hidapi-externals.zip`). To build HIDAPI using MinGW using the Manual Makefiles, see the section [Building the manual way on Unix platforms](#building-the-manual-way-on-unix-platforms) above. HIDAPI can also be built using the Windows DDK (now also called the Windows Driver Kit or WDK). This method was originally required for the HIDAPI build but not anymore. However, some users still prefer this method. It is not as well supported anymore but should still work. Patches are welcome if it does not. To build using the DDK: 1. Install the Windows Driver Kit (WDK) from Microsoft. 2. From the Start menu, in the Windows Driver Kits folder, select Build Environments, then your operating system, then the x86 Free Build Environment (or one that is appropriate for your system). 3. From the console, change directory to the `windows/ddk_build/` directory, which is part of the HIDAPI distribution. 4. Type build. 5. You can find the output files (DLL and LIB) in a subdirectory created by the build system which is appropriate for your environment. On Windows XP, this directory is `objfre_wxp_x86/i386`. ## Cross Compiling This section talks about cross compiling HIDAPI for Linux using Autotools. This is useful for using HIDAPI on embedded Linux targets. These instructions assume the most raw kind of embedded Linux build, where all prerequisites will need to be built first. This process will of course vary based on your embedded Linux build system if you are using one, such as OpenEmbedded or Buildroot. For the purpose of this section, it will be assumed that the following environment variables are exported. ```sh $ export STAGING=$HOME/out $ export HOST=arm-linux ``` `STAGING` and `HOST` can be modified to suit your setup. ### Prerequisites Note that the build of libudev is the very basic configuration. Build libusb. From the libusb source directory, run: ```sh ./configure --host=$HOST --prefix=$STAGING make make install ``` Build libudev. From the libudev source directory, run: ```sh ./configure --disable-gudev --disable-introspection --disable-hwdb \ --host=$HOST --prefix=$STAGING make make install ``` ### Building HIDAPI Build HIDAPI: ``` PKG_CONFIG_DIR= \ PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \ PKG_CONFIG_SYSROOT_DIR=$STAGING \ ./configure --host=$HOST --prefix=$STAGING ``` # pump pump is a small node module that pipes streams together and destroys all of them if one of them closes. ``` npm install pump ``` [![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) ## What problem does it solve? When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. You are also not able to provide a callback to tell when then pipe has finished. pump does these two things for you ## Usage Simply pass the streams you want to pipe together to pump and add an optional callback ``` js var pump = require('pump') var fs = require('fs') var source = fs.createReadStream('/dev/random') var dest = fs.createWriteStream('/dev/null') pump(source, dest, function(err) { console.log('pipe finished', err) }) setTimeout(function() { dest.destroy() // when dest is closed pump will destroy source }, 1000) ``` You can use pump to pipe more than two streams together as well ``` js var transform = someTransformStream() pump(source, transform, anotherTransform, dest, function(err) { console.log('pipe finished', err) }) ``` If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: ``` return pump(s1, s2) // returns s2 ``` If you want to return a stream that combines *both* s1 and s2 to a single stream use [pumpify](https://github.com/mafintosh/pumpify) instead. ## License MIT ## Related `pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. NOTE: The default branch has been renamed! master is now named main If you have a local clone, you can update it by running: ```shell git branch -m master main git fetch origin git branch -u origin/main main ``` # **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead. There are three options for implementing addons: Node-API, nan, or direct use of internal V8, libuv and Node.js libraries. Unless there is a need for direct access to functionality which is not exposed by Node-API as outlined in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) in Node.js core, use Node-API. Refer to [C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) for more information on Node-API. Node-API is an ABI stable C interface provided by Node.js for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as part of Node.js itself. It is intended to insulate native addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. The `node-addon-api` module, which is not part of Node.js, preserves the benefits of the Node-API as it consists only of inline code that depends only on the stable API provided by Node-API. As such, modules built against one version of Node.js using node-addon-api should run without having to be rebuilt with newer versions of Node.js. It is important to remember that *other* Node.js interfaces such as `libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` exclusively and build against a version of Node.js that includes an implementation of Node-API (meaning an active LTS version of Node.js) in order to benefit from ABI stability across Node.js major versions. Node.js provides an [ABI stability guide][] containing a detailed explanation of ABI stability in general, and the Node-API ABI stability guarantee in particular. As new APIs are added to Node-API, node-addon-api must be updated to provide wrappers for those new APIs. For this reason node-addon-api provides methods that allow callers to obtain the underlying Node-API handles so direct calls to Node-API and the use of the objects/methods provided by node-addon-api can be used together. For example, in order to be able to use an API for which the node-addon-api does not yet provide a wrapper. APIs exposed by node-addon-api are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the **ECMA262 Language Specification**. The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. - **[Setup](#setup)** - **[API Documentation](#api)** - **[Examples](#examples)** - **[Tests](#tests)** - **[More resource and info about native Addons](#resources)** - **[Badges](#badges)** - **[Code of Conduct](CODE_OF_CONDUCT.md)** - **[Contributors](#contributors)** - **[License](#license)** ## **Current version: 3.2.1** (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) [![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) <a name="setup"></a> node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-API version. **However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. The oldest Node.js version supported by the current version of node-addon-api is Node.js 10.x. ## Setup - [Installation and usage](doc/setup.md) - [node-gyp](doc/node-gyp.md) - [cmake-js](doc/cmake-js.md) - [Conversion tool](doc/conversion-tool.md) - [Checker tool](doc/checker-tool.md) - [Generator](doc/generator.md) - [Prebuild tools](doc/prebuild_tools.md) <a name="api"></a> ### **API Documentation** The following is the documentation for node-addon-api. - [Full Class Hierarchy](doc/hierarchy.md) - [Addon Structure](doc/addon.md) - Data Types: - [Env](doc/env.md) - [CallbackInfo](doc/callbackinfo.md) - [Reference](doc/reference.md) - [Value](doc/value.md) - [Name](doc/name.md) - [Symbol](doc/symbol.md) - [String](doc/string.md) - [Number](doc/number.md) - [Date](doc/date.md) - [BigInt](doc/bigint.md) - [Boolean](doc/boolean.md) - [External](doc/external.md) - [Object](doc/object.md) - [Array](doc/array.md) - [ObjectReference](doc/object_reference.md) - [PropertyDescriptor](doc/property_descriptor.md) - [Function](doc/function.md) - [FunctionReference](doc/function_reference.md) - [ObjectWrap](doc/object_wrap.md) - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - [Buffer](doc/buffer.md) - [ArrayBuffer](doc/array_buffer.md) - [TypedArray](doc/typed_array.md) - [TypedArrayOf](doc/typed_array_of.md) - [DataView](doc/dataview.md) - [Error Handling](doc/error_handling.md) - [Error](doc/error.md) - [TypeError](doc/type_error.md) - [RangeError](doc/range_error.md) - [Object Lifetime Management](doc/object_lifetime_management.md) - [HandleScope](doc/handle_scope.md) - [EscapableHandleScope](doc/escapable_handle_scope.md) - [Memory Management](doc/memory_management.md) - [Async Operations](doc/async_operations.md) - [AsyncWorker](doc/async_worker.md) - [AsyncContext](doc/async_context.md) - [AsyncWorker Variants](doc/async_worker_variants.md) - [Thread-safe Functions](doc/threadsafe.md) - [ThreadSafeFunction](doc/threadsafe_function.md) - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) - [Promises](doc/promises.md) - [Version management](doc/version_management.md) <a name="examples"></a> ### **Examples** Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** - **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** - **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** - **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** - **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** - **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** - **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** - **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** <a name="tests"></a> ### **Tests** To run the **node-addon-api** tests do: ``` npm install npm test ``` To avoid testing the deprecated portions of the API run ``` npm install npm test --disable-deprecated ``` To run the tests targeting a specific version of Node-API run ``` npm install export NAPI_VERSION=X npm test --NAPI_VERSION=X ``` where X is the version of Node-API you want to target. ### **Debug** To run the **node-addon-api** tests with `--debug` option: ``` npm run-script dev ``` If you want faster build, you might use the following option: ``` npm run-script dev:incremental ``` Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** ### **Benchmarks** You can run the available benchmarks using the following command: ``` npm run-script benchmark ``` See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. <a name="resources"></a> ### **More resource and info about native Addons** - **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** - **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** - **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** - **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** As node-addon-api's core mission is to expose the plain C Node-API as C++ wrappers, tools that facilitate n-api/node-addon-api providing more convenient patterns on developing a Node.js add-ons with n-api/node-addon-api can be published to NPM as standalone packages. It is also recommended to tag such packages with `node-addon-api` to provide more visibility to the community. Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). <a name="other-bindings"></a> ### **Other bindings** - **[napi-rs](https://napi.rs)** - (`Rust`) <a name="badges"></a> ### **Badges** The use of badges is recommended to indicate the minimum version of Node-API required for the module. This helps to determine which Node.js major versions are supported. Addon maintainers can consult the [Node-API support matrix][] to determine which Node.js versions provide a given Node-API version. The following badges are available: ![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) ![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) ![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) ![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) ![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) ![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) ![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) ![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) ![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) ## **Contributing** We love contributions from the community to **node-addon-api**! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. <a name="contributors"></a> ## Team members ### Active | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Chengzhong Wu | [legendecas](https://github.com/legendecas) | | Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Jim Schlight | [jschlight](https://github.com/jschlight) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | | Kevin Eady | [KevinEady](https://github.com/KevinEady) | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | ### Emeritus | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | | Jason Ginchereau | [jasongin](https://github.com/jasongin) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | | Taylor Woll | [boingoing](https://github.com/boingoing) | <a name="license"></a> Licensed under [MIT](./LICENSE.md) [ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ [Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix file-uri-to-path ================ ### Convert a `file:` URI to a file path [![Build Status](https://travis-ci.org/TooTallNate/file-uri-to-path.svg?branch=master)](https://travis-ci.org/TooTallNate/file-uri-to-path) Accepts a `file:` URI and returns a regular file path suitable for use with the `fs` module functions. Installation ------------ Install with `npm`: ``` bash $ npm install file-uri-to-path ``` Example ------- ``` js var uri2path = require('file-uri-to-path'); uri2path('file://localhost/c|/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file:///c|/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file://localhost/c:/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file://hostname/path/to/the%20file.txt'); // "\\\\hostname\\path\\to\\the file.txt" uri2path('file:///c:/path/to/the%20file.txt'); // "c:\\path\\to\\the file.txt" ``` API --- ### fileUriToPath(String uri) → String License ------- (The MIT License) Copyright (c) 2014 Nathan Rajlich &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ci-info Get details about the current Continuous Integration environment. Please [open an issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info) [![Build status](https://travis-ci.org/watson/ci-info.svg?branch=master)](https://travis-ci.org/watson/ci-info) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install ci-info --save ``` ## Usage ```js var ci = require('ci-info') if (ci.isCI) { console.log('The name of the CI server is:', ci.name) } else { console.log('This program is not running on a CI server') } ``` ## Supported CI tools Officially supported CI servers: | Name | Constant | isPR | |------|----------|------| | [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 | | [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ | | [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ | | [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 | | [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ | | [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ | | [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ | | [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ | | [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ | | [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ | | [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 | | [Drone](https://drone.io) | `ci.DRONE` | ✅ | | [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 | | [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | 🚫 | | [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 | | [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 | | [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ | | [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 | | [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ | | [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ | | [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ | | [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ | | [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ | | [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 | | [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 | | [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 | | [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ | ## API ### `ci.name` Returns a string containing name of the CI server the code is running on. If CI server is not detected, it returns `null`. Don't depend on the value of this string not to change for a specific vendor. If you find your self writing `ci.name === 'Travis CI'`, you most likely want to use `ci.TRAVIS` instead. ### `ci.isCI` Returns a boolean. Will be `true` if the code is running on a CI server, otherwise `false`. Some CI servers not listed here might still trigger the `ci.isCI` boolean to be set to `true` if they use certain vendor neutral environment variables. In those cases `ci.name` will be `null` and no vendor specific boolean will be set to `true`. ### `ci.isPR` Returns a boolean if PR detection is supported for the current CI server. Will be `true` if a PR is being tested, otherwise `false`. If PR detection is not supported for the current CI server, the value will be `null`. ### `ci.<VENDOR-CONSTANT>` A vendor specific boolean constant is exposed for each support CI vendor. A constant will be `true` if the code is determined to run on the given CI server, otherwise `false`. Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a complete list, see the support table above. Deprecated vendor constants that will be removed in the next major release: - `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO` ## License [MIT](LICENSE) A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc # ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg [travis-url]: https://travis-ci.org/feross/ieee754 [npm-image]: https://img.shields.io/npm/v/ieee754.svg [npm-url]: https://npmjs.org/package/ieee754 [downloads-image]: https://img.shields.io/npm/dm/ieee754.svg [downloads-url]: https://npmjs.org/package/ieee754 [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg [saucelabs-url]: https://saucelabs.com/u/ieee754 ### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. ## install ``` npm install ieee754 ``` ## methods `var ieee754 = require('ieee754')` The `ieee754` object has the following functions: ``` ieee754.read = function (buffer, offset, isLE, mLen, nBytes) ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) ``` The arguments mean the following: - buffer = the buffer - offset = offset into the buffer - value = value to set (only for `write`) - isLe = is little endian? - mLen = mantissa length - nBytes = number of bytes ## what is ieee754? The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). ## license BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. randombytes === [![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues ```js var randomBytes = require('randombytes'); randomBytes(16);//get 16 random bytes randomBytes(16, function (err, resp) { // resp is 16 random bytes }); ``` # js-sha256 [![Build Status](https://travis-ci.org/emn178/js-sha256.svg?branch=master)](https://travis-ci.org/emn178/js-sha256) [![Coverage Status](https://coveralls.io/repos/emn178/js-sha256/badge.svg?branch=master)](https://coveralls.io/r/emn178/js-sha256?branch=master) [![CDNJS](https://img.shields.io/cdnjs/v/js-sha256.svg)](https://cdnjs.com/libraries/js-sha256/) [![NPM](https://nodei.co/npm/js-sha256.png?stars&downloads)](https://nodei.co/npm/js-sha256/) A simple SHA-256 / SHA-224 hash function for JavaScript supports UTF-8 encoding. ## Demo [SHA256 Online](http://emn178.github.io/online-tools/sha256.html) [SHA224 Online](http://emn178.github.io/online-tools/sha224.html) ## Download [Compress](https://raw.github.com/emn178/js-sha256/master/build/sha256.min.js) [Uncompress](https://raw.github.com/emn178/js-sha256/master/src/sha256.js) ## Installation You can also install js-sha256 by using Bower. bower install js-sha256 For node.js, you can use this command to install: npm install js-sha256 ## Usage You could use like this: ```JavaScript sha256('Message to hash'); sha224('Message to hash'); var hash = sha256.create(); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.update('Message to hash'); hash2.update('Message2 to hash'); hash2.array(); // HMAC sha256.hmac('key', 'Message to hash'); sha224.hmac('key', 'Message to hash'); var hash = sha256.hmac.create('key'); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.hmac.update('key', 'Message to hash'); hash2.update('Message2 to hash'); hash2.array(); ``` If you use node.js, you should require the module first: ```JavaScript var sha256 = require('js-sha256'); ``` or ```JavaScript var sha256 = require('js-sha256').sha256; var sha224 = require('js-sha256').sha224; ``` It supports AMD: ```JavaScript require(['your/path/sha256.js'], function(sha256) { // ... }); ``` or TypeScript ```TypeScript import { sha256, sha224 } from 'js-sha256'; ``` ## Example ```JavaScript sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256('The quick brown fox jumps over the lazy dog'); // d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 sha256('The quick brown fox jumps over the lazy dog.'); // ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c sha224(''); // d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f sha224('The quick brown fox jumps over the lazy dog'); // 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 sha224('The quick brown fox jumps over the lazy dog.'); // 619cba8e8e05826e9b8c519c0a5c68f4fb653e8a3d8aa04bb2c8cd4c // It also supports UTF-8 encoding sha256('中文'); // 72726d8818f693066ceb69afa364218b692e62ea92b385782363780f47529c21 sha224('中文'); // dfbab71afdf54388af4d55f8bd3de8c9b15e0eb916bf9125f4a959d4 // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input sha256([]); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256(new Uint8Array([211, 212])); // 182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f // Different output sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.hex(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.array(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.digest(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.arrayBuffer(''); // ArrayBuffer ``` ## License The project is released under the [MIT license](http://www.opensource.org/licenses/MIT). ## Contact The project's website is located at https://github.com/emn178/js-sha256 Author: Chen, Yi-Cyuan ([email protected]) # y18n [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js const __ = require('y18n')().__; console.log(__('my awesome string %s', 'foo')); ``` output: `my awesome string foo` _using tagged template literals_ ```js const __ = require('y18n')().__; const str = 'foo'; console.log(__`my awesome string ${str}`); ``` output: `my awesome string foo` _pluralization support:_ ```js const __n = require('y18n')().__n; console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); ``` output: `2 fishes foo` ## Deno Example As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): ```typescript import y18n from "https://deno.land/x/y18n/deno.ts"; const __ = y18n({ locale: 'pirate', directory: './test/locales' }).__ console.info(__`Hi, ${'Ben'} ${'Coe'}!`) ``` You will need to run with `--allow-read` to load alternative locales. ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). ## License ISC [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard [![Tests](https://github.com/hildjj/nofilter/actions/workflows/node.js.yml/badge.svg)](https://github.com/hildjj/nofilter/actions/workflows/node.js.yml) [![coverage](https://codecov.io/gh/hildjj/nofilter/branch/main/graph/badge.svg?token=7BdD02c03C)](https://codecov.io/gh/hildjj/nofilter) # NoFilter A node.js package to read and write a stream of data into or out of what looks like a growable [Buffer](https://nodejs.org/api/buffer.html). I kept needing this, and none of the existing packages seemed to have enough features, test coverage, etc. # Examples As a data sink: ```js const NoFilter = require('nofilter') // In ES6: // import NoFilter from 'nofilter' // In typescript: // import NoFilter = require('nofilter') const nf = new NoFilter() nf.on('finish', () => { console.log(nf.toString('base64')) }) process.stdin.pipe(nf) ``` As a data source: ```js const NoFilter = require('nofilter') const nf = new NoFilter('010203', 'hex') nf.pipe(process.stdout) ``` Read the [API Docs](http://hildjj.github.io/nofilter/). Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # sourcemap-codec Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). ## Why? Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. This package makes the process slightly easier. ## Installation ```bash npm install sourcemap-codec ``` ## Usage ```js import { encode, decode } from 'sourcemap-codec'; var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); assert.deepEqual( decoded, [ // the first line (of the generated code) has no mappings, // as shown by the starting semi-colon (which separates lines) [], // the second line contains four (comma-separated) segments [ // segments are encoded as you'd expect: // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] // i.e. the first segment begins at column 2, and maps back to the second column // of the second line (both zero-based) of the 0th source, and uses the 0th // name in the `map.names` array [ 2, 0, 2, 2, 0 ], // the remaining segments are 4-length rather than 5-length, // because they don't map a name [ 4, 0, 2, 4 ], [ 6, 0, 2, 5 ], [ 7, 0, 2, 7 ] ], // the final line contains two segments [ [ 2, 1, 10, 19 ], [ 12, 1, 11, 20 ] ] ]); var encoded = encode( decoded ); assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); ``` # License MIT # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` must be an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1", {ecmaVersion: 2020})); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options are provided by in a second argument, which should be an object containing any of these fields (only `ecmaVersion` is required): - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` (the latest the library supports). This influences support for strict mode, the set of reserved words, and support for new syntax features. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features must be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. **NOTE**: If set to `"module"`, then static `import` / `export` syntax will be valid, even if `ecmaVersion` is less than 6. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed, and also allows `import.meta` expressions to appear in scripts (when `sourceType` is not `"module"`). - **allowAwaitOutsideFunction**: If `false`, `await` expressions can only appear inside `async` functions. Defaults to `true` for `ecmaVersion` 2022 and later, `false` for lower versions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowSuperOutsideMethod**: By default, `super` outside a method raises an error. Set this to `true` to accept such code. - **allowHashBang**: When this is enabled, if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. Defaults to true when `ecmaVersion` >= 2023. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)", {ecmaVersion: 2020}); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--allow-await-outside-function`: Allows top-level `await` expressions. See the `allowAwaitOutsideFunction` option for more information. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # near-ledger-js A JavaScript library for communication with [Ledger](https://www.ledger.com/) Hardware Wallet. # Example usage ```javascript import { createClient, getSupportedTransport } from "near-ledger-js"; const transport = await getSupportedTransport(); transport.setScrambleKey("NEAR"); transport.on('disconnect', () => {...}); ``` In an onClick handler: ```javascript const client = await createClient(transport); // If no error thrown, ledger is available. NOTE: U2F transport will still get here even if device is not present ``` To see debug logging for `getSupportedTransport()`, import `setDebugLogging()` and call `setDebugLogging(true)` before using the package. # How to run demo project 1. `yarn` to install dependencies 2. `yarn start` to start local server with Parcel 3. Open https://localhost:1234 in your browser 4. Open browser console 5. Try examples shown on the page # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. Deep Extend =========== Recursive object extending. [![Build Status](https://api.travis-ci.org/unclechu/node-deep-extend.svg?branch=master)](https://travis-ci.org/unclechu/node-deep-extend) [![NPM](https://nodei.co/npm/deep-extend.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/deep-extend/) Install ------- ```bash $ npm install deep-extend ``` Usage ----- ```javascript var deepExtend = require('deep-extend'); var obj1 = { a: 1, b: 2, d: { a: 1, b: [], c: { test1: 123, test2: 321 } }, f: 5, g: 123, i: 321, j: [1, 2] }; var obj2 = { b: 3, c: 5, d: { b: { first: 'one', second: 'two' }, c: { test2: 222 } }, e: { one: 1, two: 2 }, f: [], g: (void 0), h: /abc/g, i: null, j: [3, 4] }; deepExtend(obj1, obj2); console.log(obj1); /* { a: 1, b: 3, d: { a: 1, b: { first: 'one', second: 'two' }, c: { test1: 123, test2: 222 } }, f: [], g: undefined, c: 5, e: { one: 1, two: 2 }, h: /abc/g, i: null, j: [3, 4] } */ ``` Unit testing ------------ ```bash $ npm test ``` Changelog --------- [CHANGELOG.md](./CHANGELOG.md) Any issues? ----------- Please, report about issues [here](https://github.com/unclechu/node-deep-extend/issues). License ------- [MIT](./LICENSE) # asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) Minimal async jobs utility library, with streams support. [![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) [![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) [![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) [![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) <!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) --> AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. | compression | size | | :----------------- | -------: | | asynckit.js | 12.34 kB | | asynckit.min.js | 4.11 kB | | asynckit.min.js.gz | 1.47 kB | ## Install ```sh $ npm install --save asynckit ``` ## Examples ### Parallel Jobs Runs iterator over provided array in parallel. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will terminate rest of the active jobs (if abort function is provided) and return error along with salvaged data to the main callback function. #### Input Array ```javascript var parallel = require('asynckit').parallel , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , target = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // async job accepts one element from the array // and a callback function function asyncJob(item, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var parallel = require('asynckit/parallel') , assert = require('assert') ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] , target = [] , keys = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); assert.deepEqual(keys, expectedKeys); }); // supports full value, key, callback (shortcut) interface function asyncJob(item, key, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { keys.push(key); target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). ### Serial Jobs Runs iterator over provided array sequentially. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will not proceed to the rest of the items in the list and return error along with salvaged data to the main callback function. #### Input Array ```javascript var serial = require('asynckit/serial') , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // extended interface (item, key, callback) // also supported for arrays function asyncJob(item, key, cb) { target.push(key); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var serial = require('asynckit').serial , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // shortcut interface (item, callback) // works for object as well as for the arrays function asyncJob(item, cb) { target.push(item); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). _Note: Since _object_ is an _unordered_ collection of properties, it may produce unexpected results with sequential iterations. Whenever order of the jobs' execution is important please use `serialOrdered` method._ ### Ordered Serial Iterations TBD For example [compare-property](compare-property) package. ### Streaming interface TBD ## Want to Know More? More examples can be found in [test folder](test/). Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. ## License AsyncKit is licensed under the MIT license. # ci-info Get details about the current Continuous Integration environment. Please [open an issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info) [![Tests](https://github.com/watson/ci-info/workflows/Tests/badge.svg)](https://github.com/watson/ci-info/actions) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install ci-info --save ``` ## Usage ```js var ci = require('ci-info') if (ci.isCI) { console.log('The name of the CI server is:', ci.name) } else { console.log('This program is not running on a CI server') } ``` ## Supported CI tools Officially supported CI servers: | Name | Constant | isPR | | ------------------------------------------------------------------------------- | -------------------- | ---- | | [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 | | [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ | | [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ | | [Appcircle](https://appcircle.io/) | `ci.APPCIRCLE` | 🚫 | | [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 | | [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ | | [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ | | [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ | | [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ | | [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ | | [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ | | [Codefresh](https://codefresh.io/) | `ci.CODEFRESH` | ✅ | | [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 | | [Drone](https://drone.io) | `ci.DRONE` | ✅ | | [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 | | [Expo Application Services](https://expo.dev/eas) | `ci.EAS` | 🚫 | | [Gerrit CI](https://www.gerritcodereview.com) | `ci.GERRIT` | 🚫 | | [GitHub Actions](https://github.com/features/actions/) | `ci.GITHUB_ACTIONS` | ✅ | | [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | ✅ | | [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 | | [Google Cloud Build](https://cloud.google.com/build) | `ci.GOOGLE_CLOUD_BUILD` | 🚫 | | [Heroku](https://www.heroku.com) | `ci.HEROKU` | 🚫 | | [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 | | [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ | | [LayerCI](https://layerci.com/) | `ci.LAYERCI` | ✅ | | [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 | | [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ | | [Nevercode](http://nevercode.io/) | `ci.NEVERCODE` | ✅ | | [ReleaseHub](https://releasehub.com/) | `ci.RELEASEHUB` | ✅ | | [Render](https://render.com/) | `ci.RENDER` | ✅ | | [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ | | [Screwdriver](https://screwdriver.cd/) | `ci.SCREWDRIVER` | ✅ | | [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ | | [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ | | [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ | | [Sourcehut](https://sourcehut.org/) | `ci.SOURCEHUT` | 🚫 | | [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 | | [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 | | [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 | | [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ | | [Vercel](https://vercel.com/) | `ci.VERCEL` | 🚫 | | [Visual Studio App Center](https://appcenter.ms/) | `ci.APPCENTER` | 🚫 | | [Woodpecker](https://woodpecker-ci.org/) | `ci.WOODPECKER` | ✅ | ## API ### `ci.name` Returns a string containing name of the CI server the code is running on. If CI server is not detected, it returns `null`. Don't depend on the value of this string not to change for a specific vendor. If you find your self writing `ci.name === 'Travis CI'`, you most likely want to use `ci.TRAVIS` instead. ### `ci.isCI` Returns a boolean. Will be `true` if the code is running on a CI server, otherwise `false`. Some CI servers not listed here might still trigger the `ci.isCI` boolean to be set to `true` if they use certain vendor neutral environment variables. In those cases `ci.name` will be `null` and no vendor specific boolean will be set to `true`. ### `ci.isPR` Returns a boolean if PR detection is supported for the current CI server. Will be `true` if a PR is being tested, otherwise `false`. If PR detection is not supported for the current CI server, the value will be `null`. ### `ci.<VENDOR-CONSTANT>` A vendor specific boolean constant is exposed for each support CI vendor. A constant will be `true` if the code is determined to run on the given CI server, otherwise `false`. Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a complete list, see the support table above. Deprecated vendor constants that will be removed in the next major release: - `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO` ## Ports ci-info has been ported to the following languages | Language | Repository | |----------|------------| | Go | https://github.com/hofstadter-io/cinful | | Rust | https://github.com/sagiegurari/ci_info | | Kotlin | https://github.com/cloudflightio/ci-info | ## License [MIT](LICENSE) # defer-to-connect > The safe way to handle the `connect` socket event [![Coverage Status](https://coveralls.io/repos/github/szmarczak/defer-to-connect/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/defer-to-connect?branch=master) Once you receive the socket, it may be already connected (or disconnected).<br> To avoid checking that, use `defer-to-connect`. It'll do that for you. ## Usage ```js const deferToConnect = require('defer-to-connect'); deferToConnect(socket, () => { console.log('Connected!'); }); ``` ## API ### deferToConnect(socket, connectListener) Calls `connectListener()` when connected. ### deferToConnect(socket, listeners) #### listeners An object representing `connect`, `secureConnect` and `close` properties. Calls `connect()` when the socket is connected.<br> Calls `secureConnect()` when the socket is securely connected.<br> Calls `close()` when the socket is destroyed. ## License MIT # js-string-escape [![Build Status](https://travis-ci.org/joliss/js-string-escape.png?branch=master)](https://travis-ci.org/joliss/js-string-escape) Escape any string to be a valid JavaScript string literal between double quotes or single quotes. ## Installation ``` npm install js-string-escape ``` ## Example If you need to generate JavaScript output, this library will help you safely put arbitrary data in JavaScript strings: ```js jsStringEscape = require('js-string-escape') console.log('"' + jsStringEscape('Quotes (\", \'), newlines (\n), etc.') + '"') // => "Quotes (\", \'), newlines (\n), etc." ``` In other words, given any string `s`, the following invariants hold: ```js eval('"' + jsStringEscape(s) + '"') === s eval("'" + jsStringEscape(s) + "'") === s ``` These `eval` expressions are safe with untrusted strings `s`. Non-strings will be cast to strings. ## Compliance This library has been checked against [ECMAScript 5.1](http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4) and tested against all Unicode code points. Note that the returned string is not necessarily valid JSON, since JSON disallows control characters, and `\'` is illegal in JSON. # minizlib A fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) and [minipass-fetch](http://npm.im/minipass-fetch). Brotli is supported in versions of node with a Brotli binding. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. That being said, Minipass streams to make it fairly easy to use as one-liners: `new zlib.Deflate().end(data).read()` will return the deflate compressed result. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib and Brotli operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. See [Minipass](http://npm.im/minipass) for more on the differences between Node.js core streams and Minipass streams, and the convenience methods provided by that class. ## Classes - Deflate - Inflate - Gzip - Gunzip - DeflateRaw - InflateRaw - Unzip - BrotliCompress (Node v10 and higher) - BrotliDecompress (Node v10 and higher) ## USAGE ```js const zlib = require('minizlib') const input = sourceOfCompressedData() const decode = new zlib.BrotliDecompress() const output = whereToWriteTheDecodedData() input.pipe(decode).pipe(output) ``` ## REPRODUCIBLE BUILDS To create reproducible gzip compressed files across different operating systems, set `portable: true` in the options. This causes minizlib to set the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for 'unknown'. # defer-to-connect > The safe way to handle the `connect` socket event [![Coverage Status](https://coveralls.io/repos/github/szmarczak/defer-to-connect/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/defer-to-connect?branch=master) Once you receive the socket, it may be already connected (or disconnected).<br> To avoid checking that, use `defer-to-connect`. It'll do that for you. ## Usage ```js const deferToConnect = require('defer-to-connect'); deferToConnect(socket, () => { console.log('Connected!'); }); ``` ## API ### deferToConnect(socket, connectListener) Calls `connectListener()` when connected. ### deferToConnect(socket, listeners) #### listeners An object representing `connect`, `secureConnect` and `close` properties. Calls `connect()` when the socket is connected.<br> Calls `secureConnect()` when the socket is securely connected.<br> Calls `close()` when the socket is destroyed. ## License MIT argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js. Javascript port of python's [argparse](http://docs.python.org/dev/library/argparse.html) module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker. **NB. Difference with original.** - Method names changed to camelCase. See [generated docs](http://nodeca.github.com/argparse/). - Use `defaultValue` instead of `default`. - Use `argparse.Const.REMAINDER` instead of `argparse.REMAINDER`, and similarly for constant values `OPTIONAL`, `ZERO_OR_MORE`, and `ONE_OR_MORE` (aliases for `nargs` values `'?'`, `'*'`, `'+'`, respectively), and `SUPPRESS`. Example ======= test.js file: ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse example' }); parser.addArgument( [ '-f', '--foo' ], { help: 'foo bar' } ); parser.addArgument( [ '-b', '--bar' ], { help: 'bar foo' } ); parser.addArgument( '--baz', { help: 'baz bar' } ); var args = parser.parseArgs(); console.dir(args); ``` Display help: ``` $ ./test.js -h usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example Optional arguments: -h, --help Show this help message and exit. -v, --version Show program's version number and exit. -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` More [examples](https://github.com/nodeca/argparse/tree/master/examples). ArgumentParser objects ====================== ``` new ArgumentParser({parameters hash}); ``` Creates a new ArgumentParser object. **Supported params:** - ```description``` - Text to display before the argument help. - ```epilog``` - Text to display after the argument help. - ```addHelp``` - Add a -h/–help option to the parser. (default: true) - ```argumentDefault``` - Set the global default value for arguments. (default: null) - ```parents``` - A list of ArgumentParser objects whose arguments should also be included. - ```prefixChars``` - The set of characters that prefix optional arguments. (default: ‘-‘) - ```formatterClass``` - A class for customizing the help output. - ```prog``` - The name of the program (default: `path.basename(process.argv[1])`) - ```usage``` - The string describing the program usage (default: generated) - ```conflictHandler``` - Usually unnecessary, defines strategy for resolving conflicting optionals. **Not supported yet** - ```fromfilePrefixChars``` - The set of characters that prefix files from which additional arguments should be read. Details in [original ArgumentParser guide](http://docs.python.org/dev/library/argparse.html#argumentparser-objects) addArgument() method ==================== ``` ArgumentParser.addArgument(name or flag or [name] or [flags...], {options}) ``` Defines how a single command-line argument should be parsed. - ```name or flag or [name] or [flags...]``` - Either a positional name (e.g., `'foo'`), a single option (e.g., `'-f'` or `'--foo'`), an array of a single positional name (e.g., `['foo']`), or an array of options (e.g., `['-f', '--foo']`). Options: - ```action``` - The basic type of action to be taken when this argument is encountered at the command line. - ```nargs```- The number of command-line arguments that should be consumed. - ```constant``` - A constant value required by some action and nargs selections. - ```defaultValue``` - The value produced if the argument is absent from the command line. - ```type``` - The type to which the command-line argument should be converted. - ```choices``` - A container of the allowable values for the argument. - ```required``` - Whether or not the command-line option may be omitted (optionals only). - ```help``` - A brief description of what the argument does. - ```metavar``` - A name for the argument in usage messages. - ```dest``` - The name of the attribute to be added to the object returned by parseArgs(). Details in [original add_argument guide](http://docs.python.org/dev/library/argparse.html#the-add-argument-method) Action (some details) ================ ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are: - ```store``` - Just stores the argument’s value. This is the default action. - ```storeConst``` - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag. - ```storeTrue``` and ```storeFalse``` - Stores values True and False respectively. These are special cases of 'storeConst'. - ```append``` - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. - ```appendConst``` - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list. - ```count``` - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels. - ```help``` - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created. - ```version``` - Prints version information and exit. Expects a `version=` keyword argument in the addArgument() call. Details in [original action guide](http://docs.python.org/dev/library/argparse.html#action) Sub-commands ============ ArgumentParser.addSubparsers() Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like `svn checkout`, `svn update`, and `svn commit`. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. `ArgumentParser` supports creation of such sub-commands with `addSubparsers()` method. The `addSubparsers()` method is normally called with no arguments and returns an special action object. This object has a single method `addParser()`, which takes a command name and any `ArgumentParser` constructor arguments, and returns an `ArgumentParser` object that can be modified as usual. Example: sub_commands.js ```javascript #!/usr/bin/env node 'use strict'; var ArgumentParser = require('../lib/argparse').ArgumentParser; var parser = new ArgumentParser({ version: '0.0.1', addHelp:true, description: 'Argparse examples: sub-commands', }); var subparsers = parser.addSubparsers({ title:'subcommands', dest:"subcommand_name" }); var bar = subparsers.addParser('c1', {addHelp:true}); bar.addArgument( [ '-f', '--foo' ], { action: 'store', help: 'foo3 bar3' } ); var bar = subparsers.addParser( 'c2', {aliases:['co'], addHelp:true} ); bar.addArgument( [ '-b', '--bar' ], { action: 'store', type: 'int', help: 'foo3 bar3' } ); var args = parser.parseArgs(); console.dir(args); ``` Details in [original sub-commands guide](http://docs.python.org/dev/library/argparse.html#sub-commands) Contributors ============ - [Eugene Shkuropat](https://github.com/shkuropat) - [Paul Jacobson](https://github.com/hpaulj) [others](https://github.com/nodeca/argparse/graphs/contributors) License ======= Copyright (c) 2012 [Vitaly Puzrin](https://github.com/puzrin). Released under the MIT license. See [LICENSE](https://github.com/nodeca/argparse/blob/master/LICENSE) for details. ### Made by [@kilianvalkhof](https://twitter.com/kilianvalkhof) #### Other projects: - 💻 [Polypane](https://polypane.app) - Develop responsive websites and apps twice as fast on multiple screens at once - 🖌️ [Superposition](https://superposition.design) - Kickstart your design system by extracting design tokens from your website - 🗒️ [FromScratch](https://fromscratch.rocks) - A smart but simple autosaving scratchpad --- # Electron-to-Chromium [![npm](https://img.shields.io/npm/v/electron-to-chromium.svg)](https://www.npmjs.com/package/electron-to-chromium) [![travis](https://img.shields.io/travis/Kilian/electron-to-chromium/master.svg)](https://travis-ci.org/Kilian/electron-to-chromium) [![npm-downloads](https://img.shields.io/npm/dm/electron-to-chromium.svg)](https://www.npmjs.com/package/electron-to-chromium) [![codecov](https://codecov.io/gh/Kilian/electron-to-chromium/branch/master/graph/badge.svg)](https://codecov.io/gh/Kilian/electron-to-chromium)[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_shield) This repository provides a mapping of Electron versions to the Chromium version that it uses. This package is used in [Browserslist](https://github.com/ai/browserslist), so you can use e.g. `electron >= 1.4` in [Autoprefixer](https://github.com/postcss/autoprefixer), [Stylelint](https://github.com/stylelint/stylelint), [babel-preset-env](https://github.com/babel/babel-preset-env) and [eslint-plugin-compat](https://github.com/amilajack/eslint-plugin-compat). **Supported by:** <a href="https://m.do.co/c/bb22ea58e765"> <img src="https://opensource.nyc3.cdn.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_horizontal_blue.svg" width="201px"> </a> ## Install Install using `npm install electron-to-chromium`. ## Usage To include Electron-to-Chromium, require it: ```js var e2c = require('electron-to-chromium'); ``` ### Properties The Electron-to-Chromium object has 4 properties to use: #### `versions` An object of key-value pairs with a _major_ Electron version as the key, and the corresponding major Chromium version as the value. ```js var versions = e2c.versions; console.log(versions['1.4']); // returns "53" ``` #### `fullVersions` An object of key-value pairs with a Electron version as the key, and the corresponding full Chromium version as the value. ```js var versions = e2c.fullVersions; console.log(versions['1.4.11']); // returns "53.0.2785.143" ``` #### `chromiumVersions` An object of key-value pairs with a _major_ Chromium version as the key, and the corresponding major Electron version as the value. ```js var versions = e2c.chromiumVersions; console.log(versions['54']); // returns "1.4" ``` #### `fullChromiumVersions` An object of key-value pairs with a Chromium version as the key, and an array of the corresponding major Electron versions as the value. ```js var versions = e2c.fullChromiumVersions; console.log(versions['54.0.2840.101']); // returns ["1.5.1", "1.5.0"] ``` ### Functions #### `electronToChromium(query)` Arguments: * Query: string or number, required. A major or full Electron version. A function that returns the corresponding Chromium version for a given Electron function. Returns a string. If you provide it with a major Electron version, it will return a major Chromium version: ```js var chromeVersion = e2c.electronToChromium('1.4'); // chromeVersion is "53" ``` If you provide it with a full Electron version, it will return the full Chromium version. ```js var chromeVersion = e2c.electronToChromium('1.4.11'); // chromeVersion is "53.0.2785.143" ``` If a query does not match a Chromium version, it will return `undefined`. ```js var chromeVersion = e2c.electronToChromium('9000'); // chromeVersion is undefined ``` #### `chromiumToElectron(query)` Arguments: * Query: string or number, required. A major or full Chromium version. Returns a string with the corresponding Electron version for a given Chromium query. If you provide it with a major Chromium version, it will return a major Electron version: ```js var electronVersion = e2c.chromiumToElectron('54'); // electronVersion is "1.4" ``` If you provide it with a full Chrome version, it will return an array of full Electron versions. ```js var electronVersions = e2c.chromiumToElectron('56.0.2924.87'); // electronVersions is ["1.6.3", "1.6.2", "1.6.1", "1.6.0"] ``` If a query does not match an Electron version, it will return `undefined`. ```js var electronVersion = e2c.chromiumToElectron('10'); // electronVersion is undefined ``` #### `electronToBrowserList(query)` **DEPRECATED** Arguments: * Query: string or number, required. A major Electron version. _**Deprecated**: Browserlist already includes electron-to-chromium._ A function that returns a [Browserslist](https://github.com/ai/browserslist) query that matches the given major Electron version. Returns a string. If you provide it with a major Electron version, it will return a Browserlist query string that matches the Chromium capabilities: ```js var query = e2c.electronToBrowserList('1.4'); // query is "Chrome >= 53" ``` If a query does not match a Chromium version, it will return `undefined`. ```js var query = e2c.electronToBrowserList('9000'); // query is undefined ``` ### Importing just versions, fullVersions, chromiumVersions and fullChromiumVersions All lists can be imported on their own, if file size is a concern. #### `versions` ```js var versions = require('electron-to-chromium/versions'); ``` #### `fullVersions` ```js var fullVersions = require('electron-to-chromium/full-versions'); ``` #### `chromiumVersions` ```js var chromiumVersions = require('electron-to-chromium/chromium-versions'); ``` #### `fullChromiumVersions` ```js var fullChromiumVersions = require('electron-to-chromium/full-chromium-versions'); ``` ## Updating This package will be updated with each new Electron release. To update the list, run `npm run build.js`. Requires internet access as it downloads from the canonical list of Electron versions. To verify correct behaviour, run `npm test`. ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_large) # TypeScript [![GitHub Actions CI](https://github.com/microsoft/TypeScript/workflows/CI/badge.svg)](https://github.com/microsoft/TypeScript/actions?query=workflow%3ACI) [![Devops Build Status](https://dev.azure.com/typescript/TypeScript/_apis/build/status/Typescript/node10)](https://dev.azure.com/typescript/TypeScript/_build?definitionId=7) [![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript) [![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript) [TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript). Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/). ## Installing For the latest stable version: ```bash npm install -g typescript ``` For our nightly builds: ```bash npm install -g typescript@next ``` ## Contribute There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript. * [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript). * Help each other in the [TypeScript Community Discord](https://discord.gg/typescript). * Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter. * [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md). * Read the archived language specification ([docx](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.docx?raw=true), [pdf](https://github.com/microsoft/TypeScript/blob/main/doc/TypeScript%20Language%20Specification%20-%20ARCHIVED.pdf?raw=true), [md](https://github.com/microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md)). This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. ## Documentation * [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) * [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html) * [Homepage](https://www.typescriptlang.org/) ## Roadmap For details on our planned features and future direction please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap). # expand-template > Expand placeholders in a template string. [![npm](https://img.shields.io/npm/v/expand-template.svg)](https://www.npmjs.com/package/expand-template) ![Node version](https://img.shields.io/node/v/expand-template.svg) [![Build Status](https://travis-ci.org/ralphtheninja/expand-template.svg?branch=master)](https://travis-ci.org/ralphtheninja/expand-template) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) ## Install ``` $ npm i expand-template -S ``` ## Usage Default functionality expands templates using `{}` as separators for string placeholders. ```js var expand = require('expand-template')() var template = '{foo}/{foo}/{bar}/{bar}' console.log(expand(template, { foo: 'BAR', bar: 'FOO' })) // -> BAR/BAR/FOO/FOO ``` Custom separators: ```js var expand = require('expand-template')({ sep: '[]' }) var template = '[foo]/[foo]/[bar]/[bar]' console.log(expand(template, { foo: 'BAR', bar: 'FOO' })) // -> BAR/BAR/FOO/FOO ``` ## License All code, unless stated otherwise, is dual-licensed under [`WTFPL`](http://www.wtfpl.net/txt/copying/) and [`MIT`](https://opensource.org/licenses/MIT). <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/main/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` > Note: `hideBin` is a shorthand for [`process.argv.slice(2)`](https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/). It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690). ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { return yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .parse() ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .parse() ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .parse() ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ``` <details> <summary><strong>What does this do?</strong></summary> <br> This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('to-regex-range'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). <br> </details> <details> <summary><strong>Why use this library?</strong></summary> <br> ### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once <br> </details> ## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | | `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | | `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | | `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | | `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | | `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | | `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | | `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | | `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | | `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | | `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | | `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | | `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | | `toRegexRange(5, 5)` | `5` | _8μs_ | | `toRegexRange(5, 6)` | `5\|6` | _11μs_ | | `toRegexRange(1, 2)` | `1\|2` | _6μs_ | | `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | | `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | | `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | | `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | | `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | | `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | | `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | | `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [doowb](https://github.com/doowb) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ <h1 align="center"> <img width="250" src="https://rawgit.com/lukechilds/keyv/master/media/logo.svg" alt="keyv"> <br> <br> </h1> > Simple key-value storage with support for multiple backends [![Build Status](https://travis-ci.org/lukechilds/keyv.svg?branch=master)](https://travis-ci.org/lukechilds/keyv) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv?branch=master) [![npm](https://img.shields.io/npm/dm/keyv.svg)](https://www.npmjs.com/package/keyv) [![npm](https://img.shields.io/npm/v/keyv.svg)](https://www.npmjs.com/package/keyv) Keyv provides a consistent interface for key-value storage across multiple backends via storage adapters. It supports TTL based expiry, making it suitable as a cache or a persistent key-value store. ## Features There are a few existing modules similar to Keyv, however Keyv is different because it: - Isn't bloated - Has a simple Promise based API - Suitable as a TTL based cache or persistent key-value store - [Easily embeddable](#add-cache-support-to-your-module) inside another module - Works with any storage that implements the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) API - Handles all JSON types plus `Buffer` - Supports namespaces - Wide range of [**efficient, well tested**](#official-storage-adapters) storage adapters - Connection errors are passed through (db failures won't kill your app) - Supports the current active LTS version of Node.js or higher ## Usage Install Keyv. ``` npm install --save keyv ``` By default everything is stored in memory, you can optionally also install a storage adapter. ``` npm install --save @keyv/redis npm install --save @keyv/mongo npm install --save @keyv/sqlite npm install --save @keyv/postgres npm install --save @keyv/mysql ``` Create a new Keyv instance, passing your connection string if applicable. Keyv will automatically load the correct storage adapter. ```js const Keyv = require('keyv'); // One of the following const keyv = new Keyv(); const keyv = new Keyv('redis://user:pass@localhost:6379'); const keyv = new Keyv('mongodb://user:pass@localhost:27017/dbname'); const keyv = new Keyv('sqlite://path/to/database.sqlite'); const keyv = new Keyv('postgresql://user:pass@localhost:5432/dbname'); const keyv = new Keyv('mysql://user:pass@localhost:3306/dbname'); // Handle DB connection errors keyv.on('error', err => console.log('Connection Error', err)); await keyv.set('foo', 'expires in 1 second', 1000); // true await keyv.set('foo', 'never expires'); // true await keyv.get('foo'); // 'never expires' await keyv.delete('foo'); // true await keyv.clear(); // undefined ``` ### Namespaces You can namespace your Keyv instance to avoid key collisions and allow you to clear only a certain namespace while using the same database. ```js const users = new Keyv('redis://user:pass@localhost:6379', { namespace: 'users' }); const cache = new Keyv('redis://user:pass@localhost:6379', { namespace: 'cache' }); await users.set('foo', 'users'); // true await cache.set('foo', 'cache'); // true await users.get('foo'); // 'users' await cache.get('foo'); // 'cache' await users.clear(); // undefined await users.get('foo'); // undefined await cache.get('foo'); // 'cache' ``` ### Custom Serializers Keyv uses [`json-buffer`](https://github.com/dominictarr/json-buffer) for data serialization to ensure consistency across different backends. You can optionally provide your own serialization functions to support extra data types or to serialize to something other than JSON. ```js const keyv = new Keyv({ serialize: JSON.stringify, deserialize: JSON.parse }); ``` **Warning:** Using custom serializers means you lose any guarantee of data consistency. You should do extensive testing with your serialisation functions and chosen storage engine. ## Official Storage Adapters The official storage adapters are covered by [over 150 integration tests](https://travis-ci.org/lukechilds/keyv/jobs/260418145) to guarantee consistent behaviour. They are lightweight, efficient wrappers over the DB clients making use of indexes and native TTLs where available. Database | Adapter | Native TTL | Status ---|---|---|--- Redis | [@keyv/redis](https://github.com/lukechilds/keyv-redis) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-redis.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-redis) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-redis/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-redis?branch=master) MongoDB | [@keyv/mongo](https://github.com/lukechilds/keyv-mongo) | Yes | [![Build Status](https://travis-ci.org/lukechilds/keyv-mongo.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mongo) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-mongo/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-mongo?branch=master) SQLite | [@keyv/sqlite](https://github.com/lukechilds/keyv-sqlite) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-sqlite.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-sqlite) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-sqlite/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-sqlite?branch=master) PostgreSQL | [@keyv/postgres](https://github.com/lukechilds/keyv-postgres) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-postgres.svg?branch=master)](https://travis-ci.org/lukechildskeyv-postgreskeyv) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-postgres/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-postgres?branch=master) MySQL | [@keyv/mysql](https://github.com/lukechilds/keyv-mysql) | No | [![Build Status](https://travis-ci.org/lukechilds/keyv-mysql.svg?branch=master)](https://travis-ci.org/lukechilds/keyv-mysql) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/keyv-mysql/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/keyv-mysql?branch=master) ## Third-party Storage Adapters You can also use third-party storage adapters or build your own. Keyv will wrap these storage adapters in TTL functionality and handle complex types internally. ```js const Keyv = require('keyv'); const myAdapter = require('./my-storage-adapter'); const keyv = new Keyv({ store: myAdapter }); ``` Any store that follows the [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) api will work. ```js new Keyv({ store: new Map() }); ``` For example, [`quick-lru`](https://github.com/sindresorhus/quick-lru) is a completely unrelated module that implements the Map API. ```js const Keyv = require('keyv'); const QuickLRU = require('quick-lru'); const lru = new QuickLRU({ maxSize: 1000 }); const keyv = new Keyv({ store: lru }); ``` The following are third-party storage adapters compatible with Keyv: - [quick-lru](https://github.com/sindresorhus/quick-lru) - Simple "Least Recently Used" (LRU) cache - [keyv-file](https://github.com/zaaack/keyv-file) - File system storage adapter for Keyv - [keyv-dynamodb](https://www.npmjs.com/package/keyv-dynamodb) - DynamoDB storage adapter for Keyv ## Add Cache Support to your Module Keyv is designed to be easily embedded into other modules to add cache support. The recommended pattern is to expose a `cache` option in your modules options which is passed through to Keyv. Caching will work in memory by default and users have the option to also install a Keyv storage adapter and pass in a connection string, or any other storage that implements the `Map` API. You should also set a namespace for your module so you can safely call `.clear()` without clearing unrelated app data. Inside your module: ```js class AwesomeModule { constructor(opts) { this.cache = new Keyv({ uri: typeof opts.cache === 'string' && opts.cache, store: typeof opts.cache !== 'string' && opts.cache, namespace: 'awesome-module' }); } } ``` Now it can be consumed like this: ```js const AwesomeModule = require('awesome-module'); // Caches stuff in memory by default const awesomeModule = new AwesomeModule(); // After npm install --save keyv-redis const awesomeModule = new AwesomeModule({ cache: 'redis://localhost' }); // Some third-party module that implements the Map API const awesomeModule = new AwesomeModule({ cache: some3rdPartyStore }); ``` ## API ### new Keyv([uri], [options]) Returns a new Keyv instance. The Keyv instance is also an `EventEmitter` that will emit an `'error'` event if the storage adapter connection fails. ### uri Type: `String`<br> Default: `undefined` The connection string URI. Merged into the options object as options.uri. ### options Type: `Object` The options object is also passed through to the storage adapter. Check your storage adapter docs for any extra options. #### options.namespace Type: `String`<br> Default: `'keyv'` Namespace for the current instance. #### options.ttl Type: `Number`<br> Default: `undefined` Default TTL. Can be overridden by specififying a TTL on `.set()`. #### options.serialize Type: `Function`<br> Default: `JSONB.stringify` A custom serialization function. #### options.deserialize Type: `Function`<br> Default: `JSONB.parse` A custom deserialization function. #### options.store Type: `Storage adapter instance`<br> Default: `new Map()` The storage adapter instance to be used by Keyv. #### options.adapter Type: `String`<br> Default: `undefined` Specify an adapter to use. e.g `'redis'` or `'mongodb'`. ### Instance Keys must always be strings. Values can be of any type. #### .set(key, value, [ttl]) Set a value. By default keys are persistent. You can set an expiry TTL in milliseconds. Returns `true`. #### .get(key) Returns the value. #### .delete(key) Deletes an entry. Returns `true` if the key existed, `false` if not. #### .clear() Delete all entries in the current namespace. Returns `undefined`. ## License MIT © Luke Childs # pbkdf2 [![NPM Package](https://img.shields.io/npm/v/pbkdf2.svg?style=flat-square)](https://www.npmjs.org/package/pbkdf2) [![Build Status](https://img.shields.io/travis/crypto-browserify/pbkdf2.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/pbkdf2) [![Dependency status](https://img.shields.io/david/crypto-browserify/pbkdf2.svg?style=flat-square)](https://david-dm.org/crypto-browserify/pbkdf2#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()` ## Usage ```js var pbkdf2 = require('pbkdf2') var derivedKey = pbkdf2.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') ... ``` For more information on the API, please see the relevant [Node documentation](https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback). For high performance, use the `async` variant (`pbkdf2.pbkdf2`), not `pbkdf2.pbkdf2Sync`, this variant has the oppurtunity to use `window.crypto.subtle` when browserified. ## Credits This module is a derivative of [cryptocoinjs/pbkdf2-sha256](https://github.com/cryptocoinjs/pbkdf2-sha256/), so thanks to [JP Richardson](https://github.com/jprichardson/) for laying the ground work. Thank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2). # toidentifier [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][github-actions-ci-image]][github-actions-ci-url] [![Test Coverage][codecov-image]][codecov-url] > Convert a string of words to a JavaScript identifier ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install toidentifier ``` ## Example ```js var toIdentifier = require('toidentifier') console.log(toIdentifier('Bad Request')) // => "BadRequest" ``` ## API This CommonJS module exports a single default function: `toIdentifier`. ### toIdentifier(string) Given a string as the argument, it will be transformed according to the following rules and the new string will be returned: 1. Split into words separated by space characters (`0x20`). 2. Upper case the first character of each word. 3. Join the words together with no separator. 4. Remove all non-word (`[0-9a-z_]`) characters. ## License [MIT](LICENSE) [codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg [codecov-url]: https://codecov.io/gh/component/toidentifier [downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg [downloads-url]: https://npmjs.org/package/toidentifier [github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci [github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci [npm-image]: https://img.shields.io/npm/v/toidentifier.svg [npm-url]: https://npmjs.org/package/toidentifier ## [npm]: https://www.npmjs.com/ [yarn]: https://yarnpkg.com/ # lodash v4.17.21 The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. ## Installation Using npm: ```shell $ npm i -g npm $ npm i --save lodash ``` In Node.js: ```js // Load the full build. var _ = require('lodash'); // Load the core build. var _ = require('lodash/core'); // Load the FP build for immutable auto-curried iteratee-first data-last methods. var fp = require('lodash/fp'); // Load method categories. var array = require('lodash/array'); var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles. var at = require('lodash/at'); var curryN = require('lodash/fp/curryN'); ``` See the [package source](https://github.com/lodash/lodash/tree/4.17.21-npm) for more details. **Note:**<br> Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. ## Support Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.<br> Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. # jest-mock ## API ```js import {ModuleMocker} from 'jest-mock'; ``` ### `constructor(global)` Creates a new module mocker that generates mocks as if they were created in an environment with the given global object. ### `generateFromMetadata(metadata)` Generates a mock based on the given metadata (Metadata for the mock in the schema returned by the getMetadata method of this module). Mocks treat functions specially, and all mock functions have additional members, described in the documentation for `fn` in this module. One important note: function prototypes are handled specially by this mocking framework. For functions with prototypes, when called as a constructor, the mock will install mocked function members on the instance. This allows different instances of the same constructor to have different values for its mocks member and its return values. ### `getMetadata(component)` Inspects the argument and returns its schema in the following recursive format: ``` { type: ... members: {} } ``` Where type is one of `array`, `object`, `function`, or `ref`, and members is an optional dictionary where the keys are member names and the values are metadata objects. Function prototypes are defined by defining metadata for the `member.prototype` of the function. The type of a function prototype should always be `object`. For instance, a class might be defined like this: ```js const classDef = { type: 'function', members: { staticMethod: {type: 'function'}, prototype: { type: 'object', members: { instanceMethod: {type: 'function'}, }, }, }, }; ``` Metadata may also contain references to other objects defined within the same metadata object. The metadata for the referent must be marked with `refID` key and an arbitrary value. The referrer must be marked with a `ref` key that has the same value as object with refID that it refers to. For instance, this metadata blob: ```js const refID = { type: 'object', refID: 1, members: { self: {ref: 1}, }, }; ``` defines an object with a slot named `self` that refers back to the object. ### `fn` Generates a stand-alone function with members that help drive unit tests or confirm expectations. Specifically, functions returned by this method have the following members: ##### `.mock` An object with three members, `calls`, `instances` and `invocationCallOrder`, which are all lists. The items in the `calls` list are the arguments with which the function was called. The "instances" list stores the value of 'this' for each call to the function. This is useful for retrieving instances from a constructor. The `invocationCallOrder` lists the order in which the mock was called in relation to all mock calls, starting at 1. ##### `.mockReturnValueOnce(value)` Pushes the given value onto a FIFO queue of return values for the function. ##### `.mockReturnValue(value)` Sets the default return value for the function. ##### `.mockImplementationOnce(function)` Pushes the given mock implementation onto a FIFO queue of mock implementations for the function. ##### `.mockImplementation(function)` Sets the default mock implementation for the function. ##### `.mockReturnThis()` Syntactic sugar for .mockImplementation(function() {return this;}) In case both `mockImplementationOnce()/mockImplementation()` and `mockReturnValueOnce()/mockReturnValue()` are called. The priority of which to use is based on what is the last call: - if the last call is mockReturnValueOnce() or mockReturnValue(), use the specific return value or default return value. If specific return values are used up or no default return value is set, fall back to try mockImplementation(); - if the last call is mockImplementationOnce() or mockImplementation(), run the specific implementation and return the result or run default implementation and return the result. # prebuild-install > **A command line tool to easily install prebuilt binaries for multiple versions of Node.js & Electron on a specific platform.** > By default it downloads prebuilt binaries from a GitHub release. [![npm](https://img.shields.io/npm/v/prebuild-install.svg)](https://www.npmjs.com/package/prebuild-install) ![Node version](https://img.shields.io/node/v/prebuild-install.svg) [![Test](https://img.shields.io/github/workflow/status/prebuild/prebuild-install/Test?label=test)](https://github.com/prebuild/prebuild-install/actions/workflows/test.yml) [![Standard](https://img.shields.io/badge/standard-informational?logo=javascript\&logoColor=fff)](https://standardjs.com) [![Common Changelog](https://common-changelog.org/badge.svg)](https://common-changelog.org) ## Note **Instead of [`prebuild`](https://github.com/prebuild/prebuild) paired with [`prebuild-install`](https://github.com/prebuild/prebuild-install), we recommend [`prebuildify`](https://github.com/prebuild/prebuildify) paired with [`node-gyp-build`](https://github.com/prebuild/node-gyp-build).** With `prebuildify`, all prebuilt binaries are shipped inside the package that is published to npm, which means there's no need for a separate download step like you find in `prebuild`. The irony of this approach is that it is faster to download all prebuilt binaries for every platform when they are bundled than it is to download a single prebuilt binary as an install script. Upsides: 1. No extra download step, making it more reliable and faster to install. 2. Supports changing runtime versions locally and using the same install between Node.js and Electron. Reinstalling or rebuilding is not necessary, as all prebuilt binaries are in the npm tarball and the correct one is simply picked on runtime. 3. The `node-gyp-build` runtime dependency is dependency-free and will remain so out of principle, because introducing dependencies would negate the shorter install time. 4. Prebuilt binaries work even if npm install scripts are disabled. 5. The npm package checksum covers prebuilt binaries too. Downsides: 1. The installed npm package is larger on disk. Using [Node-API](https://nodejs.org/api/n-api.html) alleviates this because Node-API binaries are runtime-agnostic and forward-compatible. 2. Publishing is mildly more complicated, because `npm publish` must be done after compiling and fetching prebuilt binaries (typically in CI). ## Usage Use [`prebuild`](https://github.com/prebuild/prebuild) to create and upload prebuilt binaries. Then change your package.json install script to: ```json { "scripts": { "install": "prebuild-install || node-gyp rebuild" } } ``` When a consumer then installs your package with npm thus triggering the above install script, `prebuild-install` will download a suitable prebuilt binary, or exit with a non-zero exit code if there is none, which triggers `node-gyp rebuild` in order to build from source. Options (see below) can be passed to `prebuild-install` like so: ```json { "scripts": { "install": "prebuild-install -r napi || node-gyp rebuild" } } ``` ### Help ``` prebuild-install [options] --download -d [url] (download prebuilds, no url means github) --target -t version (version to install for) --runtime -r runtime (Node runtime [node, napi or electron] to build or install for, default is node) --path -p path (make a prebuild-install here) --token -T gh-token (github token for private repos) --arch arch (target CPU architecture, see Node OS module docs, default is current arch) --platform platform (target platform, see Node OS module docs, default is current platform) --tag-prefix <prefix> (github tag prefix, default is "v") --build-from-source (skip prebuild download) --verbose (log verbosely) --libc (use provided libc rather than system default) --debug (set Debug or Release configuration) --version (print prebuild-install version and exit) ``` When `prebuild-install` is run via an `npm` script, options `--build-from-source`, `--debug`, `--download`, `--target`, `--runtime`, `--arch` `--platform` and `--libc` may be passed through via arguments given to the `npm` command. Alternatively you can set environment variables `npm_config_build_from_source=true`, `npm_config_platform`, `npm_config_arch`, `npm_config_target` `npm_config_runtime` and `npm_config_libc`. ### Libc On non-glibc Linux platforms, the Libc name is appended to platform name. For example, musl-based environments are called `linuxmusl`. If `--libc=glibc` is passed as option, glibc is discarded and platform is called as just `linux`. This can be used for example to build cross-platform packages on Alpine Linux. ### Private Repositories `prebuild-install` supports downloading prebuilds from private GitHub repositories using the `-T <github-token>`: ``` $ prebuild-install -T <github-token> ``` If you don't want to use the token on cli you can put it in `~/.prebuild-installrc`: ``` token=<github-token> ``` Alternatively you can specify it in the `prebuild-install_token` environment variable. Note that using a GitHub token uses the API to resolve the correct release meaning that you are subject to the ([GitHub Rate Limit](https://developer.github.com/v3/rate_limit/)). ### Create GitHub Token To create a token: - Go to [this page](https://github.com/settings/tokens) - Click the `Generate new token` button - Give the token a name and click the `Generate token` button, see below ![prebuild-token](https://cloud.githubusercontent.com/assets/13285808/20844584/d0b85268-b8c0-11e6-8b08-2b19522165a9.png) The default scopes should be fine. ### Custom binaries The end user can override binary download location through environment variables in their .npmrc file. The variable needs to meet the mask `% your package name %_binary_host` or `% your package name %_binary_host_mirror`. For example: ``` leveldown_binary_host=http://overriden-host.com/overriden-path ``` Note that the package version subpath and file name will still be appended. So if you are installing `[email protected]` the resulting url will be: ``` http://overriden-host.com/overriden-path/v1.2.3/leveldown-v1.2.3-node-v57-win32-x64.tar.gz ``` #### Local prebuilds If you want to use prebuilds from your local filesystem, you can use the `% your package name %_local_prebuilds` .npmrc variable to set a path to the folder containing prebuilds. For example: ``` leveldown_local_prebuilds=/path/to/prebuilds ``` This option will look directly in that folder for bundles created with `prebuild`, for example: ``` /path/to/prebuilds/leveldown-v1.2.3-node-v57-win32-x64.tar.gz ``` Non-absolute paths resolve relative to the directory of the package invoking prebuild-install, e.g. for nested dependencies. ### Cache All prebuilt binaries are cached to minimize traffic. So first `prebuild-install` picks binaries from the cache and if no binary could be found, it will be downloaded. Depending on the environment, the cache folder is determined in the following order: - `${npm_config_cache}/_prebuilds` - `${APP_DATA}/npm-cache/_prebuilds` - `${HOME}/.npm/_prebuilds` ## Install With [npm](https://npmjs.org) do: ``` npm install prebuild-install ``` ## License [MIT](./LICENSE) # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # minimist <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![github actions][actions-image]][actions-url] [![coverage][codecov-image]][codecov-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] parse argument options This module is the guts of optimist's argument parser without all the fanciful decoration. # example ``` js var argv = require('minimist')(process.argv.slice(2)); console.log(argv); ``` ``` $ node example/parse.js -a beep -b boop { _: [], a: 'beep', b: 'boop' } ``` ``` $ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz { _: [ 'foo', 'bar', 'baz' ], x: 3, y: 4, n: 5, a: true, b: true, c: true, beep: 'boop' } ``` # security Previous versions had a prototype pollution bug that could cause privilege escalation in some circumstances when handling untrusted user input. Please use version 1.2.6 or later: * https://security.snyk.io/vuln/SNYK-JS-MINIMIST-2429795 (version <=1.2.5) * https://snyk.io/vuln/SNYK-JS-MINIMIST-559764 (version <=1.2.3) # methods ``` js var parseArgs = require('minimist') ``` ## var argv = parseArgs(args, opts={}) Return an argument object `argv` populated with the array arguments from `args`. `argv._` contains all the arguments that didn't have an option associated with them. Numeric-looking arguments will be returned as numbers unless `opts.string` or `opts.boolean` is set for that argument name. Any arguments after `'--'` will not be parsed and will end up in `argv._`. options can be: * `opts.string` - a string or array of strings argument names to always treat as strings * `opts.boolean` - a boolean, string or array of strings to always treat as booleans. if `true` will treat all double hyphenated arguments without equal signs as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`) * `opts.alias` - an object mapping string names to strings or arrays of string argument names to use as aliases * `opts.default` - an object mapping string argument names to default values * `opts.stopEarly` - when true, populate `argv._` with everything after the first non-option * `opts['--']` - when true, populate `argv._` with everything before the `--` and `argv['--']` with everything after the `--`. Here's an example: ``` > require('./')('one two three -- four five --six'.split(' '), { '--': true }) { _: [ 'one', 'two', 'three' ], '--': [ 'four', 'five', '--six' ] } ``` Note that with `opts['--']` set, parsing for arguments still stops after the `--`. * `opts.unknown` - a function which is invoked with a command line parameter not defined in the `opts` configuration object. If the function returns `false`, the unknown option is not added to `argv`. # install With [npm](https://npmjs.org) do: ``` npm install minimist ``` # license MIT [package-url]: https://npmjs.org/package/minimist [npm-version-svg]: https://versionbadg.es/minimistjs/minimist.svg [npm-badge-png]: https://nodei.co/npm/minimist.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/minimist.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/minimist.svg [downloads-url]: https://npm-stat.com/charts.html?package=minimist [codecov-image]: https://codecov.io/gh/minimistjs/minimist/branch/main/graphs/badge.svg [codecov-url]: https://app.codecov.io/gh/minimistjs/minimist/ [actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/minimistjs/minimist [actions-url]: https://github.com/minimistjs/minimist/actions # axios-retry [![Build Status](https://travis-ci.org/softonic/axios-retry.svg?branch=master)](https://travis-ci.org/softonic/axios-retry) Axios plugin that intercepts failed requests and retries them whenever possible. ## Installation ```bash npm install axios-retry ``` ### Note Not working with `axios 0.19.0`. For details see the [bug](https://github.com/axios/axios/issues/2203). [`axios 0.19.1`](https://github.com/axios/axios/releases/tag/0.19.1) has fixed this bug. ## Usage ```js // CommonJS // const axiosRetry = require('axios-retry'); // ES6 import axiosRetry from 'axios-retry'; axiosRetry(axios, { retries: 3 }); axios.get('http://example.com/test') // The first request fails and the second returns 'ok' .then(result => { result.data; // 'ok' }); // Exponential back-off retry delay between requests axiosRetry(axios, { retryDelay: axiosRetry.exponentialDelay}); // Custom retry delay axiosRetry(axios, { retryDelay: (retryCount) => { return retryCount * 1000; }}); // Works with custom axios instances const client = axios.create({ baseURL: 'http://example.com' }); axiosRetry(client, { retries: 3 }); client.get('/test') // The first request fails and the second returns 'ok' .then(result => { result.data; // 'ok' }); // Allows request-specific configuration client .get('/test', { 'axios-retry': { retries: 0 } }) .catch(error => { // The first request fails error !== undefined }); ``` **Note:** Unless `shouldResetTimeout` is set, the plugin interprets the request timeout as a global value, so it is not used for each retry but for the whole request lifecycle. ## Options | Name | Type | Default | Description | | --- | --- | --- | --- | | retries | `Number` | `3` | The number of times to retry before failing. | | retryCondition | `Function` | `isNetworkOrIdempotentRequestError` | A callback to further control if a request should be retried. By default, it retries if it is a network error or a 5xx error on an idempotent request (GET, HEAD, OPTIONS, PUT or DELETE). | | shouldResetTimeout | `Boolean` | false | Defines if the timeout should be reset between retries | | retryDelay | `Function` | `function noDelay() { return 0; }` | A callback to further control the delay in milliseconds between retried requests. By default there is no delay between retries. Another option is exponentialDelay ([Exponential Backoff](https://developers.google.com/analytics/devguides/reporting/core/v3/errors#backoff)). The function is passed `retryCount` and `error`. | ## Testing Clone the repository and execute: ```bash npm test ``` ## Contribute 1. Fork it: `git clone https://github.com/softonic/axios-retry.git` 2. Create your feature branch: `git checkout -b feature/my-new-feature` 3. Commit your changes: `git commit -am 'Added some feature'` 4. Check the build: `npm run build` 4. Push to the branch: `git push origin my-new-feature` 5. Submit a pull request :D <h1 align="center">Picomatch</h1> <p align="center"> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/v/picomatch.svg" alt="version"> </a> <a href="https://github.com/micromatch/picomatch/actions?workflow=Tests"> <img src="https://github.com/micromatch/picomatch/workflows/Tests/badge.svg" alt="test status"> </a> <a href="https://coveralls.io/github/micromatch/picomatch"> <img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status"> </a> <a href="https://npmjs.org/package/picomatch"> <img src="https://img.shields.io/npm/dm/picomatch.svg" alt="downloads"> </a> </p> <br> <br> <p align="center"> <strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br> <em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em> </p> <br> <br> ## Why picomatch? * **Lightweight** - No dependencies * **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function. * **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps) * **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files) * **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes. * **Well tested** - Thousands of unit tests See the [library comparison](#library-comparisons) to other libraries. <br> <br> ## Table of Contents <details><summary> Click to expand </summary> - [Install](#install) - [Usage](#usage) - [API](#api) * [picomatch](#picomatch) * [.test](#test) * [.matchBase](#matchbase) * [.isMatch](#ismatch) * [.parse](#parse) * [.scan](#scan) * [.compileRe](#compilere) * [.makeRe](#makere) * [.toRegex](#toregex) - [Options](#options) * [Picomatch options](#picomatch-options) * [Scan Options](#scan-options) * [Options Examples](#options-examples) - [Globbing features](#globbing-features) * [Basic globbing](#basic-globbing) * [Advanced globbing](#advanced-globbing) * [Braces](#braces) * [Matching special characters as literals](#matching-special-characters-as-literals) - [Library Comparisons](#library-comparisons) - [Benchmarks](#benchmarks) - [Philosophies](#philosophies) - [About](#about) * [Author](#author) * [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ </details> <br> <br> ## Install Install with [npm](https://www.npmjs.com/): ```sh npm install --save picomatch ``` <br> ## Usage The main export is a function that takes a glob pattern and an options object and returns a function for matching strings. ```js const pm = require('picomatch'); const isMatch = pm('*.js'); console.log(isMatch('abcd')); //=> false console.log(isMatch('a.js')); //=> true console.log(isMatch('a.md')); //=> false console.log(isMatch('a/b.js')); //=> false ``` <br> ## API ### [picomatch](lib/picomatch.js#L32) Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information. **Params** * `globs` **{String|Array}**: One or more glob patterns. * `options` **{Object=}** * `returns` **{Function=}**: Returns a matcher function. **Example** ```js const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.test](lib/picomatch.js#L117) Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string. **Params** * `input` **{String}**: String to test. * `regex` **{RegExp}** * `returns` **{Object}**: Returns an object with matching info. **Example** ```js const picomatch = require('picomatch'); // picomatch.test(input, regex[, options]); console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` ### [.matchBase](lib/picomatch.js#L161) Match the basename of a filepath. **Params** * `input` **{String}**: String to test. * `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe). * `returns` **{Boolean}** **Example** ```js const picomatch = require('picomatch'); // picomatch.matchBase(input, glob[, options]); console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true ``` ### [.isMatch](lib/picomatch.js#L183) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * **{String|Array}**: str The string to test. * **{String|Array}**: patterns One or more glob patterns to use for matching. * **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const picomatch = require('picomatch'); // picomatch.isMatch(string, patterns[, options]); console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(picomatch.isMatch('a.a', 'b.*')); //=> false ``` ### [.parse](lib/picomatch.js#L199) Parse a glob pattern to create the source string for a regular expression. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string. **Example** ```js const picomatch = require('picomatch'); const result = picomatch.parse(pattern[, options]); ``` ### [.scan](lib/picomatch.js#L231) Scan a glob pattern to separate the pattern into segments. **Params** * `input` **{String}**: Glob pattern to scan. * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const picomatch = require('picomatch'); // picomatch.scan(input[, options]); const result = picomatch.scan('!./foo/*.js'); console.log(result); { prefix: '!./', input: '!./foo/*.js', start: 3, base: 'foo', glob: '*.js', isBrace: false, isBracket: false, isGlob: true, isExtglob: false, isGlobstar: false, negated: true } ``` ### [.compileRe](lib/picomatch.js#L245) Compile a regular expression from the `state` object returned by the [parse()](#parse) method. **Params** * `state` **{Object}** * `options` **{Object}** * `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser. * `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging. * `returns` **{RegExp}** ### [.makeRe](lib/picomatch.js#L286) Create a regular expression from a parsed glob pattern. **Params** * `state` **{String}**: The object returned from the `.parse` method. * `options` **{Object}** * `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result. * `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const picomatch = require('picomatch'); const state = picomatch.parse('*.js'); // picomatch.compileRe(state[, options]); console.log(picomatch.compileRe(state)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` ### [.toRegex](lib/picomatch.js#L321) Create a regular expression from the given regex source string. **Params** * `source` **{String}**: Regular expression source string. * `options` **{Object}** * `returns` **{RegExp}** **Example** ```js const picomatch = require('picomatch'); // picomatch.toRegex(source[, options]); const { output } = picomatch.parse('*.js'); console.log(picomatch.toRegex(output)); //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ ``` <br> ## Options ### Picomatch options The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. | | `failglob` | `boolean` | `false` | Throws an error if no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatibility. | picomatch has automatic detection for regex positive and negative lookbehinds. If the pattern contains a negative lookbehind, you must be using Node.js >= 8.10 or else picomatch will throw an error. ### Scan Options In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method. | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern | | `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true | **Example** ```js const picomatch = require('picomatch'); const result = picomatch.scan('!./foo/*.js', { tokens: true }); console.log(result); // { // prefix: '!./', // input: '!./foo/*.js', // start: 3, // base: 'foo', // glob: '*.js', // isBrace: false, // isBracket: false, // isGlob: true, // isExtglob: false, // isGlobstar: false, // negated: true, // maxDepth: 2, // tokens: [ // { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true }, // { value: 'foo', depth: 1, isGlob: false }, // { value: '*.js', depth: 1, isGlob: true } // ], // slashes: [ 2, 6 ], // parts: [ 'foo', '*.js' ] // } ``` <br> ### Options Examples #### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a folder ```js const fill = require('fill-range'); const regex = pm.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex); //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` #### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')); //=> true ``` #### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onMatch }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` #### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = picomatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` <br> <br> ## Globbing features * [Basic globbing](#basic-globbing) (Wildcard matching) * [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching) ### Basic globbing | **Character** | **Description** | | --- | --- | | `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. | | `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` on Windows) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. | | `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. | | `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. | #### Matching behavior vs. Bash Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions: * Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`. * Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`. <br> ### Advanced globbing * [extglobs](#extglobs) * [POSIX brackets](#posix-brackets) * [Braces](#brace-expansion) #### Extglobs | **Pattern** | **Description** | | --- | --- | | `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` | | `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` | | `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` | | `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` | | `!(pattern)` | Match _anything but_ `pattern` | **Examples** ```js const pm = require('picomatch'); // *(pattern) matches ZERO or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // +(pattern) matches ONE or more of "pattern" console.log(pm.isMatch('a', 'a*(z)')); // true console.log(pm.isMatch('az', 'a*(z)')); // true console.log(pm.isMatch('azzz', 'a*(z)')); // true // supports multiple extglobs console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false // supports nested extglobs console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true ``` #### POSIX brackets POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true. **Enable POSIX bracket support** ```js console.log(pm.makeRe('[[:word:]]+', { posix: true })); //=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/ ``` **Supported POSIX classes** The following named POSIX bracket expressions are supported: * `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]` * `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`. * `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`. * `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`. * `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`. * `[:digit:]` - Numerical digits, equivalent to `[0-9]`. * `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`. * `[:lower:]` - Lowercase letters, equivalent to `[a-z]`. * `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`. * `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`. * `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`. * `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`. * `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`. * `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`. See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information. ### Braces Picomatch does not do brace expansion. For [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) and advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch) instead. Picomatch has very basic support for braces. ### Matching special characters as literals If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes: **Special Characters** Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms. To match any of the following characters as literals: `$^*+?()[] Examples: ```js console.log(pm.makeRe('foo/bar \\(1\\)')); console.log(pm.makeRe('foo/bar \\(1\\)')); ``` <br> <br> ## Library Comparisons The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets). | **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` | | --- | --- | --- | --- | --- | --- | --- | --- | | Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - | | Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - | | Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - | | Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - | | Extglobs | partial | ✔ | ✔ | - | ✔ | - | - | | Posix brackets | - | ✔ | ✔ | - | - | - | ✔ | | Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ | | File system operations | - | - | - | - | - | - | - | <br> <br> ## Benchmarks Performance comparison of picomatch and minimatch. ``` # .makeRe star picomatch x 1,993,050 ops/sec ±0.51% (91 runs sampled) minimatch x 627,206 ops/sec ±1.96% (87 runs sampled)) # .makeRe star; dot=true picomatch x 1,436,640 ops/sec ±0.62% (91 runs sampled) minimatch x 525,876 ops/sec ±0.60% (88 runs sampled) # .makeRe globstar picomatch x 1,592,742 ops/sec ±0.42% (90 runs sampled) minimatch x 962,043 ops/sec ±1.76% (91 runs sampled)d) # .makeRe globstars picomatch x 1,615,199 ops/sec ±0.35% (94 runs sampled) minimatch x 477,179 ops/sec ±1.33% (91 runs sampled) # .makeRe with leading star picomatch x 1,220,856 ops/sec ±0.40% (92 runs sampled) minimatch x 453,564 ops/sec ±1.43% (94 runs sampled) # .makeRe - basic braces picomatch x 392,067 ops/sec ±0.70% (90 runs sampled) minimatch x 99,532 ops/sec ±2.03% (87 runs sampled)) ``` <br> <br> ## Philosophies The goal of this library is to be blazing fast, without compromising on accuracy. **Accuracy** The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`. Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements. **Performance** Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer. <br> <br> ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios) ![Build status](https://github.com/axios/axios/actions/workflows/ci.yml/badge.svg) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) [![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios) Promise based HTTP client for the browser and node.js > New axios docs website: [click here](https://axios-http.com/) ## Table of Contents - [Features](#features) - [Browser Support](#browser-support) - [Installing](#installing) - [Example](#example) - [Axios API](#axios-api) - [Request method aliases](#request-method-aliases) - [Concurrency 👎](#concurrency-deprecated) - [Creating an instance](#creating-an-instance) - [Instance methods](#instance-methods) - [Request Config](#request-config) - [Response Schema](#response-schema) - [Config Defaults](#config-defaults) - [Global axios defaults](#global-axios-defaults) - [Custom instance defaults](#custom-instance-defaults) - [Config order of precedence](#config-order-of-precedence) - [Interceptors](#interceptors) - [Multiple Interceptors](#multiple-interceptors) - [Handling Errors](#handling-errors) - [Cancellation](#cancellation) - [AbortController](#abortcontroller) - [CancelToken 👎](#canceltoken-deprecated) - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) - [Browser](#browser) - [Node.js](#nodejs) - [Query string](#query-string) - [Form data](#form-data) - [Automatic serialization](#-automatic-serialization) - [Manual FormData passing](#manual-formdata-passing) - [Semver](#semver) - [Promises](#promises) - [TypeScript](#typescript) - [Resources](#resources) - [Credits](#credits) - [License](#license) ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using jsDelivr CDN: ```html <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> ``` Using unpkg CDN: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios').default; // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } Promise.all([getUserAccount(), getUserPermissions()]) .then(function (results) { const acct = results[0]; const perm = results[1]; }); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience, aliases have been provided for all common request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency (Deprecated) Please use `Promise.all` to replace the below functions. Helper functions for dealing with concurrent requests. axios.all(iterable) axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads // browser only onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads // browser only onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js maxContentLength: 2000, // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed maxBodyLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 21, // default // `beforeRedirect` defines a function that will be called before redirect. // Use this to adjust the request options upon redirecting, // to inspect the latest response headers, // or to cancel the request by throwing an error // If maxRedirects is set to 0, `beforeRedirect` is not used. beforeRedirect: (options, { headers }) => { if (options.hostname === "example.com") { options.auth = "user:password"; } }; // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // `proxy` defines the hostname, port, and protocol of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. // If the proxy server uses HTTPS, then you must set the protocol to `https`. proxy: { protocol: 'https', host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }), // an alternative way to cancel Axios requests using AbortController signal: new AbortController().signal, // `decompress` indicates whether or not the response body should be decompressed // automatically. If set to `true` will also remove the 'content-encoding' header // from the responses objects of all decompressed responses // - Node only (XHR cannot turn off decompression) decompress: true // default // `insecureHTTPParser` boolean. // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. // This may allow interoperability with non-conformant HTTP implementations. // Using the insecure parser should be avoided. // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none insecureHTTPParser: undefined // default // transitional options for backward compatibility that may be removed in the newer versions transitional: { // silent JSON parsing mode // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') silentJSONParsing: true, // default value for the current Axios version // try to parse the response string as JSON even if `responseType` is not 'json' forcedJSONParsing: true, // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts clarifyTimeoutError: false, }, env: { // The FormData class to be used to automatically serialize the payload into a FormData object FormData: window?.FormData || global?.FormData } } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; // Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. // See below for an example using Custom instance defaults instead. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay in the execution of your axios request when the main thread is blocked (a promise is created under the hood for the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. ```js axios.interceptors.request.use(function (config) { config.headers.test = 'I am only a header!'; return config; }, null, { synchronous: true }); ``` If you want to execute a particular interceptor based on a runtime check, you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return of `runWhen` is `false`. The function will be called with the config object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an asynchronous request interceptor that only needs to run at certain times. ```js function onGetCall(config) { return config.method === 'get'; } axios.interceptors.request.use(function (config) { config.headers.test = 'special get headers'; return config; }, null, { runWhen: onGetCall }); ``` ### Multiple Interceptors Given you add multiple response interceptors and when the response was fulfilled - then each interceptor is executed - then they are executed in the order they were added - then only the last interceptor's result is returned - then every interceptor receives the result of it's predecessor - and when the fulfillment-interceptor throws - then the following fulfillment-interceptor is not called - then the following rejection-interceptor is called - once caught, another following fulfill-interceptor is called again (just like in a promise chain). Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code. ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation ### AbortController Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way: ```js const controller = new AbortController(); axios.get('/foo/bar', { signal: controller.signal }).then(function(response) { //... }); // cancel the request controller.abort() ``` ### CancelToken `👎deprecated` You can also cancel a request using a *CancelToken*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). > This API is deprecated since v0.22.0 and shouldn't be used in new projects You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token/abort controller. > If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request. > During the transition period, you can use both cancellation APIs, even for the same request: ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js #### Query string In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows: ```js const url = require('url'); const params = new url.URLSearchParams({ foo: 'bar' }); axios.post('http://something.com/', params.toString()); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. > NOTE: > The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case. #### Form data ##### 🆕 Automatic serialization Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type` header is set to `multipart/form-data`. The following request will submit the data in a FormData format (Browser & Node.js): ```js import axios from 'axios'; axios.post('https://httpbin.org/post', {x: 1}, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default. You can overload the FormData class by setting the `env.FormData` config variable, but you probably won't need it in most cases: ```js const axios= require('axios'); var FormData = require('form-data'); axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios FormData serializer supports some special endings to perform the following operations: - `{}` - serialize the value with JSON.stringify - `[]` - unwrap the array like object as separate fields with the same key ```js const axios= require('axios'); axios.post('https://httpbin.org/post', { 'myObj{}': {x: 1, s: "foo"}, 'files[]': document.querySelector('#fileInput').files }, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` which are just the corresponding http methods with a header preset: `Content-Type`: `multipart/form-data`. FileList object can be passed directly: ```js await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) ``` All files will be sent with the same field names: `files[]`; ##### Manual FormData passing In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows: ```js const FormData = require('form-data'); const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); axios.post('https://example.com', form) ``` ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors. ```typescript let user: User = null; try { const { data } = await axios.get('/user?ID=12345'); user = data.userDetails; } catch (error) { if (axios.isAxiosError(error)) { handleAxiosError(error); } else { handleUnexpectedError(error); } } ``` ## Online one-click setup You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js) ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS. ## License [MIT](LICENSE) [![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc). # clone-response > Clone a Node.js HTTP response stream [![Build Status](https://travis-ci.org/lukechilds/clone-response.svg?branch=master)](https://travis-ci.org/lukechilds/clone-response) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/clone-response/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/clone-response?branch=master) [![npm](https://img.shields.io/npm/dm/clone-response.svg)](https://www.npmjs.com/package/clone-response) [![npm](https://img.shields.io/npm/v/clone-response.svg)](https://www.npmjs.com/package/clone-response) Returns a new stream and copies over all properties and methods from the original response giving you a complete duplicate. This is useful in situations where you need to consume the response stream but also want to pass an unconsumed stream somewhere else to be consumed later. ## Install ```shell npm install --save clone-response ``` ## Usage ```js const http = require('http'); const cloneResponse = require('clone-response'); http.get('http://example.com', response => { const clonedResponse = cloneResponse(response); response.pipe(process.stdout); setImmediate(() => { // The response stream has already been consumed by the time this executes, // however the cloned response stream is still available. doSomethingWithResponse(clonedResponse); }); }); ``` Please bear in mind that the process of cloning a stream consumes it. However, you can consume a stream multiple times in the same tick, therefore allowing you to create multiple clones. e.g: ```js const clone1 = cloneResponse(response); const clone2 = cloneResponse(response); // response can still be consumed in this tick but cannot be consumed if passed // into any async callbacks. clone1 and clone2 can be passed around and be // consumed in the future. ``` ## API ### cloneResponse(response) Returns a clone of the passed in response. #### response Type: `stream` A [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) to clone. ## License MIT © Luke Childs aproba ====== A ridiculously light-weight function argument validator ``` var validate = require("aproba") function myfunc(a, b, c) { // `a` must be a string, `b` a number, `c` a function validate('SNF', arguments) // [a,b,c] is also valid } myfunc('test', 23, function () {}) // ok myfunc(123, 23, function () {}) // type error myfunc('test', 23) // missing arg error myfunc('test', 23, function () {}, true) // too many args error ``` Valid types are: | type | description | :--: | :---------- | * | matches any type | A | `Array.isArray` OR an `arguments` object | S | typeof == string | N | typeof == number | F | typeof == function | O | typeof == object and not type A and not type E | B | typeof == boolean | E | `instanceof Error` OR `null` **(special: see below)** | Z | == `null` Validation failures throw one of three exception types, distinguished by a `code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`. If you pass in an invalid type then it will throw with a code of `EUNKNOWNTYPE`. If an **error** argument is found and is not null then the remaining arguments are optional. That is, if you say `ESO` then that's like using a non-magical `E` in: `E|ESO|ZSO`. ### But I have optional arguments?! You can provide more than one signature by separating them with pipes `|`. If any signature matches the arguments then they'll be considered valid. So for example, say you wanted to write a signature for `fs.createWriteStream`. The docs for it describe it thusly: ``` fs.createWriteStream(path[, options]) ``` This would be a signature of `SO|S`. That is, a string and and object, or just a string. Now, if you read the full `fs` docs, you'll see that actually path can ALSO be a buffer. And options can be a string, that is: ``` path <String> | <Buffer> options <String> | <Object> ``` To reproduce this you have to fully enumerate all of the possible combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The awkwardness is a feature: It reminds you of the complexity you're adding to your API when you do this sort of thing. ### Browser support This has no dependencies and should work in browsers, though you'll have noisier stack traces. ### Why this exists I wanted a very simple argument validator. It needed to do two things: 1. Be more concise and easier to use than assertions 2. Not encourage an infinite bikeshed of DSLs This is why types are specified by a single character and there's no such thing as an optional argument. This is not intended to validate user data. This is specifically about asserting the interface of your functions. If you need greater validation, I encourage you to write them by hand or look elsewhere. # rollup-plugin-sourcemaps [![npm](https://img.shields.io/npm/v/rollup-plugin-sourcemaps.svg)](https://www.npmjs.com/package/rollup-plugin-sourcemaps) [![Build Status](https://img.shields.io/travis/maxdavidson/rollup-plugin-sourcemaps/master.svg)](https://travis-ci.org/maxdavidson/rollup-plugin-sourcemaps) [![Coverage Status](https://img.shields.io/coveralls/maxdavidson/rollup-plugin-sourcemaps/master.svg)](https://coveralls.io/github/maxdavidson/rollup-plugin-sourcemaps?branch=master) [Rollup](https://rollupjs.org) plugin for loading files with existing source maps. Inspired by [webpack/source-map-loader](https://github.com/webpack/source-map-loader). Works with rollup 0.31.2 or later. If you use [rollup-plugin-babel](https://github.com/rollup/rollup-plugin-babel), you might be able to use the [`inputSourceMap`](https://babeljs.io/docs/en/options#inputsourcemap) option instead of this plugin. ## Why? - You transpile your files with source maps before bundling with rollup - You consume external modules with bundled source maps ## Usage ```javascript import sourcemaps from 'rollup-plugin-sourcemaps'; export default { input: 'src/index.js', plugins: [sourcemaps()], output: { sourcemap: true, file: 'dist/my-awesome-package.js', }, }; ``` # merge2 Merge multiple streams into one stream in sequence or parallel. [![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Downloads][downloads-image]][downloads-url] ## Install Install with [npm](https://npmjs.org/package/merge2) ```sh npm install merge2 ``` ## Usage ```js const gulp = require('gulp') const merge2 = require('merge2') const concat = require('gulp-concat') const minifyHtml = require('gulp-minify-html') const ngtemplate = require('gulp-ngtemplate') gulp.task('app-js', function () { return merge2( gulp.src('static/src/tpl/*.html') .pipe(minifyHtml({empty: true})) .pipe(ngtemplate({ module: 'genTemplates', standalone: true }) ), gulp.src([ 'static/src/js/app.js', 'static/src/js/locale_zh-cn.js', 'static/src/js/router.js', 'static/src/js/tools.js', 'static/src/js/services.js', 'static/src/js/filters.js', 'static/src/js/directives.js', 'static/src/js/controllers.js' ]) ) .pipe(concat('app.js')) .pipe(gulp.dest('static/dist/js/')) }) ``` ```js const stream = merge2([stream1, stream2], stream3, {end: false}) //... stream.add(stream4, stream5) //.. stream.end() ``` ```js // equal to merge2([stream1, stream2], stream3) const stream = merge2() stream.add([stream1, stream2]) stream.add(stream3) ``` ```js // merge order: // 1. merge `stream1`; // 2. merge `stream2` and `stream3` in parallel after `stream1` merged; // 3. merge 'stream4' after `stream2` and `stream3` merged; const stream = merge2(stream1, [stream2, stream3], stream4) // merge order: // 1. merge `stream5` and `stream6` in parallel after `stream4` merged; // 2. merge 'stream7' after `stream5` and `stream6` merged; stream.add([stream5, stream6], stream7) ``` ```js // nest merge // equal to merge2(stream1, stream2, stream6, stream3, [stream4, stream5]); const streamA = merge2(stream1, stream2) const streamB = merge2(stream3, [stream4, stream5]) const stream = merge2(streamA, streamB) streamA.add(stream6) ``` ## API ```js const merge2 = require('merge2') ``` ### merge2() ### merge2(options) ### merge2(stream1, stream2, ..., streamN) ### merge2(stream1, stream2, ..., streamN, options) ### merge2(stream1, [stream2, stream3, ...], streamN, options) return a duplex stream (mergedStream). streams in array will be merged in parallel. ### mergedStream.add(stream) ### mergedStream.add(stream1, [stream2, stream3, ...], ...) return the mergedStream. ### mergedStream.on('queueDrain', function() {}) It will emit 'queueDrain' when all streams merged. If you set `end === false` in options, this event give you a notice that should add more streams to merge or end the mergedStream. #### stream *option* Type: `Readable` or `Duplex` or `Transform` stream. #### options *option* Type: `Object`. * **end** - `Boolean` - if `end === false` then mergedStream will not be auto ended, you should end by yourself. **Default:** `undefined` * **pipeError** - `Boolean` - if `pipeError === true` then mergedStream will emit `error` event from source streams. **Default:** `undefined` * **objectMode** - `Boolean` . **Default:** `true` `objectMode` and other options(`highWaterMark`, `defaultEncoding` ...) is same as Node.js `Stream`. ## License MIT © [Teambition](https://www.teambition.com) [npm-url]: https://npmjs.org/package/merge2 [npm-image]: http://img.shields.io/npm/v/merge2.svg [travis-url]: https://travis-ci.org/teambition/merge2 [travis-image]: http://img.shields.io/travis/teambition/merge2.svg [downloads-url]: https://npmjs.org/package/merge2 [downloads-image]: http://img.shields.io/npm/dm/merge2.svg?style=flat-square # libusb [![Build Status](https://travis-ci.org/libusb/libusb.svg?branch=master)](https://travis-ci.org/libusb/libusb) [![Build status](https://ci.appveyor.com/api/projects/status/xvrfam94jii4a6lw?svg=true)](https://ci.appveyor.com/project/LudovicRousseau/libusb) [![Coverity Scan Build Status](https://scan.coverity.com/projects/2180/badge.svg)](https://scan.coverity.com/projects/libusb-libusb) libusb is a library for USB device access from Linux, macOS, Windows, OpenBSD/NetBSD and Haiku userspace. It is written in C (Haiku backend in C++) and licensed under the GNU Lesser General Public License version 2.1 or, at your option, any later version (see [COPYING](COPYING)). libusb is abstracted internally in such a way that it can hopefully be ported to other operating systems. Please see the [PORTING](PORTING) file for more information. libusb homepage: http://libusb.info/ Developers will wish to consult the API documentation: http://api.libusb.info Use the mailing list for questions, comments, etc: http://mailing-list.libusb.info - Hans de Goede <[email protected]> - Xiaofan Chen <[email protected]> - Ludovic Rousseau <[email protected]> - Nathan Hjelm <[email protected]> - Chris Dickens <[email protected]> (Please use the mailing list rather than mailing developers directly) # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # common-path-prefix Computes the longest prefix string that is common to each path, excluding the base component. Tested with Node.js 8 and above. ## Installation ```console npm install common-path-prefix ``` ## Usage The module has one default export, the `commonPathPrefix` function: ```js const commonPathPrefix = require('common-path-prefix') ``` Call `commonPathPrefix()` with an array of paths (strings) and an optional separator character: ```js const paths = ['templates/main.handlebars', 'templates/_partial.handlebars'] commonPathPrefix(paths, '/') // returns 'templates/' ``` If the separator is not provided the first `/` or `\` found in any of the paths is used. Otherwise the platform-default value is used: ```js commonPathPrefix(['templates/main.handlebars', 'templates/_partial.handlebars']) // returns 'templates/' commonPathPrefix(['templates\\main.handlebars', 'templates\\_partial.handlebars']) // returns 'templates\\' ``` You can provide any separator, for example: ```js commonPathPrefix(['foo$bar', 'foo$baz'], '$') // returns 'foo$'' ``` An empty string is returned if no common prefix exists: ```js commonPathPrefix(['foo/bar', 'baz/qux']) // returns '' commonPathPrefix(['foo/bar']) // returns '' ``` Note that the following *does* have a common prefix: ```js commonPathPrefix(['/foo/bar', '/baz/qux']) // returns '/' ``` # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # is-typedarray [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) Detect whether or not an object is a [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). ## Usage [![NPM](https://nodei.co/npm/is-typedarray.png)](https://nodei.co/npm/is-typedarray/) ### isTypedArray(array) Returns `true` when array is a Typed Array, and `false` when it is not. ## License MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # v8flags [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Get available v8 and Node.js flags. ## Usage ```js const v8flags = require('v8flags'); v8flags(function(err, results) { console.log(results); // [ '--use_strict', // '--es5_readonly', // '--es52_globals', // '--harmony_typeof', // '--harmony_scoping', // '--harmony_modules', // '--harmony_proxies', // '--harmony_collections', // '--harmony', // ... }); ``` ## API ### `v8flags(cb)` Finds the available flags and calls the passed callback with any errors and an array of flag results. ### `v8flags.configfile` The name of the cache file for flags. ### `v8flags.configPath` The filepath location of the `configfile` above. ## License MIT [downloads-image]: http://img.shields.io/npm/dm/v8flags.svg [npm-url]: https://www.npmjs.com/package/v8flags [npm-image]: http://img.shields.io/npm/v/v8flags.svg [travis-url]: https://travis-ci.org/gulpjs/v8flags [travis-image]: http://img.shields.io/travis/gulpjs/v8flags.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/v8flags [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/v8flags.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/v8flags [coveralls-image]: http://img.shields.io/coveralls/gulpjs/v8flags/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg bs58 ==== [![build status](https://travis-ci.org/cryptocoinjs/bs58.svg)](https://travis-ci.org/cryptocoinjs/bs58) JavaScript component to compute base 58 encoding. This encoding is typically used for crypto currencies such as Bitcoin. **Note:** If you're looking for **base 58 check** encoding, see: [https://github.com/bitcoinjs/bs58check](https://github.com/bitcoinjs/bs58check), which depends upon this library. Install ------- npm i --save bs58 API --- ### encode(input) `input` must be a [Buffer](https://nodejs.org/api/buffer.html) or an `Array`. It returns a `string`. **example**: ```js const bs58 = require('bs58') const bytes = Buffer.from('003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187', 'hex') const address = bs58.encode(bytes) console.log(address) // => 16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS ``` ### decode(input) `input` must be a base 58 encoded string. Returns a [Buffer](https://nodejs.org/api/buffer.html). **example**: ```js const bs58 = require('bs58') const address = '16UjcYNBG9GTK4uq2f7yYEbuifqCzoLMGS' const bytes = bs58.decode(address) console.log(out.toString('hex')) // => 003c176e659bea0f29a3e9bf7880c112b1b31b4dc826268187 ``` Hack / Test ----------- Uses JavaScript standard style. Read more: [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Credits ------- - [Mike Hearn](https://github.com/mikehearn) for original Java implementation - [Stefan Thomas](https://github.com/justmoon) for porting to JavaScript - [Stephan Pair](https://github.com/gasteve) for buffer improvements - [Daniel Cousens](https://github.com/dcousens) for cleanup and merging improvements from bitcoinjs-lib - [Jared Deckard](https://github.com/deckar01) for killing `bigi` as a dependency License ------- MIT has-unicode =========== Try to guess if your terminal supports unicode ```javascript var hasUnicode = require("has-unicode") if (hasUnicode()) { // the terminal probably has unicode support } ``` ```javascript var hasUnicode = require("has-unicode").tryHarder hasUnicode(function(unicodeSupported) { if (unicodeSupported) { // the terminal probably has unicode support } }) ``` ## Detecting Unicode What we actually detect is UTF-8 support, as that's what Node itself supports. If you have a UTF-16 locale then you won't be detected as unicode capable. ### Windows Since at least Windows 7, `cmd` and `powershell` have been unicode capable, but unfortunately even then it's not guaranteed. In many localizations it still uses legacy code pages and there's no facility short of running programs or linking C++ that will let us detect this. As such, we report any Windows installation as NOT unicode capable, and recommend that you encourage your users to override this via config. ### Unix Like Operating Systems We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient for most POSIX systems. While locale data can be put in `/etc/locale.conf` as well, AFAIK it's always copied into the environment. # mime-db [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url] This is a large database of mime types and information about them. It consists of a single, public JSON file and does not include any logic, allowing it to remain as un-opinionated as possible with an API. It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation ```bash npm install mime-db ``` ### Database Download If you're crazy enough to use this in the browser, you can just grab the JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the JSON format may change in the future. ``` https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json ``` ## Usage ```js var db = require('mime-db') // grab data on .js files var data = db['application/javascript'] ``` ## Data Structure The JSON file is a map lookup for lowercased mime types. Each mime type has the following properties: - `.source` - where the mime type is defined. If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type can be gzipped. - `.charset` - the default charset associated with this type, if any. If unknown, every property could be `undefined`. ## Contributing To edit the database, only make PRs against `src/custom-types.json` or `src/custom-suffix.json`. The `src/custom-types.json` file is a JSON object with the MIME type as the keys and the values being an object with the following keys: - `compressible` - leave out if you don't know, otherwise `true`/`false` to indicate whether the data represented by the type is typically compressible. - `extensions` - include an array of file extensions that are associated with the type. - `notes` - human-readable notes about the type, typically what the type is. - `sources` - include an array of URLs of where the MIME type and the associated extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); links to type aggregating sites and Wikipedia are _not acceptable_. To update the build, run `npm run build`. ### Adding Custom Media Types The best way to get new media types included in this library is to register them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. If that is not possible / feasible, they can be added directly here as a "custom" type. To do this, it is required to have a primary source that definitively lists the media type. If an extension is going to be listed as associateed with this media type, the source must definitively link the media type and extension as well. [ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci [ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master [node-image]: https://badgen.net/npm/node/mime-db [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-db [npm-url]: https://npmjs.org/package/mime-db [npm-version-image]: https://badgen.net/npm/v/mime-db # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Requests sent via `adapters/` (see lib/adapters/README.md) - Managing interceptors - Handling config # detect-libc Node.js module to detect details of the C standard library (libc) implementation provided by a given Linux system. Currently supports detection of GNU glibc and MUSL libc. Provides asychronous and synchronous functions for the family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`). For previous v1.x releases, please see the [v1](https://github.com/lovell/detect-libc/tree/v1) branch. ## Install ```sh npm install detect-libc ``` ## API ### GLIBC ```ts const GLIBC: string = 'glibc'; ``` A String constant containing the value `glibc`. ### MUSL ```ts const MUSL: string = 'musl'; ``` A String constant containing the value `musl`. ### family ```ts function family(): Promise<string | null>; ``` Resolves asychronously with: * `glibc` or `musl` when the libc family can be determined * `null` when the libc family cannot be determined * `null` when run on a non-Linux platform ```js const { family, GLIBC, MUSL } = require('detect-libc'); switch (await family()) { case GLIBC: ... case MUSL: ... case null: ... } ``` ### familySync ```ts function familySync(): string | null; ``` Synchronous version of `family()`. ```js const { familySync, GLIBC, MUSL } = require('detect-libc'); switch (familySync()) { case GLIBC: ... case MUSL: ... case null: ... } ``` ### version ```ts function version(): Promise<string | null>; ``` Resolves asychronously with: * The version when it can be determined * `null` when the libc family cannot be determined * `null` when run on a non-Linux platform ```js const { version } = require('detect-libc'); const v = await version(); if (v) { const [major, minor, patch] = v.split('.'); } ``` ### versionSync ```ts function versionSync(): string | null; ``` Synchronous version of `version()`. ```js const { versionSync } = require('detect-libc'); const v = versionSync(); if (v) { const [major, minor, patch] = v.split('.'); } ``` ### isNonGlibcLinux ```ts function isNonGlibcLinux(): Promise<boolean>; ``` Resolves asychronously with: * `false` when the libc family is `glibc` * `true` when the libc family is not `glibc` * `false` when run on a non-Linux platform ```js const { isNonGlibcLinux } = require('detect-libc'); if (await isNonGlibcLinux()) { ... } ``` ### isNonGlibcLinuxSync ```ts function isNonGlibcLinuxSync(): boolean; ``` Synchronous version of `isNonGlibcLinux()`. ```js const { isNonGlibcLinuxSync } = require('detect-libc'); if (isNonGlibcLinuxSync()) { ... } ``` ## Licensing Copyright 2017, 2022 Lovell Fuller Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # toidentifier [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][github-actions-ci-image]][github-actions-ci-url] [![Test Coverage][codecov-image]][codecov-url] > Convert a string of words to a JavaScript identifier ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install toidentifier ``` ## Example ```js var toIdentifier = require('toidentifier') console.log(toIdentifier('Bad Request')) // => "BadRequest" ``` ## API This CommonJS module exports a single default function: `toIdentifier`. ### toIdentifier(string) Given a string as the argument, it will be transformed according to the following rules and the new string will be returned: 1. Split into words separated by space characters (`0x20`). 2. Upper case the first character of each word. 3. Join the words together with no separator. 4. Remove all non-word (`[0-9a-z_]`) characters. ## License [MIT](LICENSE) [codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg [codecov-url]: https://codecov.io/gh/component/toidentifier [downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg [downloads-url]: https://npmjs.org/package/toidentifier [github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci [github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci [npm-image]: https://img.shields.io/npm/v/toidentifier.svg [npm-url]: https://npmjs.org/package/toidentifier ## [npm]: https://www.npmjs.com/ [yarn]: https://yarnpkg.com/ # registry-auth-token [![npm version](http://img.shields.io/npm/v/registry-auth-token.svg?style=flat-square)](http://browsenpm.org/package/registry-auth-token)[![Build Status](http://img.shields.io/travis/rexxars/registry-auth-token/main.svg?style=flat-square)](https://travis-ci.org/rexxars/registry-auth-token) Get the auth token set for an npm registry from `.npmrc`. Also allows fetching the configured registry URL for a given npm scope. ## Installing ``` npm install --save registry-auth-token ``` ## Usage Returns an object containing `token` and `type`, or `undefined` if no token can be found. `type` can be either `Bearer` or `Basic`. ```js var getAuthToken = require('registry-auth-token') var getRegistryUrl = require('registry-auth-token/registry-url') // Get auth token and type for default `registry` set in `.npmrc` console.log(getAuthToken()) // {token: 'someToken', type: 'Bearer'} // Get auth token for a specific registry URL console.log(getAuthToken('//registry.foo.bar')) // Find the registry auth token for a given URL (with deep path): // If registry is at `//some.host/registry` // URL passed is `//some.host/registry/deep/path` // Will find token the closest matching path; `//some.host/registry` console.log(getAuthToken('//some.host/registry/deep/path', {recursive: true})) // Find the configured registry url for scope `@foobar`. // Falls back to the global registry if not defined. console.log(getRegistryUrl('@foobar')) // Use the npm config that is passed in console.log(getRegistryUrl('http://registry.foobar.eu/', { npmrc: { 'registry': 'http://registry.foobar.eu/', '//registry.foobar.eu/:_authToken': 'qar' } })) ``` ## Return value ```js // If auth info can be found: {token: 'someToken', type: 'Bearer'} // Or: {token: 'someOtherToken', type: 'Basic'} // Or, if nothing is found: undefined ``` ## Security Please be careful when using this. Leaking your auth token is dangerous. ## License MIT-licensed. See LICENSE. # lodash v4.17.21 The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. ## Installation Using npm: ```shell $ npm i -g npm $ npm i --save lodash ``` In Node.js: ```js // Load the full build. var _ = require('lodash'); // Load the core build. var _ = require('lodash/core'); // Load the FP build for immutable auto-curried iteratee-first data-last methods. var fp = require('lodash/fp'); // Load method categories. var array = require('lodash/array'); var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles. var at = require('lodash/at'); var curryN = require('lodash/fp/curryN'); ``` See the [package source](https://github.com/lodash/lodash/tree/4.17.21-npm) for more details. **Note:**<br> Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. ## Support Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.<br> Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. are-we-there-yet ---------------- Track complex hiearchies of asynchronous task completion statuses. This is intended to give you a way of recording and reporting the progress of the big recursive fan-out and gather type workflows that are so common in async. What you do with this completion data is up to you, but the most common use case is to feed it to one of the many progress bar modules. Most progress bar modules include a rudamentary version of this, but my needs were more complex. Usage ===== ```javascript var TrackerGroup = require("are-we-there-yet").TrackerGroup var top = new TrackerGroup("program") var single = top.newItem("one thing", 100) single.completeWork(20) console.log(top.completed()) // 0.2 fs.stat("file", function(er, stat) { if (er) throw er var stream = top.newStream("file", stat.size) console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete // and 50% * 20% == 10% fs.createReadStream("file").pipe(stream).on("data", function (chunk) { // do stuff with chunk }) top.on("change", function (name) { // called each time a chunk is read from "file" // top.completed() will start at 0.1 and fill up to 0.6 as the file is read }) }) ``` Shared Methods ============== * var completed = tracker.completed() Implemented in: `Tracker`, `TrackerGroup`, `TrackerStream` Returns the ratio of completed work to work to be done. Range of 0 to 1. * tracker.finish() Implemented in: `Tracker`, `TrackerGroup` Marks the tracker as completed. With a TrackerGroup this marks all of its components as completed. Marks all of the components of this tracker as finished, which in turn means that `tracker.completed()` for this will now be 1. This will result in one or more `change` events being emitted. Events ====== All tracker objects emit `change` events with the following arguments: ``` function (name, completed, tracker) ``` `name` is the name of the tracker that originally emitted the event, or if it didn't have one, the first containing tracker group that had one. `completed` is the percent complete (as returned by `tracker.completed()` method). `tracker` is the tracker object that you are listening for events on. TrackerGroup ============ * var tracker = new TrackerGroup(**name**) * **name** *(optional)* - The name of this tracker group, used in change notifications if the component updating didn't have a name. Defaults to undefined. Creates a new empty tracker aggregation group. These are trackers whose completion status is determined by the completion status of other trackers. * tracker.addUnit(**otherTracker**, **weight**) * **otherTracker** - Any of the other are-we-there-yet tracker objects * **weight** *(optional)* - The weight to give the tracker, defaults to 1. Adds the **otherTracker** to this aggregation group. The weight determines how long you expect this tracker to take to complete in proportion to other units. So for instance, if you add one tracker with a weight of 1 and another with a weight of 2, you're saying the second will take twice as long to complete as the first. As such, the first will account for 33% of the completion of this tracker and the second will account for the other 67%. Returns **otherTracker**. * var subGroup = tracker.newGroup(**name**, **weight**) The above is exactly equivalent to: ```javascript var subGroup = tracker.addUnit(new TrackerGroup(name), weight) ``` * var subItem = tracker.newItem(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subItem = tracker.addUnit(new Tracker(name, todo), weight) ``` * var subStream = tracker.newStream(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subStream = tracker.addUnit(new TrackerStream(name, todo), weight) ``` * console.log( tracker.debug() ) Returns a tree showing the completion of this tracker group and all of its children, including recursively entering all of the children. Tracker ======= * var tracker = new Tracker(**name**, **todo**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **todo** *(optional)* The amount of work todo (a number). Defaults to 0. Ordinarily these are constructed as a part of a tracker group (via `newItem`). * var completed = tracker.completed() Returns the ratio of completed work to work to be done. Range of 0 to 1. If total work to be done is 0 then it will return 0. * tracker.addWork(**todo**) * **todo** A number to add to the amount of work to be done. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. * tracker.completeWork(**completed**) * **completed** A number to add to the work complete Increase the amount of work complete, thus increasing the completion percentage. Will never increase the work completed past the amount of work todo. That is, percentages > 100% are not allowed. Triggers a `change` event. * tracker.finish() Marks this tracker as finished, tracker.completed() will now be 1. Triggers a `change` event. TrackerStream ============= * var tracker = new TrackerStream(**name**, **size**, **options**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **size** *(optional)* The number of bytes being sent through this stream. * **options** *(optional)* A hash of stream options The tracker stream object is a pass through stream that updates an internal tracker object each time a block passes through. It's intended to track downloads, file extraction and other related activities. You use it by piping your data source into it and then using it as your data source. If your data has a length attribute then that's used as the amount of work completed when the chunk is passed through. If it does not (eg, object streams) then each chunk counts as completing 1 unit of work, so your size should be the total number of objects being streamed. * tracker.addWork(**todo**) * **todo** Increase the expected overall size by **todo** bytes. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. # braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) > Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save braces ``` ## v3.0.0 Released!! See the [changelog](CHANGELOG.md) for details. ## Why use braces? Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters. * **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) * **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. * **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up. * **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written). * **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)). * [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']` * [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']` * [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']` * [Supports escaping](#escaping) - To prevent evaluation of special characters. ## Usage The main export is a function that takes one or more brace `patterns` and `options`. ```js const braces = require('braces'); // braces(patterns[, options]); console.log(braces(['{01..05}', '{a..e}'])); //=> ['(0[1-5])', '([a-e])'] console.log(braces(['{01..05}', '{a..e}'], { expand: true })); //=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e'] ``` ### Brace Expansion vs. Compilation By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching. **Compiled** ```js console.log(braces('a/{x,y,z}/b')); //=> ['a/(x|y|z)/b'] console.log(braces(['a/{01..20}/b', 'a/{1..5}/b'])); //=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ] ``` **Expanded** Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)): ```js console.log(braces('a/{x,y,z}/b', { expand: true })); //=> ['a/x/b', 'a/y/b', 'a/z/b'] console.log(braces.expand('{01..10}')); //=> ['01','02','03','04','05','06','07','08','09','10'] ``` ### Lists Expand lists (like Bash "sets"): ```js console.log(braces('a/{foo,bar,baz}/*.js')); //=> ['a/(foo|bar|baz)/*.js'] console.log(braces.expand('a/{foo,bar,baz}/*.js')); //=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] ``` ### Sequences Expand ranges of characters (like Bash "sequences"): ```js console.log(braces.expand('{1..3}')); // ['1', '2', '3'] console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b'] console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c'] console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c'] // supports zero-padded ranges console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b'] console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b'] ``` See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options. ### Steppped ranges Steps, or increments, may be used with ranges: ```js console.log(braces.expand('{2..10..2}')); //=> ['2', '4', '6', '8', '10'] console.log(braces('{2..10..2}')); //=> ['(2|4|6|8|10)'] ``` When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. ### Nesting Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. **"Expanded" braces** ```js console.log(braces.expand('a{b,c,/{x,y}}/e')); //=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] console.log(braces.expand('a/{x,{1..5},y}/c')); //=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] ``` **"Optimized" braces** ```js console.log(braces('a{b,c,/{x,y}}/e')); //=> ['a(b|c|/(x|y))/e'] console.log(braces('a/{x,{1..5},y}/c')); //=> ['a/(x|([1-5])|y)/c'] ``` ### Escaping **Escaping braces** A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: ```js console.log(braces.expand('a\\{d,c,b}e')); //=> ['a{d,c,b}e'] console.log(braces.expand('a{d,c,b\\}e')); //=> ['a{d,c,b}e'] ``` **Escaping commas** Commas inside braces may also be escaped: ```js console.log(braces.expand('a{b\\,c}d')); //=> ['a{b,c}d'] console.log(braces.expand('a{d\\,c,b}e')); //=> ['ad,ce', 'abe'] ``` **Single items** Following bash conventions, a brace pattern is also not expanded when it contains a single character: ```js console.log(braces.expand('a{b}c')); //=> ['a{b}c'] ``` ## Options ### options.maxLength **Type**: `Number` **Default**: `65,536` **Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. ```js console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error ``` ### options.expand **Type**: `Boolean` **Default**: `undefined` **Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing). ```js console.log(braces('a/{b,c}/d', { expand: true })); //=> [ 'a/b/d', 'a/c/d' ] ``` ### options.nodupes **Type**: `Boolean` **Default**: `undefined` **Description**: Remove duplicates from the returned array. ### options.rangeLimit **Type**: `Number` **Default**: `1000` **Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`. You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether. **Examples** ```js // pattern exceeds the "rangeLimit", so it's optimized automatically console.log(braces.expand('{1..1000}')); //=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] // pattern does not exceed "rangeLimit", so it's NOT optimized console.log(braces.expand('{1..100}')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] ``` ### options.transform **Type**: `Function` **Default**: `undefined` **Description**: Customize range expansion. **Example: Transforming non-numeric values** ```js const alpha = braces.expand('x/{a..e}/y', { transform(value, index) { // When non-numeric values are passed, "value" is a character code. return 'foo/' + String.fromCharCode(value) + '-' + index; } }); console.log(alpha); //=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ] ``` **Example: Transforming numeric values** ```js const numeric = braces.expand('{1..5}', { transform(value) { // when numeric values are passed, "value" is a number return 'foo/' + value * 2; } }); console.log(numeric); //=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ] ``` ### options.quantifiers **Type**: `Boolean` **Default**: `undefined` **Description**: 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. **Examples** ```js const braces = require('braces'); console.log(braces('a/b{1,3}/{x,y,z}')); //=> [ 'a/b(1|3)/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); //=> [ 'a/b{1,3}/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); //=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] ``` ### options.unescape **Type**: `Boolean` **Default**: `undefined` **Description**: Strip backslashes that were used for escaping from the result. ## What is "brace expansion"? Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). In addition to "expansion", braces are also used for matching. In other words: * [brace expansion](#brace-expansion) is for generating new lists * [brace matching](#brace-matching) is for filtering existing lists <details> <summary><strong>More about brace expansion</strong> (click to expand)</summary> There are two main types of brace expansion: 1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` 2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". Here are some example brace patterns to illustrate how they work: **Sets** ``` {a,b,c} => a b c {a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 ``` **Sequences** ``` {1..9} => 1 2 3 4 5 6 7 8 9 {4..-4} => 4 3 2 1 0 -1 -2 -3 -4 {1..20..3} => 1 4 7 10 13 16 19 {a..j} => a b c d e f g h i j {j..a} => j i h g f e d c b a {a..z..3} => a d g j m p s v y ``` **Combination** Sets and sequences can be mixed together or used along with any other strings. ``` {a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar ``` The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. ## Brace matching In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. For example, the pattern `foo/{1..3}/bar` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar ``` But not: ``` baz/1/qux baz/2/qux baz/3/qux ``` Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` ## Brace matching pitfalls Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. ### tldr **"brace bombs"** * brace expansion can eat up a huge amount of processing resources * as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially * users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. ### The solution Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. ### Geometric complexity At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: ``` {1,2}{3,4} => (2X2) => 13 14 23 24 {1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 ``` But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: ``` {1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 249 257 258 259 267 268 269 347 348 349 357 358 359 367 368 369 ``` Now, imagine how this complexity grows given that each element is a n-tuple: ``` {1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) {1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) ``` Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. **More information** Interested in learning more about brace expansion? * [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) * [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) * [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) </details> ## Performance Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. ### Better algorithms Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. **The proof is in the numbers** Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs)| N/A (freezes) | | `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | | `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | | `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | | `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | | `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | | `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | | `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | | `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | | `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | | `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | | `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | | `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | | `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | | `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | | `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | | `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | ### Faster algorithms When you need expansion, braces is still much faster. _(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ | **Pattern** | **braces** | **[minimatch][]** | | --- | --- | --- | | `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | | `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | | `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | | `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | | `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | | `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | | `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | | `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm benchmark ``` ### Latest results Braces is more accurate, without sacrificing performance. ```bash # range (expanded) braces x 29,040 ops/sec ±3.69% (91 runs sampled)) minimatch x 4,735 ops/sec ±1.28% (90 runs sampled) # range (optimized for regex) braces x 382,878 ops/sec ±0.56% (94 runs sampled) minimatch x 1,040 ops/sec ±0.44% (93 runs sampled) # nested ranges (expanded) braces x 19,744 ops/sec ±2.27% (92 runs sampled)) minimatch x 4,579 ops/sec ±0.50% (93 runs sampled) # nested ranges (optimized for regex) braces x 246,019 ops/sec ±2.02% (93 runs sampled) minimatch x 1,028 ops/sec ±0.39% (94 runs sampled) # set (expanded) braces x 138,641 ops/sec ±0.53% (95 runs sampled) minimatch x 219,582 ops/sec ±0.98% (94 runs sampled) # set (optimized for regex) braces x 388,408 ops/sec ±0.41% (95 runs sampled) minimatch x 44,724 ops/sec ±0.91% (89 runs sampled) # nested sets (expanded) braces x 84,966 ops/sec ±0.48% (94 runs sampled) minimatch x 140,720 ops/sec ±0.37% (95 runs sampled) # nested sets (optimized for regex) braces x 263,340 ops/sec ±2.06% (92 runs sampled) minimatch x 28,714 ops/sec ±0.40% (90 runs sampled) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 197 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | | 1 | [hemanth](https://github.com/hemanth) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ # is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) > Returns true if the value is a finite number. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-number ``` ## Why is this needed? In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: ```js console.log(+[]); //=> 0 console.log(+''); //=> 0 console.log(+' '); //=> 0 console.log(typeof NaN); //=> 'number' ``` This library offers a performant way to smooth out edge cases like these. ## Usage ```js const isNumber = require('is-number'); ``` See the [tests](./test.js) for more examples. ### true ```js isNumber(5e3); // true isNumber(0xff); // true isNumber(-1.1); // true isNumber(0); // true isNumber(1); // true isNumber(1.1); // true isNumber(10); // true isNumber(10.10); // true isNumber(100); // true isNumber('-1.1'); // true isNumber('0'); // true isNumber('012'); // true isNumber('0xff'); // true isNumber('1'); // true isNumber('1.1'); // true isNumber('10'); // true isNumber('10.10'); // true isNumber('100'); // true isNumber('5e3'); // true isNumber(parseInt('012')); // true isNumber(parseFloat('012')); // true ``` ### False Everything else is false, as you would expect: ```js isNumber(Infinity); // false isNumber(NaN); // false isNumber(null); // false isNumber(undefined); // false isNumber(''); // false isNumber(' '); // false isNumber('foo'); // false isNumber([1]); // false isNumber([]); // false isNumber(function () {}); // false isNumber({}); // false ``` ## Release history ### 7.0.0 * Refactor. Now uses `.isFinite` if it exists. * Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. ### 6.0.0 * Optimizations, thanks to @benaadams. ### 5.0.0 **Breaking changes** * removed support for `instanceof Number` and `instanceof String` ## Benchmarks As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. ``` # all v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) fastest is 'v7.0' # string v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) fastest is 'parseFloat,v7.0' # number v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) fastest is 'v6.0' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 49 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [charlike-old](https://github.com/charlike-old) | | 1 | [benaadams](https://github.com/benaadams) | | 1 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ # sha.js [![NPM Package](https://img.shields.io/npm/v/sha.js.svg?style=flat-square)](https://www.npmjs.org/package/sha.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/sha.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/sha.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/sha.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/sha.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `SHA` on pure JavaScript. ```js var shajs = require('sha.js') console.log(shajs('sha256').update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 console.log(new shajs.sha256().update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 var sha256stream = shajs('sha256') sha256stream.end('42') console.log(sha256stream.read().toString('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 ``` ## supported hashes `sha.js` currently implements: - SHA (SHA-0) -- **legacy, do not use in new systems** - SHA-1 -- **legacy, do not use in new systems** - SHA-224 - SHA-256 - SHA-384 - SHA-512 ## Not an actual stream Note, this doesn't actually implement a stream, but wrapping this in a stream is trivial. It does update incrementally, so you can hash things larger than RAM, as it uses a constant amount of memory (except when using base64 or utf8 encoding, see code comments). ## Acknowledgements This work is derived from Paul Johnston's [A JavaScript implementation of the Secure Hash Algorithm](http://pajhome.org.uk/crypt/md5/sha1.html). ## LICENSE [MIT](LICENSE) # is-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/is-buffer/master.svg [travis-url]: https://travis-ci.org/feross/is-buffer [npm-image]: https://img.shields.io/npm/v/is-buffer.svg [npm-url]: https://npmjs.org/package/is-buffer [downloads-image]: https://img.shields.io/npm/dm/is-buffer.svg [downloads-url]: https://npmjs.org/package/is-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Determine if an object is a [`Buffer`](http://nodejs.org/api/buffer.html) (including the [browserify Buffer](https://github.com/feross/buffer)) [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/is-buffer.svg [saucelabs-url]: https://saucelabs.com/u/is-buffer ## Why not use `Buffer.isBuffer`? This module lets you check if an object is a `Buffer` without using `Buffer.isBuffer` (which includes the whole [buffer](https://github.com/feross/buffer) module in [browserify](http://browserify.org/)). It's future-proof and works in node too! ## install ```bash npm install is-buffer ``` ## usage ```js var isBuffer = require('is-buffer') isBuffer(new Buffer(4)) // true isBuffer(undefined) // false isBuffer(null) // false isBuffer('') // false isBuffer(true) // false isBuffer(false) // false isBuffer(0) // false isBuffer(1) // false isBuffer(1.0) // false isBuffer('string') // false isBuffer({}) // false isBuffer(function foo () {}) // false ``` ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). # signal-exit [![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) [![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) [![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the process to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Update Browserslist DB <img width="120" height="120" alt="Browserslist logo by Anton Popov" src="https://browsersl.ist/logo.svg" align="right"> CLI tool to update `caniuse-lite` with browsers DB from [Browserslist](https://github.com/browserslist/browserslist/) config. Some queries like `last 2 version` or `>1%` depends on actual data from `caniuse-lite`. ```sh npx update-browserslist-db@latest ``` <a href="https://evilmartians.com/?utm_source=update-browserslist-db"> <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg" alt="Sponsored by Evil Martians" width="236" height="54"> </a> ## Docs Read **[full docs](https://github.com/browserslist/update-db#readme)** on GitHub. # napi-build-utils [![npm](https://img.shields.io/npm/v/napi-build-utils.svg)](https://www.npmjs.com/package/napi-build-utils) ![Node version](https://img.shields.io/node/v/prebuild.svg) [![Build Status](https://travis-ci.org/inspiredware/napi-build-utils.svg?branch=master)](https://travis-ci.org/inspiredware/napi-build-utils) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) A set of utilities to assist developers of tools that build [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. ## Background This module is targeted to developers creating tools that build N-API native add-ons. It implements a set of functions that aid in determining the N-API version supported by the currently running Node instance and the set of N-API versions against which the N-API native add-on is designed to be built. Other functions determine whether a particular N-API version can be built and can issue console warnings for unsupported N-API versions. Unlike the modules this code is designed to facilitate building, this module is written entirely in JavaScript. ## Quick start ```bash $ npm install napi-build-utils ``` The module exports a set of functions documented [here](./index.md). For example: ```javascript var napiBuildUtils = require('napi-build-utils'); var napiVersion = napiBuildUtils.getNapiVersion(); // N-API version supported by Node, or undefined. ``` ## Declaring supported N-API versions Native modules that are designed to work with [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) must explicitly declare the N-API version(s) against which they are coded to build. This is accomplished by including a `binary.napi_versions` property in the module's `package.json` file. For example: ```json "binary": { "napi_versions": [2,3] } ``` In the absence of a need to compile against a specific N-API version, the value `3` is a good choice as this is the N-API version that was supported when N-API left experimental status. Modules that are built against a specific N-API version will continue to operate indefinitely, even as later versions of N-API are introduced. ## Support If you run into problems or limitations, please file an issue and we'll take a look. Pull requests are also welcome. # micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Tests](https://github.com/micromatch/micromatch/actions/workflows/test.yml/badge.svg)](https://github.com/micromatch/micromatch/actions/workflows/test.yml) > Glob matching for javascript/node.js. A replacement and faster alternative to minimatch and multimatch. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> - [Install](#install) - [Quickstart](#quickstart) - [Why use micromatch?](#why-use-micromatch) * [Matching features](#matching-features) - [Switching to micromatch](#switching-to-micromatch) * [From minimatch](#from-minimatch) * [From multimatch](#from-multimatch) - [API](#api) - [Options](#options) - [Options Examples](#options-examples) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.expandRange](#optionsexpandrange) * [options.format](#optionsformat) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.noextglob](#optionsnoextglob) * [options.nonegate](#optionsnonegate) * [options.noglobstar](#optionsnoglobstar) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.onIgnore](#optionsonignore) * [options.onMatch](#optionsonmatch) * [options.onResult](#optionsonresult) * [options.posixSlashes](#optionsposixslashes) * [options.unescape](#optionsunescape) - [Extended globbing](#extended-globbing) * [Extglobs](#extglobs) * [Braces](#braces) * [Regex character classes](#regex-character-classes) * [Regex groups](#regex-groups) * [POSIX bracket expressions](#posix-bracket-expressions) - [Notes](#notes) * [Bash 4.3 parity](#bash-43-parity) * [Backslashes](#backslashes) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Latest results](#latest-results) - [Contributing](#contributing) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/) (requires [Node.js](https://nodejs.org/en/) >=8.6): ```sh $ npm install --save micromatch ``` ## Quickstart ```js const micromatch = require('micromatch'); // micromatch(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['f*', 'b*'])) //=> ['foo', 'bar', 'baz'] console.log(micromatch(['foo', 'bar', 'baz', 'qux'], ['*', '!b*'])) //=> ['foo', 'qux'] ``` Use [.isMatch()](#ismatch) to for boolean matching: ```js console.log(micromatch.isMatch('foo', 'f*')) //=> true console.log(micromatch.isMatch('foo', ['b*', 'f*'])) //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! <br> ## Why use micromatch? > micromatch is a [replacement](#switching-to-micromatch) for minimatch and multimatch * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) * More complete support for the Bash 4.3 specification than minimatch and multimatch. Micromatch passes _all of the spec tests_ from bash, including some that bash still fails. * **Fast & Performant** - Loads in about 5ms and performs [fast matches](#benchmarks). * **Glob matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories * **[Advanced globbing](#extended-globbing)** - Supports [extglobs](#extglobs), [braces](#braces-1), and [POSIX brackets](#posix-bracket-expressions), and support for escaping special characters with `\` or quotes. * **Accurate** - Covers more scenarios [than minimatch](https://github.com/yarnpkg/yarn/pull/3339) * **Well tested** - More than 5,000 [test assertions](./test) * **Windows support** - More reliable windows support than minimatch and multimatch. * **[Safe](https://github.com/micromatch/braces#braces-is-safe)** - Micromatch is not subject to DoS with brace patterns like minimatch and multimatch. ### Matching features * Support for multiple glob patterns (no need for wrappers like multimatch) * Wildcards (`**`, `*.js`) * Negation (`'!a/*.js'`, `'*!(b).js'`) * [extglobs](#extglobs) (`+(x|y)`, `!(a|b)`) * [POSIX character classes](#posix-bracket-expressions) (`[[:alpha:][:digit:]]`) * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) * regex character classes (`foo-[1-5].js`) * regex logical "or" (`foo/(abc|xyz).js`) You can mix and match these features to create whatever patterns you need! ## Switching to micromatch _(There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information.)_ ### From minimatch Use [micromatch.isMatch()](#ismatch) instead of `minimatch()`: ```js console.log(micromatch.isMatch('foo', 'b*')); //=> false ``` Use [micromatch.match()](#match) instead of `minimatch.match()`: ```js console.log(micromatch.match(['foo', 'bar'], 'b*')); //=> 'bar' ``` ### From multimatch Same signature: ```js console.log(micromatch(['foo', 'bar', 'baz'], ['f*', '*z'])); //=> ['foo', 'baz'] ``` ## API **Params** * `list` **{String|Array<string>}**: List of strings to match. * `patterns` **{String|Array<string>}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) * `returns` **{Array}**: Returns an array of matches **Example** ```js const mm = require('micromatch'); // mm(list, patterns[, options]); console.log(mm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.matcher](index.js#L104) Returns a 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. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}** * `returns` **{Function}**: Returns a matcher function. **Example** ```js const mm = require('micromatch'); // mm.matcher(pattern[, options]); const isMatch = mm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.isMatch](index.js#L123) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `[options]` **{Object}**: See available [options](#options). * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.isMatch(string, patterns[, options]); console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(mm.isMatch('a.a', 'b.*')); //=> false ``` ### [.not](index.js#L148) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js const mm = require('micromatch'); // mm.not(list, patterns[, options]); console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L188) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any of the patterns matches any part of `str`. **Example** ```js var mm = require('micromatch'); // mm.contains(string, pattern[, options]); console.log(mm.contains('aa/bb/cc', '*b')); //=> true console.log(mm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L230) 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. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js const mm = require('micromatch'); // mm.matchKeys(object, patterns[, options]); const obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(mm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.some](index.js#L259) Returns true if some of the strings in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any `patterns` matches any of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.some(list, patterns[, options]); console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L295) Returns true if every string in the given `list` matches any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if all `patterns` matches all of the strings in `list` **Example** ```js const mm = require('micromatch'); // mm.every(list, patterns[, options]); console.log(mm.every('foo.js', ['foo.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.all](index.js#L334) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js const mm = require('micromatch'); // mm.all(string, patterns[, options]); console.log(mm.all('foo.js', ['foo.js'])); // true console.log(mm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(mm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.capture](index.js#L361) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `glob` **{String}**: Glob pattern to use for matching. * `input` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array|null}**: Returns an array of captures if the input matches the glob pattern, otherwise `null`. **Example** ```js const mm = require('micromatch'); // mm.capture(pattern, string[, options]); console.log(mm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(mm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L387) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js const mm = require('micromatch'); // mm.makeRe(pattern[, options]); console.log(mm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.scan](index.js#L403) Scan a glob pattern to separate the pattern into segments. Used by the [split](#split) method. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with **Example** ```js const mm = require('micromatch'); const state = mm.scan(pattern[, options]); ``` ### [.parse](index.js#L419) Parse a glob pattern to create the source string for a regular expression. **Params** * `glob` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object with useful properties and output to be used as regex source string. **Example** ```js const mm = require('micromatch'); const state = mm.parse(pattern[, options]); ``` ### [.braces](index.js#L446) Process the given brace `pattern`. **Params** * `pattern` **{String}**: String with brace pattern to process. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * `returns` **{Array}** **Example** ```js const { braces } = require('micromatch'); console.log(braces('foo/{a,b,c}/bar')); //=> [ 'foo/(a|b|c)/bar' ] console.log(braces('foo/{a,b,c}/bar', { expand: true })); //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] ``` ## Options | **Option** | **Type** | **Default value** | **Description** | | --- | --- | --- | --- | | `basename` | `boolean` | `false` | If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. | | `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). | | `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. | | `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). | | `cwd` | `string` | `process.cwd()` | Current working directory. Used by `picomatch.split()` | | `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. | | `dot` | `boolean` | `false` | Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. | | `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. This option is overridden by the `expandBrace` option. | | `failglob` | `boolean` | `false` | Similar to the `failglob` behavior in Bash, throws an error when no matches are found. Based on the bash option of the same name. | | `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. | | `flags` | `boolean` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. | | [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. | | `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. | | `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. | | `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. | | `lookbehinds` | `boolean` | `true` | Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. | | `matchBase` | `boolean` | `false` | Alias for `basename` | | `maxLength` | `boolean` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. | | `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. | | `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. | | `nocase` | `boolean` | `false` | Perform case-insensitive matching. Equivalent to the regex `i` flag. Note that this option is ignored when the `flags` option is defined. | | `nodupes` | `boolean` | `true` | Deprecated, use `nounique` instead. This option will be removed in a future major release. By default duplicates are removed. Disable uniquification by setting this option to false. | | `noext` | `boolean` | `false` | Alias for `noextglob` | | `noextglob` | `boolean` | `false` | Disable support for matching with [extglobs](#extglobs) (like `+(a\|b)`) | | `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) | | `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` | | `noquantifiers` | `boolean` | `false` | Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. | | [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. | | [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. | | [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. | | `posix` | `boolean` | `false` | Support [POSIX character classes](#posix-bracket-expressions) ("posix brackets"). | | `posixSlashes` | `boolean` | `undefined` | Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself | | `prepend` | `string` | `undefined` | String to prepend to the generated regex used for matching. | | `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). | | `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. | | `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. | | `unescape` | `boolean` | `undefined` | Remove preceding backslashes from escaped glob characters before creating the regular expression to perform matches. | | `unixify` | `boolean` | `undefined` | Alias for `posixSlashes`, for backwards compatitibility. | ## Options Examples ### options.basename 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`. **Type**: `Boolean` **Default**: `false` **Example** ```js micromatch(['a/b.js', 'a/c.md'], '*.js'); //=> [] micromatch(['a/b.js', 'a/c.md'], '*.js', { basename: true }); //=> ['a/b.js'] ``` ### options.bash 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 any other star. **Type**: `Boolean` **Default**: `true` **Example** ```js const files = ['abc', 'ajz']; console.log(micromatch(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(micromatch(files, '[a-c]*', { bash: false })); ``` ### options.expandRange **Type**: `function` **Default**: `undefined` Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need. **Example** The following example shows how to create a glob that matches a numeric folder name between `01` and `25`, with leading zeros. ```js const fill = require('fill-range'); const regex = micromatch.makeRe('foo/{01..25}/bar', { expandRange(a, b) { return `(${fill(a, b, { toRegex: true })})`; } }); console.log(regex) //=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/ console.log(regex.test('foo/00/bar')) // false console.log(regex.test('foo/01/bar')) // true console.log(regex.test('foo/10/bar')) // true console.log(regex.test('foo/22/bar')) // true console.log(regex.test('foo/25/bar')) // true console.log(regex.test('foo/26/bar')) // false ``` ### options.format **Type**: `function` **Default**: `undefined` Custom function for formatting strings before they're matched. **Example** ```js // strip leading './' from strings const format = str => str.replace(/^\.\//, ''); const isMatch = picomatch('foo/*.js', { format }); console.log(isMatch('./foo/bar.js')) //=> true ``` ### options.ignore String or array of glob patterns to match files to ignore. **Type**: `String|Array` **Default**: `undefined` ```js const isMatch = micromatch.matcher('*', { ignore: 'f*' }); console.log(isMatch('foo')) //=> false console.log(isMatch('bar')) //=> true console.log(isMatch('baz')) //=> true ``` ### options.matchBase Alias for [options.basename](#options-basename). ### options.noextglob Disable extglob support, so that [extglobs](#extglobs) are regarded as literal characters. **Type**: `Boolean` **Default**: `undefined` **Examples** ```js console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)')); //=> ['a/b', 'a/!(z)'] console.log(micromatch(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', { noextglob: true })); //=> ['a/!(z)'] (matches only as literal characters) ``` ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. **Type**: `Boolean` **Default**: `undefined` ### options.noglobstar Disable matching with globstars (`**`). **Type**: `Boolean` **Default**: `undefined` ```js micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] micromatch(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` ### options.nonull Alias for [options.nullglob](#options-nullglob). ### options.nullglob 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`. **Type**: `Boolean` **Default**: `undefined` ### options.onIgnore ```js const onIgnore = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); // { glob: '*', regex: /^(?:(?!\.)(?=.)[^\/]*?\/?)$/, input: 'foo', output: 'foo' } }; const isMatch = micromatch.matcher('*', { onIgnore, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.onMatch ```js const onMatch = ({ glob, regex, input, output }) => { console.log({ input, output }); // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } // { input: 'some\\path', output: 'some/path' } }; const isMatch = micromatch.matcher('**', { onMatch, posixSlashes: true }); isMatch('some\\path'); isMatch('some\\path'); isMatch('some\\path'); ``` ### options.onResult ```js const onResult = ({ glob, regex, input, output }) => { console.log({ glob, regex, input, output }); }; const isMatch = micromatch('*', { onResult, ignore: 'f*' }); isMatch('foo'); isMatch('bar'); isMatch('baz'); ``` ### options.posixSlashes Convert path separators on returned files to posix/unix-style forward slashes. Aliased as `unixify` for backwards compatibility. **Type**: `Boolean` **Default**: `true` on windows, `false` everywhere else. **Example** ```js console.log(micromatch.match(['a\\b\\c'], 'a/**')); //=> ['a/b/c'] console.log(micromatch.match(['a\\b\\c'], { posixSlashes: false })); //=> ['a\\b\\c'] ``` ### options.unescape Remove backslashes from escaped glob characters before creating the regular expression to perform matches. **Type**: `Boolean` **Default**: `undefined` **Example** In this example we want to match a literal `*`: ```js console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c')); //=> ['a\\*c'] console.log(micromatch.match(['abc', 'a\\*c'], 'a\\*c', { unescape: true })); //=> ['a*c'] ``` <br> <br> ## Extended globbing Micromatch supports the following extended globbing features. ### Extglobs Extended globbing, as described by the bash man page: | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | <sup><strong>*</strong></sup> Note that `@` isn't a regex character. ### Braces Brace patterns can be used to match specific ranges or sets of characters. **Example** The pattern `{f,b}*/{1..3}/{b,q}*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. ### Regex character classes Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). ### Regex groups Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. ### POSIX bracket expressions POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. **Example** ```js console.log(micromatch.isMatch('a1', '[[:alpha:][:digit:]]')) //=> true console.log(micromatch.isMatch('a1', '[[:alpha:][:alpha:]]')) //=> false ``` *** ## Notes ### Bash 4.3 parity Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. ### Backslashes There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. * Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows, which is consistent with bash behavior. _More importantly, unescaping globs can result in unsafe regular expressions_. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. We made this decision for micromatch for a couple of reasons: * Consistency with bash conventions. * Glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. **A note about joining paths to globs** Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. To solve this, you might be inspired to do something like `'foo\\*'.replace(/\\/g, '/')`, but this causes another, potentially much more serious, problem. ## Benchmarks ### Running benchmarks Install dependencies for running benchmarks: ```sh $ cd bench && npm install ``` Run the benchmarks: ```sh $ npm run bench ``` ### Latest results As of March 24, 2022 (longer bars are better): ```sh # .makeRe star micromatch x 2,232,802 ops/sec ±2.34% (89 runs sampled)) minimatch x 781,018 ops/sec ±6.74% (92 runs sampled)) # .makeRe star; dot=true micromatch x 1,863,453 ops/sec ±0.74% (93 runs sampled) minimatch x 723,105 ops/sec ±0.75% (93 runs sampled) # .makeRe globstar micromatch x 1,624,179 ops/sec ±2.22% (91 runs sampled) minimatch x 1,117,230 ops/sec ±2.78% (86 runs sampled)) # .makeRe globstars micromatch x 1,658,642 ops/sec ±0.86% (92 runs sampled) minimatch x 741,224 ops/sec ±1.24% (89 runs sampled)) # .makeRe with leading star micromatch x 1,525,014 ops/sec ±1.63% (90 runs sampled) minimatch x 561,074 ops/sec ±3.07% (89 runs sampled) # .makeRe - braces micromatch x 172,478 ops/sec ±2.37% (78 runs sampled) minimatch x 96,087 ops/sec ±2.34% (88 runs sampled))) # .makeRe braces - range (expanded) micromatch x 26,973 ops/sec ±0.84% (89 runs sampled) minimatch x 3,023 ops/sec ±0.99% (90 runs sampled)) # .makeRe braces - range (compiled) micromatch x 152,892 ops/sec ±1.67% (83 runs sampled) minimatch x 992 ops/sec ±3.50% (89 runs sampled)d)) # .makeRe braces - nested ranges (expanded) micromatch x 15,816 ops/sec ±13.05% (80 runs sampled) minimatch x 2,953 ops/sec ±1.64% (91 runs sampled) # .makeRe braces - nested ranges (compiled) micromatch x 110,881 ops/sec ±1.85% (82 runs sampled) minimatch x 1,008 ops/sec ±1.51% (91 runs sampled) # .makeRe braces - set (compiled) micromatch x 134,930 ops/sec ±3.54% (63 runs sampled)) minimatch x 43,242 ops/sec ±0.60% (93 runs sampled) # .makeRe braces - nested sets (compiled) micromatch x 94,455 ops/sec ±1.74% (69 runs sampled)) minimatch x 27,720 ops/sec ±1.84% (93 runs sampled)) ``` ## Contributing All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. **Bug reports** Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: * [research existing issues first](../../issues) (open and closed) * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js * if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. **Platform issues** It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/micromatch/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 512 | [jonschlinkert](https://github.com/jonschlinkert) | | 12 | [es128](https://github.com/es128) | | 9 | [danez](https://github.com/danez) | | 8 | [doowb](https://github.com/doowb) | | 6 | [paulmillr](https://github.com/paulmillr) | | 5 | [mrmlnc](https://github.com/mrmlnc) | | 3 | [DrPizza](https://github.com/DrPizza) | | 2 | [TrySound](https://github.com/TrySound) | | 2 | [mceIdo](https://github.com/mceIdo) | | 2 | [Glazy](https://github.com/Glazy) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [antonyk](https://github.com/antonyk) | | 2 | [Tvrqvoise](https://github.com/Tvrqvoise) | | 1 | [amilajack](https://github.com/amilajack) | | 1 | [Cslove](https://github.com/Cslove) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [DianeLooney](https://github.com/DianeLooney) | | 1 | [UltCombo](https://github.com/UltCombo) | | 1 | [frangio](https://github.com/frangio) | | 1 | [joyceerhl](https://github.com/joyceerhl) | | 1 | [juszczykjakub](https://github.com/juszczykjakub) | | 1 | [muescha](https://github.com/muescha) | | 1 | [sebdeckers](https://github.com/sebdeckers) | | 1 | [tomByrer](https://github.com/tomByrer) | | 1 | [fidian](https://github.com/fidian) | | 1 | [curbengh](https://github.com/curbengh) | | 1 | [simlu](https://github.com/simlu) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | | 1 | [yvele](https://github.com/yvele) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2022, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 24, 2022._ # hash-base [![NPM Package](https://img.shields.io/npm/v/hash-base.svg?style=flat-square)](https://www.npmjs.org/package/hash-base) [![Build Status](https://img.shields.io/travis/crypto-browserify/hash-base.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/hash-base) [![Dependency status](https://img.shields.io/david/crypto-browserify/hash-base.svg?style=flat-square)](https://david-dm.org/crypto-browserify/hash-base#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Abstract base class to inherit from if you want to create streams implementing the same API as node crypto [Hash][1] (for [Cipher][2] / [Decipher][3] check [crypto-browserify/cipher-base][4]). ## Example ```js const HashBase = require('hash-base') const inherits = require('inherits') // our hash function is XOR sum of all bytes function MyHash () { HashBase.call(this, 1) // in bytes this._sum = 0x00 } inherits(MyHash, HashBase) MyHash.prototype._update = function () { for (let i = 0; i < this._block.length; ++i) this._sum ^= this._block[i] } MyHash.prototype._digest = function () { return this._sum } const data = Buffer.from([ 0x00, 0x42, 0x01 ]) const hash = new MyHash().update(data).digest() console.log(hash) // => 67 ``` You also can check [source code](index.js) or [crypto-browserify/md5.js][5] ## LICENSE MIT [1]: https://nodejs.org/api/crypto.html#crypto_class_hash [2]: https://nodejs.org/api/crypto.html#crypto_class_cipher [3]: https://nodejs.org/api/crypto.html#crypto_class_decipher [4]: https://github.com/crypto-browserify/cipher-base [5]: https://github.com/crypto-browserify/md5.js # Browserslist [![Cult Of Martians][cult-img]][cult] <img width="120" height="120" alt="Browserslist logo by Anton Popov" src="https://browsersl.ist/logo.svg" align="right"> The config to share target browsers and Node.js versions between different front-end tools. It is used in: * [Autoprefixer] * [Babel] * [postcss-preset-env] * [eslint-plugin-compat] * [stylelint-no-unsupported-browser-features] * [postcss-normalize] * [obsolete-webpack-plugin] All tools will find target browsers automatically, when you add the following to `package.json`: ```json "browserslist": [ "defaults and supports es6-module", "maintained node versions" ] ``` Or in `.browserslistrc` config: ```yaml # Browsers that we support defaults and supports es6-module maintained node versions ``` Developers set their version lists using queries like `last 2 versions` to be free from updating versions manually. Browserslist will use [`caniuse-lite`] with [Can I Use] data for this queries. You can check how config works at our playground: [`browsersl.ist`](https://browsersl.ist/) <a href="https://browsersl.ist/"> <img src="/img/screenshot.webp" alt="browsersl.ist website"> </a> <br> <br> <div align="center"> <a href="https://evilmartians.com/?utm_source=browserslist"> <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg" alt="Sponsored by Evil Martians" width="236" height="54"> </a> <a href="https://cube.dev/?ref=eco-browserslist-github"> <img src="https://user-images.githubusercontent.com/986756/154330861-d79ab8ec-aacb-4af8-9e17-1b28f1eccb01.svg" alt="Supported by Cube" width="227" height="46"> </a> </div> [stylelint-no-unsupported-browser-features]: https://github.com/ismay/stylelint-no-unsupported-browser-features [obsolete-webpack-plugin]: https://github.com/ElemeFE/obsolete-webpack-plugin [eslint-plugin-compat]: https://github.com/amilajack/eslint-plugin-compat [Browserslist Example]: https://github.com/browserslist/browserslist-example [postcss-preset-env]: https://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env [postcss-normalize]: https://github.com/csstools/postcss-normalize [`browsersl.ist`]: https://browsersl.ist/ [`caniuse-lite`]: https://github.com/ben-eb/caniuse-lite [Autoprefixer]: https://github.com/postcss/autoprefixer [Can I Use]: https://caniuse.com/ [Babel]: https://github.com/babel/babel/tree/master/packages/babel-preset-env [cult-img]: https://cultofmartians.com/assets/badges/badge.svg [cult]: https://cultofmartians.com/done.html ## Docs Read **[full docs](https://github.com/browserslist/browserslist#readme)** on GitHub. # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # capability.js - javascript environment capability detection [![Build Status](https://travis-ci.org/inf3rno/capability.png?branch=master)](https://travis-ci.org/inf3rno/capability) The capability.js library provides capability detection for different javascript environments. ## Documentation This project is empty yet. ### Installation ```bash npm install capability ``` ```bash bower install capability ``` #### Environment compatibility The lib requires only basic javascript features, so it will run in every js environments. #### Requirements If you want to use the lib in browser, you'll need a node module loader, e.g. browserify, webpack, etc... #### Usage In this documentation I used the lib as follows: ```js var capability = require("capability"); ``` ### Capabilities API #### Defining a capability You can define a capability by using the `define(name, test)` function. ```js capability.define("Object.create", function () { return Object.create; }); ``` The `name` parameter should contain the identifier of the capability and the `test` parameter should contain a function, which can detect the capability. If the capability is supported by the environment, then the `test()` should return `true`, otherwise it should return `false`. You don't have to convert the return value into a `Boolean`, the library will do that for you, so you won't have memory leaks because of this. #### Testing a capability The `test(name)` function will return a `Boolean` about whether the capability is supported by the actual environment. ```js console.log(capability.test("Object.create")); // true - in recent environments // false - by pre ES5 environments without Object.create ``` You can use `capability(name)` instead of `capability.test(name)` if you want a short code by optional requirements. #### Checking a capability The `check(name)` function will throw an Error when the capability is not supported by the actual environment. ```js capability.check("Object.create"); // this will throw an Error by pre ES5 environments without Object.create ``` #### Checking capability with require and modules It is possible to check the environments with `require()` by adding a module, which calls the `check(name)` function. By the capability definitions in this lib I added such modules by each definition, so you can do for example `require("capability/es5")`. Ofc. you can do fun stuff if you want, e.g. you can call multiple `check`s from a single `requirements.js` file in your lib, etc... ### Definitions Currently the following definitions are supported by the lib: - strict mode - `arguments.callee.caller` - es5 - `Array.prototype.forEach` - `Array.prototype.map` - `Function.prototype.bind` - `Object.create` - `Object.defineProperties` - `Object.defineProperty` - `Object.prototype.hasOwnProperty` - `Error.captureStackTrace` - `Error.prototype.stack` ## License MIT - 2016 Jánszky László Lajos # mustache.js - Logic-less {{mustache}} templates with JavaScript > What could be more logical awesome than no logic at all? [![Build Status](https://travis-ci.org/janl/mustache.js.svg?branch=master)](https://travis-ci.org/janl/mustache.js) [mustache.js](http://github.com/janl/mustache.js) is a zero-dependency implementation of the [mustache](http://mustache.github.com/) template system in JavaScript. [Mustache](http://mustache.github.com/) is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values. For a language-agnostic overview of mustache's template syntax, see the `mustache(5)` [manpage](http://mustache.github.com/mustache.5.html). ## Where to use mustache.js? You can use mustache.js to render mustache templates anywhere you can use JavaScript. This includes web browsers, server-side environments such as [Node.js](http://nodejs.org/), and [CouchDB](http://couchdb.apache.org/) views. mustache.js ships with support for the [CommonJS](http://www.commonjs.org/) module API, the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) API (AMD) and [ECMAScript modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). In addition to being a package to be used programmatically, you can use it as a [command line tool](#command-line-tool). And this will be your templates after you use Mustache: !['stache](https://cloud.githubusercontent.com/assets/288977/8779228/a3cf700e-2f02-11e5-869a-300312fb7a00.gif) ## Install You can get Mustache via [npm](http://npmjs.com). ```bash $ npm install mustache --save ``` ## Usage Below is a quick example how to use mustache.js: ```js var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view); ``` In this example, the `Mustache.render` function takes two parameters: 1) the [mustache](http://mustache.github.com/) template and 2) a `view` object that contains the data and code needed to render the template. ## Templates A [mustache](http://mustache.github.com/) template is a string that contains any number of mustache tags. Tags are indicated by the double mustaches that surround them. `{{person}}` is a tag, as is `{{#person}}`. In both examples we refer to `person` as the tag's key. There are several types of tags available in mustache.js, described below. There are several techniques that can be used to load templates and hand them to mustache.js, here are two of them: #### Include Templates If you need a template for a dynamic part in a static website, you can consider including the template in the static HTML file to avoid loading templates separately. Here's a small example: ```js // file: render.js function renderHello() { var template = document.getElementById('template').innerHTML; var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; } ``` ```html <html> <body onload="renderHello()"> <div id="target">Loading...</div> <script id="template" type="x-tmpl-mustache"> Hello {{ name }}! </script> <script src="https://unpkg.com/mustache@latest"></script> <script src="render.js"></script> </body> </html> ``` #### Load External Templates If your templates reside in individual files, you can load them asynchronously and render them when they arrive. Another example using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch): ```js function renderHello() { fetch('template.mustache') .then((response) => response.text()) .then((template) => { var rendered = Mustache.render(template, { name: 'Luke' }); document.getElementById('target').innerHTML = rendered; }); } ``` ### Variables The most basic tag type is a simple variable. A `{{name}}` tag renders the value of the `name` key in the current context. If there is no such key, nothing is rendered. All variables are HTML-escaped by default. If you want to render unescaped HTML, use the triple mustache: `{{{name}}}`. You can also use `&` to unescape a variable. If you'd like to change HTML-escaping behavior globally (for example, to template non-HTML formats), you can override Mustache's escape function. For example, to disable all escaping: `Mustache.escape = function(text) {return text;};`. If you want `{{name}}` _not_ to be interpreted as a mustache tag, but rather to appear exactly as `{{name}}` in the output, you must change and then restore the default delimiter. See the [Custom Delimiters](#custom-delimiters) section for more information. View: ```json { "name": "Chris", "company": "<b>GitHub</b>" } ``` Template: ``` * {{name}} * {{age}} * {{company}} * {{{company}}} * {{&company}} {{=<% %>=}} * {{company}} <%={{ }}=%> ``` Output: ```html * Chris * * &lt;b&gt;GitHub&lt;/b&gt; * <b>GitHub</b> * <b>GitHub</b> * {{company}} ``` JavaScript's dot notation may be used to access keys that are properties of objects in a view. View: ```json { "name": { "first": "Michael", "last": "Jackson" }, "age": "RIP" } ``` Template: ```html * {{name.first}} {{name.last}} * {{age}} ``` Output: ```html * Michael Jackson * RIP ``` ### Sections Sections render blocks of text zero or more times, depending on the value of the key in the current context. A section begins with a pound and ends with a slash. That is, `{{#person}}` begins a `person` section, while `{{/person}}` ends it. The text between the two tags is referred to as that section's "block". The behavior of the section is determined by the value of the key. #### False Values or Empty Lists If the `person` key does not exist, or exists and has a value of `null`, `undefined`, `false`, `0`, or `NaN`, or is an empty string or an empty list, the block will not be rendered. View: ```json { "person": false } ``` Template: ```html Shown. {{#person}} Never shown! {{/person}} ``` Output: ```html Shown. ``` #### Non-Empty Lists If the `person` key exists and is not `null`, `undefined`, or `false`, and is not an empty list the block will be rendered one or more times. When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections. View: ```json { "stooges": [ { "name": "Moe" }, { "name": "Larry" }, { "name": "Curly" } ] } ``` Template: ```html {{#stooges}} <b>{{name}}</b> {{/stooges}} ``` Output: ```html <b>Moe</b> <b>Larry</b> <b>Curly</b> ``` When looping over an array of strings, a `.` can be used to refer to the current item in the list. View: ```json { "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"] } ``` Template: ```html {{#musketeers}} * {{.}} {{/musketeers}} ``` Output: ```html * Athos * Aramis * Porthos * D'Artagnan ``` If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. View: ```js { "beatles": [ { "firstName": "John", "lastName": "Lennon" }, { "firstName": "Paul", "lastName": "McCartney" }, { "firstName": "George", "lastName": "Harrison" }, { "firstName": "Ringo", "lastName": "Starr" } ], "name": function () { return this.firstName + " " + this.lastName; } } ``` Template: ```html {{#beatles}} * {{name}} {{/beatles}} ``` Output: ```html * John Lennon * Paul McCartney * George Harrison * Ringo Starr ``` #### Functions If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. View: ```js { "name": "Tater", "bold": function () { return function (text, render) { return "<b>" + render(text) + "</b>"; } } } ``` Template: ```html {{#bold}}Hi {{name}}.{{/bold}} ``` Output: ```html <b>Hi Tater.</b> ``` ### Inverted Sections An inverted section opens with `{{^section}}` instead of `{{#section}}`. The block of an inverted section is rendered only if the value of that section's tag is `null`, `undefined`, `false`, *falsy* or an empty list. View: ```json { "repos": [] } ``` Template: ```html {{#repos}}<b>{{name}}</b>{{/repos}} {{^repos}}No repos :({{/repos}} ``` Output: ```html No repos :( ``` ### Comments Comments begin with a bang and are ignored. The following template: ```html <h1>Today{{! ignore me }}.</h1> ``` Will render as follows: ```html <h1>Today.</h1> ``` Comments may contain newlines. ### Partials Partials begin with a greater than sign, like {{> box}}. Partials are rendered at runtime (as opposed to compile time), so recursive partials are possible. Just avoid infinite loops. They also inherit the calling context. Whereas in ERB you may have this: ```html+erb <%= partial :next_more, :start => start, :size => size %> ``` Mustache requires only this: ```html {{> next_more}} ``` Why? Because the `next_more.mustache` file will inherit the `size` and `start` variables from the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. For example, this template and partial: base.mustache: <h2>Names</h2> {{#names}} {{> user}} {{/names}} user.mustache: <strong>{{name}}</strong> Can be thought of as a single, expanded template: ```html <h2>Names</h2> {{#names}} <strong>{{name}}</strong> {{/names}} ``` In mustache.js an object of partials may be passed as the third argument to `Mustache.render`. The object should be keyed by the name of the partial, and its value should be the partial text. ```js Mustache.render(template, view, { user: userTemplate }); ``` ### Custom Delimiters Custom delimiters can be used in place of `{{` and `}}` by setting the new values in JavaScript or in templates. #### Setting in JavaScript The `Mustache.tags` property holds an array consisting of the opening and closing tag values. Set custom values by passing a new array of tags to `render()`, which gets honored over the default values, or by overriding the `Mustache.tags` property itself: ```js var customTags = [ '<%', '%>' ]; ``` ##### Pass Value into Render Method ```js Mustache.render(template, view, {}, customTags); ``` ##### Override Tags Property ```js Mustache.tags = customTags; // Subsequent parse() and render() calls will use customTags ``` #### Setting in Templates Set Delimiter tags start with an equals sign and change the tag delimiters from `{{` and `}}` to custom strings. Consider the following contrived example: ```html+erb * {{ default_tags }} {{=<% %>=}} * <% erb_style_tags %> <%={{ }}=%> * {{ default_tags_again }} ``` Here we have a list with three items. The first item uses the default tag style, the second uses ERB style as defined by the Set Delimiter tag, and the third returns to the default style after yet another Set Delimiter declaration. According to [ctemplates](https://htmlpreview.github.io/?https://raw.githubusercontent.com/OlafvdSpek/ctemplate/master/doc/howto.html), this "is useful for languages like TeX, where double-braces may occur in the text and are awkward to use for markup." Custom delimiters may not contain whitespace or the equals sign. ## Pre-parsing and Caching Templates By default, when mustache.js first parses a template it keeps the full parsed token tree in a cache. The next time it sees that same template it skips the parsing step and renders the template much more quickly. If you'd like, you can do this ahead of time using `mustache.parse`. ```js Mustache.parse(template); // Then, sometime later. Mustache.render(template, view); ``` ## Command line tool mustache.js is shipped with a Node.js based command line tool. It might be installed as a global tool on your computer to render a mustache template of some kind ```bash $ npm install -g mustache $ mustache dataView.json myTemplate.mustache > output.html ``` also supports stdin. ```bash $ cat dataView.json | mustache - myTemplate.mustache > output.html ``` or as a package.json `devDependency` in a build process maybe? ```bash $ npm install mustache --save-dev ``` ```json { "scripts": { "build": "mustache dataView.json myTemplate.mustache > public/output.html" } } ``` ```bash $ npm run build ``` The command line tool is basically a wrapper around `Mustache.render` so you get all the features. If your templates use partials you should pass paths to partials using `-p` flag: ```bash $ mustache -p path/to/partial1.mustache -p path/to/partial2.mustache dataView.json myTemplate.mustache ``` ## Plugins for JavaScript Libraries mustache.js may be built specifically for several different client libraries, including the following: - [jQuery](http://jquery.com/) - [MooTools](http://mootools.net/) - [Dojo](http://www.dojotoolkit.org/) - [YUI](http://developer.yahoo.com/yui/) - [qooxdoo](http://qooxdoo.org/) These may be built using [Rake](http://rake.rubyforge.org/) and one of the following commands: ```bash $ rake jquery $ rake mootools $ rake dojo $ rake yui3 $ rake qooxdoo ``` ## TypeScript Since the source code of this package is written in JavaScript, we follow the [TypeScript publishing docs](https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) preferred approach by having type definitions available via [@types/mustache](https://www.npmjs.com/package/@types/mustache). ## Testing In order to run the tests you'll need to install [Node.js](http://nodejs.org/). You also need to install the sub module containing [Mustache specifications](http://github.com/mustache/spec) in the project root. ```bash $ git submodule init $ git submodule update ``` Install dependencies. ```bash $ npm install ``` Then run the tests. ```bash $ npm test ``` The test suite consists of both unit and integration tests. If a template isn't rendering correctly for you, you can make a test for it by doing the following: 1. Create a template file named `mytest.mustache` in the `test/_files` directory. Replace `mytest` with the name of your test. 2. Create a corresponding view file named `mytest.js` in the same directory. This file should contain a JavaScript object literal enclosed in parentheses. See any of the other view files for an example. 3. Create a file with the expected output in `mytest.txt` in the same directory. Then, you can run the test with: ```bash $ TEST=mytest npm run test-render ``` ### Browser tests Browser tests are not included in `npm test` as they run for too long, although they are ran automatically on Travis when merged into master. Run browser tests locally in any browser: ```bash $ npm run test-browser-local ``` then point your browser to `http://localhost:8080/__zuul` ## Who uses mustache.js? An updated list of mustache.js users is kept [on the Github wiki](https://github.com/janl/mustache.js/wiki/Beard-Competition). Add yourself or your company if you use mustache.js! ## Contributing mustache.js is a mature project, but it continues to actively invite maintainers. You can help out a high-profile project that is used in a lot of places on the web. No big commitment required, if all you do is review a single [Pull Request](https://github.com/janl/mustache.js/pulls), you are a maintainer. And a hero. ### Your First Contribution - review a [Pull Request](https://github.com/janl/mustache.js/pulls) - fix an [Issue](https://github.com/janl/mustache.js/issues) - update the [documentation](https://github.com/janl/mustache.js#usage) - make a website - write a tutorial ## Thanks mustache.js wouldn't kick ass if it weren't for these fine souls: * Chris Wanstrath / defunkt * Alexander Lang / langalex * Sebastian Cohnen / tisba * J Chris Anderson / jchris * Tom Robinson / tlrobinson * Aaron Quint / quirkey * Douglas Crockford * Nikita Vasilyev / NV * Elise Wood / glytch * Damien Mathieu / dmathieu * Jakub Kuźma / qoobaa * Will Leinweber / will * dpree * Jason Smith / jhs * Aaron Gibralter / agibralter * Ross Boucher / boucher * Matt Sanford / mzsanford * Ben Cherry / bcherry * Michael Jackson / mjackson * Phillip Johnsen / phillipj * David da Silva Contín / dasilvacontin # fs-constants Small module that allows you to get the fs constants across Node and the browser. ``` npm install fs-constants ``` Previously you would use `require('constants')` for this in node but that has been deprecated and changed to `require('fs').constants` which does not browserify. This module uses `require('constants')` in the browser and `require('fs').constants` in node to work around this ## Usage ``` js var constants = require('fs-constants') console.log('constants:', constants) ``` ## License MIT # node-gyp-build > Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds. ``` npm install node-gyp-build ``` [![Test](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml/badge.svg)](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml) Use together with [`prebuildify`][prebuildify] to easily support prebuilds for your native modules. ## Usage > **Note.** Prebuild names have changed in [`prebuildify@3`][prebuildify] and `node-gyp-build@4`. Please see the documentation below. `node-gyp-build` works similar to [`node-gyp build`][node-gyp] except that it will check if a build or prebuild is present before rebuilding your project. It's main intended use is as an npm install script and bindings loader for native modules that bundle prebuilds using [`prebuildify`][prebuildify]. First add `node-gyp-build` as an install script to your native project ``` js { ... "scripts": { "install": "node-gyp-build" } } ``` Then in your `index.js`, instead of using the [`bindings`](https://www.npmjs.com/package/bindings) module use `node-gyp-build` to load your binding. ``` js var binding = require('node-gyp-build')(__dirname) ``` If you do these two things and bundle prebuilds with [`prebuildify`][prebuildify] your native module will work for most platforms without having to compile on install time AND will work in both node and electron without the need to recompile between usage. Users can override `node-gyp-build` and force compiling by doing `npm install --build-from-source`. Prebuilds will be attempted loaded from `MODULE_PATH/prebuilds/...` and then next `EXEC_PATH/prebuilds/...` (the latter allowing use with `zeit/pkg`) ## Supported prebuild names If so desired you can bundle more specific flavors, for example `musl` builds to support Alpine, or targeting a numbered ARM architecture version. These prebuilds can be bundled in addition to generic prebuilds; `node-gyp-build` will try to find the most specific flavor first. Prebuild filenames are composed of _tags_. The runtime tag takes precedence, as does an `abi` tag over `napi`. For more details on tags, please see [`prebuildify`][prebuildify]. Values for the `libc` and `armv` tags are auto-detected but can be overridden through the `LIBC` and `ARM_VERSION` environment variables, respectively. ## License MIT [prebuildify]: https://github.com/prebuild/prebuildify [node-gyp]: https://www.npmjs.com/package/node-gyp # graceful-fs graceful-fs functions as a drop-in replacement for the fs module, making various improvements. The improvements are meant to normalize behavior across different platforms and environments, and to make filesystem access more resilient to errors. ## Improvements over [fs module](https://nodejs.org/api/fs.html) * Queues up `open` and `readdir` calls, and retries them once something closes if there is an EMFILE error from too many file descriptors. * fixes `lchmod` for Node versions prior to 0.6.2. * implements `fs.lutimes` if possible. Otherwise it becomes a noop. * ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or `lchown` if the user isn't root. * makes `lchmod` and `lchown` become noops, if not available. * retries reading a file if `read` results in EAGAIN error. On Windows, it retries renaming a file for up to one second if `EACCESS` or `EPERM` error occurs, likely because antivirus software has locked the directory. ## USAGE ```javascript // use just like fs var fs = require('graceful-fs') // now go and do stuff with it... fs.readFile('some-file-or-whatever', (err, data) => { // Do stuff here. }) ``` ## Sync methods This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync methods. If you use sync methods which open file descriptors then you are responsible for dealing with any errors. This is a known limitation, not a bug. ## Global Patching If you want to patch the global fs module (or any other fs-like module) you can do this: ```javascript // Make sure to read the caveat below. var realFs = require('fs') var gracefulFs = require('graceful-fs') gracefulFs.gracefulify(realFs) ``` This should only ever be done at the top-level application layer, in order to delay on EMFILE errors from any fs-using dependencies. You should **not** do this in a library, because it can cause unexpected delays in other parts of the program. ## Changes This module is fairly stable at this point, and used by a lot of things. That being said, because it implements a subtle behavior change in a core part of the node API, even modest changes can be extremely breaking, and the versioning is thus biased towards bumping the major when in doubt. The main change between major versions has been switching between providing a fully-patched `fs` module vs monkey-patching the node core builtin, and the approach by which a non-monkey-patched `fs` was created. The goal is to trade `EMFILE` errors for slower fs operations. So, if you try to open a zillion files, rather than crashing, `open` operations will be queued up and wait for something else to `close`. There are advantages to each approach. Monkey-patching the fs means that no `EMFILE` errors can possibly occur anywhere in your application, because everything is using the same core `fs` module, which is patched. However, it can also obviously cause undesirable side-effects, especially if the module is loaded multiple times. Implementing a separate-but-identical patched `fs` module is more surgical (and doesn't run the risk of patching multiple times), but also imposes the challenge of keeping in sync with the core module. The current approach loads the `fs` module, and then creates a lookalike object that has all the same methods, except a few that are patched. It is safe to use in all versions of Node from 0.8 through 7.0. ### v4 * Do not monkey-patch the fs module. This module may now be used as a drop-in dep, and users can opt into monkey-patching the fs builtin if their app requires it. ### v3 * Monkey-patch fs, because the eval approach no longer works on recent node. * fixed possible type-error throw if rename fails on windows * verify that we *never* get EMFILE errors * Ignore ENOSYS from chmod/chown * clarify that graceful-fs must be used as a drop-in ### v2.1.0 * Use eval rather than monkey-patching fs. * readdir: Always sort the results * win32: requeue a file if error has an OK status ### v2.0 * A return to monkey patching * wrap process.cwd ### v1.1 * wrap readFile * Wrap fs.writeFile. * readdir protection * Don't clobber the fs builtin * Handle fs.read EAGAIN errors by trying again * Expose the curOpen counter * No-op lchown/lchmod if not implemented * fs.rename patch only for win32 * Patch fs.rename to handle AV software on Windows * Close #4 Chown should not fail on einval or eperm if non-root * Fix isaacs/fstream#1 Only wrap fs one time * Fix #3 Start at 1024 max files, then back off on EMFILE * lutimes that doens't blow up on Linux * A full on-rewrite using a queue instead of just swallowing the EMFILE error * Wrap Read/Write streams as well ### 1.0 * Update engines for node 0.6 * Be lstat-graceful on Windows * first # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. Inspired by http://stackoverflow.com/questions/13227489 *note: this relies on Node/V8 specific APIs, as such other runtimes may not work* ## Installation ```bash yarn add get-caller-file ``` ## Usage Given: ```js // ./foo.js const getCallerFile = require('get-caller-file'); module.exports = function() { return getCallerFile(); // figures out who called it }; ``` ```js // index.js const foo = require('./foo'); foo() // => /full/path/to/this/file/index.js ``` ## Options: * `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. # mkdirp-classic Just a non-deprecated mirror of [mkdirp 0.5.2](https://github.com/substack/node-mkdirp/tree/0.5.1) for use in modules where we depend on the non promise interface. ``` npm install mkdirp-classic ``` ## Usage ``` js // See the above link ``` ## License MIT base64-js ========= `base64-js` does basic base64 encoding/decoding in pure JS. [![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. ## install With [npm](https://npmjs.org) do: `npm install base64-js` and `var base64js = require('base64-js')` For use in web browsers do: `<script src="base64js.min.js"></script>` [Get supported base64-js with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-base64-js?utm_source=npm-base64-js&utm_medium=referral&utm_campaign=readme) ## methods `base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. * `byteLength` - Takes a base64 string and returns length of byte array * `toByteArray` - Takes a base64 string and returns a byte array * `fromByteArray` - Takes a byte array and returns a base64 string ## license MIT NEAR Units ========== TypeScript/JavaScript tools to help parse and format NEAR units. For now, this means NEAR tokens and [gas units](https://docs.near.org/docs/concepts/gas). # Install npm i --save near-units Or using [Yarn](https://yarnpkg.com/): yarn add near-units # Parsing strings ```js import { NEAR, Gas, parse } from 'near-units'; const near = NEAR.parse('1.25 mN'); console.log(near.toHuman()); // 1.25 mN const gas = Gas.parse('1 Tgas'); console.log(gas.toHuman()); // 1 Tgas // equivalent to the above, but TS typings might not be as helpful const near = parse('1.25 mN'); const gas = parse('1 Tgas'); ``` See [\_\_tests__](./__tests__) for a full list of examples of inputs that can be parsed and the human-readable version that can be returned by `toHuman`. # Doing math `NEAR` and `Gas` both wrap `BN` from [bn.js], so you can perform any math with them that you need: ```js import { NEAR } from 'near-units'; const amount1 = NEAR.parse('100'); const amount2 = NEAR.parse('0.5'); const amount3 = amount1.mul(amount2); ``` See [the bn.js docs for all possible operations][bn.js]. [bn.js]: https://github.com/indutny/bn.js/ # Interop Since they wrap `BN`, they can be passed directly to function calls with [near-api-js](https://github.com/near/near-api-js) or [near-runner](https://github.com/near/runner-js): ```js // with an Account object from near-api-js someAccount.functionCall({ contractId: 'example.near', methodName: 'do_something', args: { param1: 'whatever' }, gas: Gas.parse('50,000,000,000,000'), attachedDeposit: NEAR.parse('1'), }); // with an Account object from near-runner someAccount.call( 'example.near', 'do_something', { param1: 'whatever' }, { gas: Gas.parse('50,000,000,000,000'), attachedDeposit: NEAR.parse('1'), } }); ``` `NEAR` and `Gas` also both override `toJSON` to get to a string version that can be passed as an argument to near-cli and in other contexts. # CLI This package ships with a minimal CLI: npm i -g near-units Now you can `near-units --help`: Parse and format NEAR tokens and gas units. Examples: near-units 10 N # => 10000000000000000000000000 near-units -h 10000000000000000000000000 yN # => 10 N near-units 50 Tgas # => 50000000000000 near-units -h 50000000000000 gas # => 50 Tgas You can use it anywhere near units are accepted. For example, on macOS & Linux, you can: ```bash near call $LOCKUP transfer '{ "receiver_id": "example.near", "amount": "'$(near-units 1N)'" }' --accountId=$ACCOUNT --gas=$(near-units 50Tgas) ``` # registry-auth-token [![npm version](http://img.shields.io/npm/v/registry-auth-token.svg?style=flat-square)](http://browsenpm.org/package/registry-auth-token)[![Build Status](http://img.shields.io/travis/rexxars/registry-auth-token/main.svg?style=flat-square)](https://travis-ci.org/rexxars/registry-auth-token) Get the auth token set for an npm registry from `.npmrc`. Also allows fetching the configured registry URL for a given npm scope. ## Installing ``` npm install --save registry-auth-token ``` ## Usage Returns an object containing `token` and `type`, or `undefined` if no token can be found. `type` can be either `Bearer` or `Basic`. ```js var getAuthToken = require('registry-auth-token') var getRegistryUrl = require('registry-auth-token/registry-url') // Get auth token and type for default `registry` set in `.npmrc` console.log(getAuthToken()) // {token: 'someToken', type: 'Bearer'} // Get auth token for a specific registry URL console.log(getAuthToken('//registry.foo.bar')) // Find the registry auth token for a given URL (with deep path): // If registry is at `//some.host/registry` // URL passed is `//some.host/registry/deep/path` // Will find token the closest matching path; `//some.host/registry` console.log(getAuthToken('//some.host/registry/deep/path', {recursive: true})) // Find the configured registry url for scope `@foobar`. // Falls back to the global registry if not defined. console.log(getRegistryUrl('@foobar')) // Use the npm config that is passed in console.log(getRegistryUrl('http://registry.foobar.eu/', { npmrc: { 'registry': 'http://registry.foobar.eu/', '//registry.foobar.eu/:_authToken': 'qar' } })) ``` ## Return value ```js // If auth info can be found: {token: 'someToken', type: 'Bearer'} // Or: {token: 'someOtherToken', type: 'Basic'} // Or, if nothing is found: undefined ``` ## Security Please be careful when using this. Leaking your auth token is dangerous. ## License MIT-licensed. See LICENSE. TweetNaCl.js ============ Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) to JavaScript for modern browsers and Node.js. Public domain. [![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) ](https://travis-ci.org/dchest/tweetnacl-js) Demo: <https://dchest.github.io/tweetnacl-js/> Documentation ============= * [Overview](#overview) * [Audits](#audits) * [Installation](#installation) * [Examples](#examples) * [Usage](#usage) * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) * [Scalar multiplication](#scalar-multiplication) * [Signatures](#signatures) * [Hashing](#hashing) * [Random bytes generation](#random-bytes-generation) * [Constant-time comparison](#constant-time-comparison) * [System requirements](#system-requirements) * [Development and testing](#development-and-testing) * [Benchmarks](#benchmarks) * [Contributors](#contributors) * [Who uses it](#who-uses-it) Overview -------- The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it. There are two versions, you can use either of them: * `nacl.js` is the port of TweetNaCl with minimum differences from the original + high-level API. * `nacl-fast.js` is like `nacl.js`, but with some functions replaced with faster versions. (Used by default when importing NPM package.) Audits ------ TweetNaCl.js has been audited by [Cure53](https://cure53.de/) in January-February 2017 (audit was sponsored by [Deletype](https://deletype.com)): > The overall outcome of this audit signals a particularly positive assessment > for TweetNaCl-js, as the testing team was unable to find any security > problems in the library. It has to be noted that this is an exceptionally > rare result of a source code audit for any project and must be seen as a true > testament to a development proceeding with security at its core. > > To reiterate, the TweetNaCl-js project, the source code was found to be > bug-free at this point. > > [...] > > In sum, the testing team is happy to recommend the TweetNaCl-js project as > likely one of the safer and more secure cryptographic tools among its > competition. [Read full audit report](https://cure53.de/tweetnacl.pdf) Installation ------------ You can install TweetNaCl.js via a package manager: [Yarn](https://yarnpkg.com/): $ yarn add tweetnacl [NPM](https://www.npmjs.org/): $ npm install tweetnacl or [download source code](https://github.com/dchest/tweetnacl-js/releases). Examples -------- You can find usage examples in our [wiki](https://github.com/dchest/tweetnacl-js/wiki/Examples). Usage ----- All API functions accept and return bytes as `Uint8Array`s. If you need to encode or decode strings, use functions from <https://github.com/dchest/tweetnacl-util-js> or one of the more robust codec packages. In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to convert them manually; make sure to convert using copying: `Buffer.from(array)` (or `new Buffer(array)` in Node.js v4 or earlier), instead of sharing: `Buffer.from(array.buffer)` (or `new Buffer(array.buffer)` Node 4 or earlier), because some functions return subarrays of their buffers. ### Public-key authenticated encryption (box) Implements *x25519-xsalsa20-poly1305*. #### nacl.box.keyPair() Generates a new random key pair for box and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 32-byte secret key } #### nacl.box.keyPair.fromSecretKey(secretKey) Returns a key pair for box with public key corresponding to the given secret key. #### nacl.box(message, nonce, theirPublicKey, mySecretKey) Encrypts and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair. Returns an encrypted and authenticated message, which is `nacl.box.overheadLength` longer than the original message. #### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce. Returns the original message, or `null` if authentication fails. #### nacl.box.before(theirPublicKey, mySecretKey) Returns a precomputed shared key which can be used in `nacl.box.after` and `nacl.box.open.after`. #### nacl.box.after(message, nonce, sharedKey) Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.open.after(box, nonce, sharedKey) Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. #### Constants ##### nacl.box.publicKeyLength = 32 Length of public key in bytes. ##### nacl.box.secretKeyLength = 32 Length of secret key in bytes. ##### nacl.box.sharedKeyLength = 32 Length of precomputed shared key in bytes. ##### nacl.box.nonceLength = 24 Length of nonce in bytes. ##### nacl.box.overheadLength = 16 Length of overhead added to box compared to original message. ### Secret-key authenticated encryption (secretbox) Implements *xsalsa20-poly1305*. #### nacl.secretbox(message, nonce, key) Encrypts and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key. Returns an encrypted and authenticated message, which is `nacl.secretbox.overheadLength` longer than the original message. #### nacl.secretbox.open(box, nonce, key) Authenticates and decrypts the given secret box using the key and the nonce. Returns the original message, or `null` if authentication fails. #### Constants ##### nacl.secretbox.keyLength = 32 Length of key in bytes. ##### nacl.secretbox.nonceLength = 24 Length of nonce in bytes. ##### nacl.secretbox.overheadLength = 16 Length of overhead added to secret box compared to original message. ### Scalar multiplication Implements *x25519*. #### nacl.scalarMult(n, p) Multiplies an integer `n` by a group element `p` and returns the resulting group element. #### nacl.scalarMult.base(n) Multiplies an integer `n` by a standard group element and returns the resulting group element. #### Constants ##### nacl.scalarMult.scalarLength = 32 Length of scalar in bytes. ##### nacl.scalarMult.groupElementLength = 32 Length of group element in bytes. ### Signatures Implements [ed25519](http://ed25519.cr.yp.to). #### nacl.sign.keyPair() Generates new random key pair for signing and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 64-byte secret key } #### nacl.sign.keyPair.fromSecretKey(secretKey) Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by `nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. #### nacl.sign.keyPair.fromSeed(seed) Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use `nacl.sign.keyPair` to generate a new key pair from a random seed. #### nacl.sign(message, secretKey) Signs the message using the secret key and returns a signed message. #### nacl.sign.open(signedMessage, publicKey) Verifies the signed message and returns the message without signature. Returns `null` if verification failed. #### nacl.sign.detached(message, secretKey) Signs the message using the secret key and returns a signature. #### nacl.sign.detached.verify(message, signature, publicKey) Verifies the signature for the message and returns `true` if verification succeeded or `false` if it failed. #### Constants ##### nacl.sign.publicKeyLength = 32 Length of signing public key in bytes. ##### nacl.sign.secretKeyLength = 64 Length of signing secret key in bytes. ##### nacl.sign.seedLength = 32 Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. ##### nacl.sign.signatureLength = 64 Length of signature in bytes. ### Hashing Implements *SHA-512*. #### nacl.hash(message) Returns SHA-512 hash of the message. #### Constants ##### nacl.hash.hashLength = 64 Length of hash in bytes. ### Random bytes generation #### nacl.randomBytes(length) Returns a `Uint8Array` of the given length containing random bytes of cryptographic quality. **Implementation note** TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on: * `window.crypto.getRandomValues` (WebCrypto standard) * `window.msCrypto.getRandomValues` (Internet Explorer 11) * `crypto.randomBytes` (Node.js) If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception: * `nacl.randomBytes` * `nacl.box.keyPair` * `nacl.sign.keyPair` Other functions are deterministic and will continue working. If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not `Math.random`!), and you know what you are doing, you can plug it into TweetNaCl.js like this: nacl.setPRNG(function(x, n) { // ... copy n random bytes into x ... }); Note that `nacl.setPRNG` *completely replaces* internal random byte generator with the one provided. ### Constant-time comparison #### nacl.verify(x, y) Compares `x` and `y` in constant time and returns `true` if their lengths are non-zero and equal, and their contents are equal. Returns `false` if either of the arguments has zero length, or arguments have different lengths, or their contents differ. System requirements ------------------- TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of: * Chrome * Firefox * Safari (Mac, iOS) * Internet Explorer 11 Other systems: * Node.js Development and testing ------------------------ Install NPM modules needed for development: $ npm install To build minified versions: $ npm run build Tests use minified version, so make sure to rebuild it every time you change `nacl.js` or `nacl-fast.js`. ### Testing To run tests in Node.js: $ npm run test-node By default all tests described here work on `nacl.min.js`. To test other versions, set environment variable `NACL_SRC` to the file name you want to test. For example, the following command will test fast minified version: $ NACL_SRC=nacl-fast.min.js npm run test-node To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version: $ npm run test-node-all To prepare tests for browsers: $ npm run build-test-browser and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to run them. To run tests in both Node and Electron: $ npm test ### Benchmarking To run benchmarks in Node.js: $ npm run bench $ NACL_SRC=nacl-fast.min.js npm run bench To run benchmarks in a browser, open `test/benchmark/bench.html` (or `test/benchmark/bench-fast.html`). Benchmarks ---------- For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android: | | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | | ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| | salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | | poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | | hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | | secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | | box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | | scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | | sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | | sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | (You can run benchmarks on your devices by clicking on the links at the bottom of the [home page](https://tweetnacl.js.org)). In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 200 and verify 100 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications. Contributors ------------ See AUTHORS.md file. Third-party libraries based on TweetNaCl.js ------------------------------------------- * [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation * [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption * [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) * [tweetnacl-sealed-box](https://github.com/whs/tweetnacl-sealed-box) — implementation of [`sealed boxes`](https://download.libsodium.org/doc/public-key_cryptography/sealed_boxes.html) * [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules Who uses it ----------- Some notable users of TweetNaCl.js: * [GitHub](https://github.com) * [MEGA](https://github.com/meganz/webclient) * [Stellar](https://www.stellar.org/) * [miniLock](https://github.com/kaepora/miniLock) wide-align ---------- A wide-character aware text alignment function for use in terminals / on the console. ### Usage ``` var align = require('wide-align') // Note that if you view this on a unicode console, all of the slashes are // aligned. This is because on a console, all narrow characters are // an en wide and all wide characters are an em. In browsers, this isn't // held to and wide characters like "古" can be less than two narrow // characters even with a fixed width font. console.log(align.center('abc', 10)) // ' abc ' console.log(align.center('古古古', 10)) // ' 古古古 ' console.log(align.left('abc', 10)) // 'abc ' console.log(align.left('古古古', 10)) // '古古古 ' console.log(align.right('abc', 10)) // ' abc' console.log(align.right('古古古', 10)) // ' 古古古' ``` ### Functions #### `align.center(str, length)` → `str` Returns *str* with spaces added to both sides such that that it is *length* chars long and centered in the spaces. #### `align.left(str, length)` → `str` Returns *str* with spaces to the right such that it is *length* chars long. ### `align.right(str, length)` → `str` Returns *str* with spaces to the left such that it is *length* chars long. ### Origins These functions were originally taken from [cliui](https://npmjs.com/package/cliui). Changes include switching to the MUCH faster pad generation function from [lodash](https://npmjs.com/package/lodash), making center alignment pad both sides and adding left alignment. <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # Borsh JS [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![Travis status](https://travis-ci.com/near/borsh.svg?branch=master)](https://travis-ci.com/near/borsh-js) [![NPM version](https://img.shields.io/npm/v/borsh.svg?style=flat-square)](https://npmjs.com/borsh) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/borsh.svg?style=flat-square)](https://npmjs.com/borsh) **Borsh JS** is an implementation of the [Borsh] binary serialization format for JavaScript and TypeScript projects. Borsh stands for _Binary Object Representation Serializer for Hashing_. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification. ## Examples ### Serializing an object ```javascript const value = new Test({ x: 255, y: 20, z: '123', q: [1, 2, 3] }); const schema = new Map([[Test, { kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]); const buffer = borsh.serialize(schema, value); ``` ### Deserializing an object ```javascript const newValue = borsh.deserialize(schema, Test, buffer); ``` ## Type Mappings | Borsh | TypeScript | |-----------------------|----------------| | `u8` integer | `number` | | `u16` integer | `number` | | `u32` integer | `number` | | `u64` integer | `BN` | | `u128` integer | `BN` | | `u256` integer | `BN` | | `u512` integer | `BN` | | `f32` float | N/A | | `f64` float | N/A | | fixed-size byte array | `Uint8Array` | | UTF-8 string | `string` | | option | `null` or type | | map | N/A | | set | N/A | | structs | `any` | ## Contributing Install dependencies: ```bash yarn install ``` Continuously build with: ```bash yarn dev ``` Run tests: ```bash yarn test ``` Run linter ```bash yarn lint ``` ## Publish Prepare `dist` version by running: ```bash yarn build ``` When publishing to npm use [np](https://github.com/sindresorhus/np). # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT.txt) and [LICENSE-APACHE](LICENSE-APACHE) for details. [Borsh]: https://borsh.io util-deprecate ============== ### The Node.js `util.deprecate()` function with browser support In Node.js, this module simply re-exports the `util.deprecate()` function. In the web browser (i.e. via browserify), a browser-specific implementation of the `util.deprecate()` function is used. ## API A `deprecate()` function is the only thing exposed by this module. ``` javascript // setup: exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); // users see: foo(); // foo() is deprecated, use bar() instead foo(); foo(); ``` ## License (The MIT License) Copyright (c) 2014 Nathan Rajlich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ci-parallel-vars > Get CI environment variables for parallelizing builds ## Install ``` yarn add ci-parallel-vars ``` ## Usage ```js const ciParallelVars = require('ci-parallel-vars'); console.log(ciParallelVars); // { index: 3, total: 10 } || null ``` ## Supports > If you want to add support for another pair, please open a pull request and > add them to `index.js` and to this list. - [Knapsack] / [TravisCI] / [GitLab] - `CI_NODE_INDEX`/`CI_NODE_TOTAL` - [CircleCI] - `CIRCLE_NODE_INDEX`/`CIRCLE_NODE_TOTAL` - [Bitbucket Pipelines] - `BITBUCKET_PARALLEL_STEP`/`BITBUCKET_PARALLEL_STEP_COUNT` - [Buildkite] - `BUILDKITE_PARALLEL_JOB`/`BUILDKITE_PARALLEL_JOB_COUNT` - [Semaphore] - `SEMAPHORE_CURRENT_JOB`/`SEMAPHORE_JOB_COUNT` One of these pairs must both be defined as numbers or `ci-parallel-vars` will be `null`. [Knapsack]: http://docs.knapsackpro.com/ruby/knapsack#info-about-env-variables [TravisCI]: https://docs.travis-ci.com/user/speeding-up-the-build/#Parallelizing-RSpec%2C-Cucumber-and-Minitest-on-multiple-VMs [GitLab]: https://docs.gitlab.com/ee/ci/yaml/#parallel [CircleCI]: https://circleci.com/docs/1.0/parallel-manual-setup/#using-environment-variables [Bitbucket Pipelines]: https://confluence.atlassian.com/bitbucket/parallel-steps-946606807.html [Buildkite]: https://buildkite.com/docs/builds/parallel-builds [Semaphore]: https://semaphoreci.com/docs/available-environment-variables.html#variables-exported-in-builds-and-deploys <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # flagged-respawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A tool for respawning node binaries when special flags are present. ## What is it? Say you wrote a command line tool that runs arbitrary javascript (e.g. task runner, test framework, etc). For the sake of discussion, let's pretend it's a testing harness you've named `testify`. Everything is going splendidly until one day you decide to test some code that relies on a feature behind a v8 flag in node (`--harmony`, for example). Without much thought, you run `testify --harmony spec tests.js`. It doesn't work. After digging around for a bit, you realize this produces a [`process.argv`](http://nodejs.org/docs/latest/api/process.html#process_process_argv) of: `['node', '/usr/local/bin/test', '--harmony', 'spec', 'tests.js']` Crap. The `--harmony` flag is in the wrong place! It should be applied to the **node** command, not our binary. What we actually wanted was this: `['node', '--harmony', '/usr/local/bin/test', 'spec', 'tests.js']` Flagged-respawn fixes this problem and handles all the edge cases respawning creates, such as: - Providing a method to determine if a respawn is needed. - Piping stderr/stdout from the child into the parent. - Making the parent process exit with the same code as the child. - If the child is killed, making the parent exit with the same signal. To see it in action, clone this repository and run `npm install` / `npm run respawn` / `npm run nospawn`. ## Sample Usage ```js #!/usr/bin/env node const flaggedRespawn = require('flagged-respawn'); // get a list of all possible v8 flags for the running version of node const v8flags = require('v8flags').fetch(); flaggedRespawn(v8flags, process.argv, function (ready, child) { if (ready) { console.log('Running!'); // your cli code here } else { console.log('Special flags found, respawning.'); } if (process.pid !== child.pid) { console.log('Respawned to PID:', child.pid); } }); ``` ## API ### <u>flaggedRespawn(flags, argv, [ forcedFlags, ] callback) : Void</u> Respawns the script itself when *argv* has special flag contained in *flags* and/or *forcedFlags* is not empty. Because members of *flags* and *forcedFlags* are passed to `node` command, each of them needs to be a node flag or a V8 flag. #### Forbid respawning If `--no-respawning` flag is given in *argv*, this function does not respawned even if *argv* contains members of flags or *forcedFlags* is not empty. (This flag is also used internally to prevent from respawning more than once). #### Parameter: | Parameter | Type | Description | |:--------------|:------:|:----------------------------------------------------| | *flags* | Array | An array of node flags and V8 flags which are available when present in *argv*. | | *argv* | Array | Command line arguments to respawn. | | *forcedFlags* | Array or String | An array of node flags or a string of a single flag and V8 flags for respawning forcely. | | *callback* | function | A called function when not respawning or after respawned. | * **<u><i>callback</i>(ready, proc, argv) : Void</u>** *callback* function is called both when respawned or not, and it can be distinguished by callback's argument: *ready*. (*ready* indicates whether a process spawned its child process (false) or not (true), but it does not indicate whether a process is a spawned child process or not. *ready* for a spawned child process is true.) *argv* is an array of command line arguments which is respawned (when *ready* is false) or is passed current process except flags within *flags* and `--no-respawning` (when *ready* is true). **Parameter:** | Parameter | Type | Description | |:----------|:-------:|:--------------------------| | *ready* | boolean | True, if not respawning and is ready to execute main function. | | *proc* | object | Child process object if respawned, otherwise current process object. | | *argv* | Array | An array of command line arguments. | ## License MIT [downloads-image]: http://img.shields.io/npm/dm/flagged-respawn.svg [npm-url]: https://www.npmjs.com/package/flagged-respawn [npm-image]: http://img.shields.io/npm/v/flagged-respawn.svg [travis-url]: https://travis-ci.org/gulpjs/flagged-respawn [travis-image]: http://img.shields.io/travis/gulpjs/flagged-respawn.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/flagged-respawn [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/flagged-respawn.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/flagged-respawn [coveralls-image]: http://img.shields.io/coveralls/gulpjs/flagged-respawn/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # node-hid - Access USB HID devices from Node.js # [![npm](https://img.shields.io/npm/dm/node-hid.svg?maxAge=2592000)](http://npmjs.com/package/node-hid) [![build macos](https://github.com/node-hid/node-hid/workflows/macos/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Amacos) [![build windows](https://github.com/node-hid/node-hid/workflows/windows/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Awindows) [![build linux](https://github.com/node-hid/node-hid/workflows/linux/badge.svg)](https://github.com/node-hid/node-hid/actions?query=workflow%3Alinux) * [node-hid - Access USB HID devices from Node.js](#node-hid---access-usb-hid-devices-from-nodejs) * [Platform Support](#platform-support) * [Supported Platforms](#supported-platforms) * [Supported Node versions](#supported-node-versions) * [Supported Electron versions](#supported-electron-versions) * [Installation](#installation) * [Installation Special Cases](#installation-special-cases) * [Examples](#examples) * [Usage](#usage) * [List all HID devices connected](#list-all-hid-devices-connected) * [Cost of HID.devices() and <code>new HID.HID()</code> for detecting device plug/unplug](#cost-of-hiddevices-and-new-hidhid-for-detecting-device-plugunplug) * [Opening a device](#opening-a-device) * [Picking a device from the device list](#picking-a-device-from-the-device-list) * [Reading from a device](#reading-from-a-device) * [Writing to a device](#writing-to-a-device) * [Complete API](#complete-api) * [devices = HID.devices()](#devices--hiddevices) * [HID.setDriverType(type)](#hidsetdrivertypetype) * [device = new HID.HID(path)](#device--new-hidhidpath) * [device = new HID.HID(vid,pid)](#device--new-hidhidvidpid) * [device.on('data', function(data) {} )](#deviceondata-functiondata--) * [device.on('error, function(error) {} )](#deviceonerror-functionerror--) * [device.write(data)](#devicewritedata) * [device.close()](#deviceclose) * [device.pause()](#devicepause) * [device.resume()](#deviceresume) * [device.read(callback)](#devicereadcallback) * [device.readSync()](#devicereadsync) * [device.readTimeout(time_out)](#devicereadtimeouttime_out) * [device.sendFeatureReport(data)](#devicesendfeaturereportdata) * [device.getFeatureReport(report_id, report_length)](#devicegetfeaturereportreport_id-report_length) * [device.setNonBlocking(no_block)](#devicesetnonblockingno_block) * [General notes:](#general-notes) * [Thread safety, Worker threads, Context-aware modules](#thread-safety-worker-threads-context-aware-modules) * [Devices node-hid cannot read](#devices-node-hid-cannot-read) * [Mac notes](#mac-notes) * [Windows notes](#windows-notes) * [Xbox 360 Controller on Windows 10](#xbox-360-controller-on-windows-10) * [Linux notes](#linux-notes) * [udev device permissions](#udev-device-permissions) * [Selecting driver type](#selecting-driver-type) * [Compiling from source](#compiling-from-source) * [Linux (kernel 2.6 ) : (install examples shown for Debian/Ubuntu)](#linux-kernel-26--install-examples-shown-for-debianubuntu) * [FreeBSD](#freebsd) * [Mac OS X 10.8 ](#mac-os-x-108) * [Windows 7, 8, 10](#windows-7-8-10) * [Building node-hid from source, for your projects](#building-node-hid-from-source-for-your-projects) * [Build node-hid for <code>node-hid</code> development](#build-node-hid-for-node-hid-development) * [Building node-hid for cross-compiling](#building-node-hid-for-cross-compiling) * [Electron projects using node-hid](#electron-projects-using-node-hid) * [NW.js projects using node-hid](#nwjs-projects-using-node-hid) * [Support](#support) ## Platform Support `node-hid` supports Node.js v6 and upwards. For versions before that, you will need to build from source. The platforms, architectures and node versions `node-hid` supports are the following. In general we try to provide pre-built native library binaries for the most common platforms, Node and Electron versions. We strive to make `node-hid` cross-platform so there's a good chance any combination not listed here will compile and work. ### Supported Platforms ### - Windows x86 (32-bit) (¹) - Windows x64 (64-bit) - Mac OSX 10.9+ - Linux x64 (²) - Linux x86 (¹) - Linux ARM / Raspberry Pi (¹) - Linux MIPSel (¹) - Linux PPC64 (¹) ¹ prebuilt-binaries not provided for these platforms ² prebuilt binary built on Ubuntu 18.04 x64 ### Supported Node versions ### * Node v8 to * Node v16 ### Supported Electron versions ### * Electron v3 to * Electron v16 Future versions of Node or Electron should work, since `node-hid` is now based on NAPI. ## Installation For most "standard" use cases (macOS, Windows, Linux x86), `node-hid` will install like a standard npm package: ``` npm install node-hid ``` If you install globally, the test program `src/show-devices.js` is installed as `hid-showdevices`. On Linux you can use it to try the difference between `hidraw` and `libusb` driverTypes: ``` $ npm install -g node-hid $ hid-showdevices libusb $ hid-showdevices hidraw ``` ### Installation Special Cases We are using [prebuild](https://github.com/mafintosh/prebuild) to compile and post binaries of the library for most common use cases (Linux, MacOS, Windows on standard processor platforms). If a prebuild is not available, `node-hid` will work, but `npm install node-hid` will compile the binary when you install. For more details on compiler setup, see [Compling from source](#compiling-from-source) below. ## Examples In the `src/` directory, various JavaScript programs can be found that talk to specific devices in some way. Some interesting ones: - [`show-devices.js`](./src/show-devices.js) - display all HID devices in the system - [`test-ps3-rumbleled.js`](./src/test-ps3-rumbleled.js) - Read PS3 joystick and control its LED & rumblers - [`test-powermate.js`](./src/test-powermate.js) - Read Griffin PowerMate knob and change its LED - [`test-blink1.js`](./src/test-blink1.js) - Fade colors on blink(1) RGB LED - [`test-bigredbutton.js`](./src/test-bigredbutton.js) - Read Dreamcheeky Big Red Button - [`test-teensyrawhid.js`](./src/test-teensyrawhid.js) - Read/write Teensy running RawHID "Basic" Arduino sketch To try them out, run them with `node src/showdevices.js` from within the node-hid directory. ---- ## Usage ### List all HID devices connected ```js var HID = require('node-hid'); var devices = HID.devices(); ``` `devices` will contain an array of objects, one for each HID device available. Of particular interest are the `vendorId` and `productId`, as they uniquely identify a device, and the `path`, which is needed to open a particular device. Sample output: ```js HID.devices(); { vendorId: 10168, productId: 493, path: 'IOService:/AppleACPIPl...HIDDevice@14210000,0', serialNumber: '20002E8C', manufacturer: 'ThingM', product: 'blink(1) mk2', release: 2, interface: -1, usagePage: 65280, usage: 1 }, { vendorId: 1452, productId: 610, path: 'IOService:/AppleACPIPl...Keyboard@14400000,0', serialNumber: '', manufacturer: 'Apple Inc.', product: 'Apple Internal Keyboard / Trackpad', release: 549, interface: -1, usagePage: 1, usage: 6 }, <and more> ``` #### Cost of `HID.devices()` and `new HID.HID()` for detecting device plug/unplug Both `HID.devices()` and `new HID.HID()` are relatively costly, each causing a USB (and potentially Bluetooth) enumeration. This takes time and OS resources. Doing either can slow down the read/write that you do in parallel with a device, and cause other USB devices to slow down too. This is how USB works. If you are polling `HID.devices()` or doing repeated `new HID.HID(vid,pid)` to detect device plug / unplug, consider instead using [node-usb-detection](https://github.com/MadLittleMods/node-usb-detection). `node-usb-detection` uses OS-specific, non-bus enumeration ways to detect device plug / unplug. ### Opening a device Before a device can be read from or written to, it must be opened. The `path` can be determined by a prior HID.devices() call. Use either the `path` from the list returned by a prior call to `HID.devices()`: ```js var device = new HID.HID(path); ``` or open the first device matching a VID/PID pair: ```js var device = new HID.HID(vid,pid); ``` The `device` variable will contain a handle to the device. If an error occurs opening the device, an exception will be thrown. A `node-hid` device is an `EventEmitter`. While it shares some method names and usage patterns with `Readable` and `Writable` streams, it is not a stream and the semantics vary. For example, `device.write` does not take encoding or callback args and `device.pause` does not do the same thing as `readable.pause`. There is also no `pipe` method. ### Picking a device from the device list If you need to filter down the `HID.devices()` list, you can use standard Javascript array techniques: ```js var devices = HID.devices(); var deviceInfo = devices.find( function(d) { var isTeensy = d.vendorId===0x16C0 && d.productId===0x0486; return isTeensy && d.usagePage===0xFFAB && d.usage===0x200; }); if( deviceInfo ) { var device = new HID.HID( deviceInfo.path ); // ... use device } ``` ### Reading from a device To receive FEATURE reports, use `device.getFeatureReport()`. To receive INPUT reports, use `device.on("data",...)`. A `node-hid` device is an EventEmitter. Reading from a device is performed by registering a "data" event handler: ```js device.on("data", function(data) {}); ``` You can also listen for errors like this: ```js device.on("error", function(err) {}); ``` For FEATURE reports: ```js var buf = device.getFeatureReport(reportId, reportLength) ``` Notes: - Reads via `device.on("data")` are asynchronous - Reads via `device.getFeatureReport()` are synchronous - To remove an event handler, close the device with `device.close()` - When there is not yet a data handler or no data handler exists, data is not read at all -- there is no buffer. ### Writing to a device To send FEATURE reports, use `device.sendFeatureReport()`. To send OUTPUT reports, use `device.write()`. All writing is synchronous. The ReportId is the first byte of the array sent to `device.sendFeatureReport()` or `device.write()`, meaning the array should be one byte bigger than your report. If your device does NOT use numbered reports, set the first byte of the 0x00. ```js device.write([0x00, 0x01, 0x01, 0x05, 0xff, 0xff]); ``` ```js device.sendFeatureReport( [0x01, 'c', 0, 0xff,0x33,0x00, 70,0, 0] ); ``` Notes: - You must send the exact number of bytes for your chosen OUTPUT or FEATURE report. - Both `device.write()` and `device.sendFeatureReport()` return number of bytes written + 1. - For devices using Report Ids, the first byte of the array to `write()` or `sendFeatureReport()` must be the Report Id. ## Complete API ### `devices = HID.devices()` - Return array listing all connected HID devices ### `HID.setDriverType(type)` - Linux only - Sets underlying HID driver type - `type` can be `"hidraw"` or `"libusb"`, defaults to `"hidraw"` ### `device = new HID.HID(path)` - Open a HID device at the specified platform-specific path ### `device = new HID.HID(vid,pid)` - Open first HID device with specific VendorId and ProductId ### `device.on('data', function(data) {} )` - `data` - Buffer - the data read from the device ### `device.on('error, function(error) {} )` - `error` - The error Object emitted ### `device.write(data)` - `data` - the data to be synchronously written to the device, first byte is Report Id or 0x00 if not using numbered reports. - Returns number of bytes actually written ### `device.close()` - Closes the device. Subsequent reads will raise an error. ### `device.pause()` - Pauses reading and the emission of `data` events. This means the underlying device is _silenced_ until resumption -- it is not like pausing a stream, where data continues to accumulate. ### `device.resume()` - This method will cause the HID device to resume emmitting `data` events. If no listeners are registered for the `data` event, data will be lost. - When a `data` event is registered for this HID device, this method will be automatically called. ### `device.read(callback)` - Low-level function call to initiate an asynchronous read from the device. - `callback` is of the form `callback(err, data)` ### `device.readSync()` - Return an array of numbers data. If an error occurs, an exception will be thrown. ### `device.readTimeout(time_out)` - `time_out` - timeout in milliseconds - Return an array of numbers data. If an error occurs, an exception will be thrown. ### `device.sendFeatureReport(data)` - `data` - data of HID feature report, with 0th byte being report_id (`[report_id,...]`) - Returns number of bytes actually written ### `device.getFeatureReport(report_id, report_length)` - `report_id` - HID feature report id to get - `report_length` - length of report ### `device.setNonBlocking(no_block)` - `no_block` - boolean. Set to `true` to enable non-blocking reads - exactly mirrors `hid_set_nonblocking()` in [`hidapi`](https://github.com/libusb/hidapi) ----- ## General notes: ### Thread safety, Worker threads, Context-aware modules In general `node-hid` is not thread-safe because the underlying C-library it wraps (`hidapi`) is not thread-safe. However, `node-hid` is now reporting as minimally Context Aware to allow use in Electron v9+. Until `node-hid` (or `hidapi`) is rewritten to be thread-safe, please constrain all accesses to it via a single thread. ### Devices `node-hid` cannot read The following devices are unavailable to `node-hid` because the OS owns them: - Keyboards - Mice - Barcode readers (in USB HID keyboard mode) - RFID scanners (in USB HID keyboard mode) - Postage Scales (in USB HID keyboard mode) Most OSes will prevent USB HID keyboards or mice, or devices that appear as a keyboard to the OS. This includes many RFID scanners, barcode readers, USB HID scales, and many other devices. This is a security precaution. Otherwise, it would be trivial to build keyloggers. Some keyboard-pretending devices like barcode or RFID readers can be configured to be in "HID data" mode or "Serial / UART" mode. If in "HID Data" mode then `node-hid` can access them, if in "Serial / UART" mode, you should use `node-serialport` instead. ## Mac notes See General notes above Keyboards ## Windows notes See General notes above about Keyboards ### Xbox 360 Controller on Windows 10 For reasons similar to mice & keyboards it appears you can't access this controller on Windows 10. ## Linux notes See General notes above about Keyboards ### udev device permissions Most Linux distros use `udev` to manage access to physical devices, and USB HID devices are normally owned by the `root` user. To allow non-root access, you must create a udev rule for the device, based on the devices vendorId and productId. This rule is a text file placed in `/etc/udev/rules.d`. For an example HID device (say a blink(1) light with vendorId = 0x27b8 and productId = 0x01ed, the rules file to support both `hidraw` and `libusb` would look like: ``` SUBSYSTEM=="input", GROUP="input", MODE="0666" SUBSYSTEM=="usb", ATTRS{idVendor}=="27b8", ATTRS{idProduct}=="01ed", MODE:="666", GROUP="plugdev" KERNEL=="hidraw*", ATTRS{idVendor}=="27b8", ATTRS{idProduct}=="01ed", MODE="0666", GROUP="plugdev" ``` Note that the values for idVendor and idProduct must be in hex and lower-case. Save this file as `/etc/udev/rules.d/51-blink1.rules`, unplug the HID device, and reload the rules with: ``` sudo udevadm control --reload-rules ``` For a complete example, see the [blink1 udev rules](https://github.com/todbot/blink1/blob/master/linux/51-blink1.rules). ### Selecting driver type By default as of `[email protected]`, the [hidraw](https://www.kernel.org/doc/Documentation/hid/hidraw.txt) driver is used to talk to HID devices. Before `[email protected]`, the more older but less capable [libusb](http://libusb.info/) driver was used. With `hidraw` Linux apps can now see `usage` and `usagePage` attributes of devices. If you would still like to use the `libusb` driver, then you can do either: During runtime, you can use `HID.setDriverType('libusb')` immediately after require()-ing `node-hid`: ```js var HID = require('node-hid'); HID.setDriverType('libusb'); ``` If you must have the libusb version and cannot use `setDriverType()`, you can install older node-hid or build from source: ``` npm install [email protected] ``` or: ``` npm install node-hid --build-from-source --driver=libusb ``` ## Compiling from source To compile & develop locally or if `prebuild` cannot download a pre-built binary for you, you will need the following compiler tools and libraries: ### Linux (kernel 2.6+) : (install examples shown for Debian/Ubuntu) * Compilation tools: `apt install build-essential git pkg-config` * libudev-dev: `apt install libudev-dev` (Debian/Ubuntu) / `yum install libusbx-devel` (Fedora) * libusb-1.0-0 w/headers:`apt install libusb-1.0-0 libusb-1.0-0-dev` ### FreeBSD * Compilation tools: `pkg install git gcc gmake libiconv node npm` ### Mac OS X 10.8+ * [Xcode](https://itunes.apple.com/us/app/xcode/id497799835?mt=12) ### Windows 7, 8, 10 The below is slightly stale. The 2021 solution is to use the official NodeJs Windows installer and pick "install native module tools" * Visual C++ compiler and Python 2.7 * either: * `npm install --global windows-build-tools` * add `%USERPROFILE%\.windows-build-tools\python27` to `PATH`, like PowerShell: `$env:Path += ";$env:USERPROFILE\.windows-build-tools\python27"` * or: * [Python 2.7](https://www.python.org/downloads/windows/) * [Visual Studio Express 2013 for Desktop](https://www.visualstudio.com/downloads/download-visual-studio-vs#d-2013-express) ### Building `node-hid` from source, for your projects ``` npm install node-hid --build-from-source ``` ### Build `node-hid` for `node-hid` development * check out a copy of this repo * change into its directory * update the submodules * build the node package For example: ``` git clone https://github.com/node-hid/node-hid.git cd node-hid # must change into node-hid directory npm install -g rimraf # just so it doesn't get 'clean'ed npm run prepublishOnly # get the needed hidapi submodule npm install --build-from-source # rebuilds the module with C code npm run showdevices # list connected HID devices node ./src/show-devices.js # same as above ``` You may see some warnings from the C compiler as it compiles [hidapi](https://github.com/libusb/hidapi) (the underlying C library `node-hid` uses). This is expected. For ease of development, there are also the scripts: ``` npm run gypclean # "node-gyp clean" clean gyp build directory npm run gypconfigure # "node-gyp configure" configure makefiles npm run gypbuild # "node-gyp build" build native code ``` ### Building `node-hid` for cross-compiling When cross-compiling you need to override `node-hid`'s normal behavior of using Linux `pkg-config` to determine CLFAGS and LDFLAGS for `libusb`. To do this, you can use the `node-gyp` variable `node_hid_no_pkg_config` and then invoke a `node-hid` rebuild with either: ``` node-gyp rebuild --node_hid_no_pkg_config=1 ``` or ``` npm gyprebuild --node_hid_no_pkg_config=1 ``` ## Electron projects using `node-hid` In your electron project, add `electron-rebuild` to your `devDependencies`. Then in your package.json `scripts` add: ``` "postinstall": "electron-rebuild" ``` This will cause `npm` to rebuild `node-hid` for the version of Node that is in Electron. If you get an error similar to `The module "HID.node" was compiled against a different version of Node.js` then `electron-rebuild` hasn't been run and Electron is trying to use `node-hid` compiled for Node.js and not for Electron. If using `node-hid` with `webpack` or similar bundler, you may need to exclude `node-hid` and other libraries with native code. In webpack, you say which `externals` you have in your `webpack-config.js`: ``` externals: { "node-hid": 'commonjs node-hid' } ``` Examples of `node-hid` in Electron: * [electron-hid-test](https://github.com/todbot/electron-hid-test) - Simple example of using `node-hid`, should track latest Electron release * [electron-hid-test-erb](https://github.com/todbot/electron-hid-test-erb) - Simple example of using `node-hid` using [electron-react-boilerplate](https://github.com/electron-react-boilerplate/electron-react-boilerplate/) * [electron-hid-toy](https://github.com/todbot/electron-hid-toy) - Simple example of using `node-hid`, showing packaging and signing * [Blink1Control2](https://github.com/todbot/Blink1Control2/) - a complete application, using webpack (e.g. see its [webpack-config.js](https://github.com/todbot/Blink1Control2/blob/master/webpack.config.js)) ## NW.js projects using `node-hid` Without knowing much about NW.js, a quick hacky solution that works is: ``` cd my-nwjs-app npm install node-hid --save npm install -g nw-gyp cd node_modules/node-hid nw-gyp rebuild --target=0.42.3 --arch=x64 // or whatever NW.js version you have cd ../.. nwjs . ``` ## Support Please use the [node-hid github issues page](https://github.com/node-hid/node-hid/issues) for support questions and issues. near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages # is-ci Returns `true` if the current environment is a Continuous Integration server. Please [open an issue](https://github.com/watson/is-ci/issues) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/is-ci.svg)](https://www.npmjs.com/package/is-ci) [![Build status](https://travis-ci.org/watson/is-ci.svg?branch=master)](https://travis-ci.org/watson/is-ci) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install is-ci --save ``` ## Programmatic Usage ```js const isCI = require('is-ci') if (isCI) { console.log('The code is running on a CI server') } ``` ## CLI Usage For CLI usage you need to have the `is-ci` executable in your `PATH`. There's a few ways to do that: - Either install the module globally using `npm install is-ci -g` - Or add the module as a dependency to your app in which case it can be used inside your package.json scripts as is - Or provide the full path to the executable, e.g. `./node_modules/.bin/is-ci` ```bash is-ci && echo "This is a CI server" ``` ## Supported CI tools Refer to [ci-info](https://github.com/watson/ci-info#supported-ci-tools) docs for all supported CI's ## License [MIT](LICENSE) # Ozone - Javascript Class Framework [![Build Status](https://travis-ci.org/inf3rno/o3.png?branch=master)](https://travis-ci.org/inf3rno/o3) The Ozone class framework contains enhanced class support to ease the development of object-oriented javascript applications in an ES5 environment. Another alternative to get a better class support to use ES6 classes and compilers like Babel, Traceur or TypeScript until native ES6 support arrives. ## Documentation ### Installation ```bash npm install o3 ``` ```bash bower install o3 ``` #### Environment compatibility The framework succeeded the tests on - node v4.2 and v5.x - chrome 51.0 - firefox 47.0 and 48.0 - internet explorer 11.0 - phantomjs 2.1 by the usage of npm scripts under win7 x64. I wasn't able to test the framework by Opera since the Karma launcher is buggy, so I decided not to support Opera. I used [Yadda](https://github.com/acuminous/yadda) to write BDD tests. I used [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. On pre-ES5 environments there will be bugs in the Class module due to pre-ES5 enumeration and the lack of some ES5 methods, so pre-ES5 environments are not supported. #### Requirements An ES5 capable environment is required with - `Object.create` - ES5 compatible property enumeration: `Object.defineProperty`, `Object.getOwnPropertyDescriptor`, `Object.prototype.hasOwnProperty`, etc. - `Array.prototype.forEach` #### Usage In this documentation I used the framework as follows: ```js var o3 = require("o3"), Class = o3.Class; ``` ### Inheritance #### Inheriting from native classes (from the Error class in these examples) You can extend native classes by calling the Class() function. ```js var UserError = Class(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` An alternative to call Class.extend() with the Ancestor as the context. The Class() function uses this in the background. ```js var UserError = Class.extend.call(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` #### Inheriting from custom classes You can use Class.extend() by any other class, not just by native classes. ```js var Ancestor = Class(Object, { prototype: { a: 1, b: 2 } }); var Descendant = Class.extend.call(Ancestor, { prototype: { c: 3 } }); ``` Or you can simply add it as a static method, so you don't have to pass context any time you want to use it. The only drawback, that this static method will be inherited as well. ```js var Ancestor = Class(Object, { extend: Class.extend, prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheriting from the Class class You can inherit the extend() method and other utility methods from the Class class. Probably this is the simplest solution if you need the Class API and you don't need to inherit from special native classes like Error. ```js var Ancestor = Class.extend({ prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheritance with clone and merge The static extend() method uses the clone() and merge() utility methods to inherit from the ancestor and add properties from the config. ```js var MyClass = Class.clone.call(Object, function MyClass(){ // ... }); Class.merge.call(MyClass, { prototype: { x: 1, y: 2 } }); ``` Or with utility methods. ```js var MyClass = Class.clone(function MyClass() { // ... }).merge({ prototype: { x: 1, y: 2 } }); ``` #### Inheritance with clone and absorb You can fill in missing properties with the usage of absorb. ```js var MyClass = Class(SomeAncestor, {...}); Class.absorb.call(MyClass, Class); MyClass.merge({...}); ``` For example if you don't have Class methods and your class already has an ancestor, then you can use absorb() to add Class methods. #### Abstract classes Using abstract classes with instantiation verification won't be implemented in this lib, however we provide an `abstractMethod`, which you can put to not implemented parts of your abstract class. ```js var AbstractA = Class({ prototype: { doA: function (){ // ... var b = this.getB(); // ... // do something with b // ... }, getB: abstractMethod } }); var AB1 = Class(AbstractA, { prototype: { getB: function (){ return new B1(); } } }); var ab1 = new AB1(); ``` I strongly support the composition over inheritance principle and I think you should use dependency injection instead of abstract classes. ```js var A = Class({ prototype: { init: function (b){ this.b = b; }, doA: function (){ // ... // do something with this.b // ... } } }); var b = new B1(); var ab1 = new A(b); ``` ### Constructors #### Using a custom constructor You can pass your custom constructor as a config option by creating the class. ```js var MyClass = Class(Object, { prototype: { constructor: function () { // ... } } }); ``` #### Using a custom factory to create the constructor Or you can pass a static factory method to create your custom constructor. ```js var MyClass = Class(Object, { factory: function () { return function () { // ... } } }); ``` #### Using an inherited factory to create the constructor By inheritance the constructors of the descendant classes will be automatically created as well. ```js var Ancestor = Class(Object, { factory: function () { return function () { // ... } } }); var Descendant = Class(Ancestor, {}); ``` #### Using the default factory to create the constructor You don't need to pass anything if you need a noop function as constructor. The Class.factory() will create a noop constructor by default. ```js var MyClass = Class(Object, {}); ``` In fact you don't need to pass any arguments to the Class function if you need an empty class inheriting from the Object native class. ```js var MyClass = Class(); ``` The default factory calls the build() and init() methods if they are given. ```js var MyClass = Class({ prototype: { build: function (options) { console.log("build", options); }, init: function (options) { console.log("init", options); } } }); var my = new MyClass({a: 1, b: 2}); // build {a: 1, b: 2} // init {a: 1, b: 2} var my2 = my.clone({c: 3}); // build {c: 3} var MyClass2 = MyClass.extend({}, [{d: 4}]); // build {d: 4} ``` ### Instantiation #### Creating new instance with the new operator Ofc. you can create a new instance in the javascript way. ```js var MyClass = Class(); var my = new MyClass(); ``` #### Creating a new instance with the static newInstance method If you want to pass an array of arguments then you can do it the following way. ```js var MyClass = Class.extend({ prototype: { constructor: function () { for (var i in arguments) console.log(arguments[i]); } } }); var my = MyClass.newInstance.apply(MyClass, ["a", "b", "c"]); // a // b // c ``` #### Creating new instance with clone You can create a new instance by cloning the prototype of the class. ```js var MyClass = Class(); var my = Class.prototype.clone.call(MyClass.prototype); ``` Or you can inherit the utility methods to make this easier. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); ``` Just be aware that by default cloning calls only the `build()` method, so the `init()` method won't be called by the new instance. #### Cloning instances You can clone an existing instance with the clone method. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); var my2 = my.clone(); ``` Be aware that this is prototypal inheritance with Object.create(), so the inherited properties won't be enumerable. The clone() method calls the build() method on the new instance if it is given. #### Using clone in the constructor You can use the same behavior both by cloning and by creating a new instance using the constructor ```js var MyClass = Class.extend({ lastIndex: 0, prototype: { index: undefined, constructor: function MyClass() { return MyClass.prototype.clone(); }, clone: function () { var instance = Class.prototype.clone.call(this); instance.index = ++MyClass.lastIndex; return instance; } } }); var my1 = new MyClass(); var my2 = MyClass.prototype.clone(); var my3 = my1.clone(); var my4 = my2.clone(); ``` Be aware that this way the constructor will drop the instance created with the `new` operator. Be aware that the clone() method is used by inheritance, so creating the prototype of a descendant class will use the clone() method as well. ```js var Descendant = MyClass.clone(function Descendant() { return Descendant.prototype.clone(); }); var my5 = Descendant.prototype; var my6 = new Descendant(); // ... ``` #### Using absorb(), merge() or inheritance to set the defaults values on properties You can use absorb() to set default values after configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(config); this.absorb(theDefaults); } } }); ``` You can use merge() to set default values before configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(theDefaults); this.merge(config); } } }); ``` You can use inheritance to set default values on class level. ```js var MyClass = Class.extend({ prototype: { aProperty: defaultValue, // ... constructor: function (config) { this.merge(config); } } }); ``` ## License MIT - 2015 Jánszky László Lajos # binary-parse-stream Painless streaming binary protocol parsers using generators. ## Installation npm install binary-parse-stream ## Synchronous This module uses the exact same generator interface as [binary-parse-stream](https://github.com/nathan7/binary-parse-stream), which presents a synchronous interface to a generator parser. ## Usage ```js const BinaryParseStream = require('binary-parse-stream') const {One} = BinaryParseStream // -1 ``` BinaryParseStream is a TransformStream that consumes buffers and outputs objects on the other end. It expects your subclass to implement a `_parse` method that is a generator. When your generator yields a number, it'll be fed a buffer of that length from the input. If it yields -1, it'll be given the value of the first byte instead of a single-byte buffer. When your generator returns, the return value will be pushed to the output side. ## Example The following module parses a protocol that consists of a 32-bit unsigned big-endian type parameter, an unsigned 8-bit length parameter, and a buffer of the specified length. It outputs `{type, buf}` objects. ```js class SillyProtocolParseStream extends BinaryParseStream { constructor(options) { super(options) this.count = 0 } *_parse() { const type = (yield 4).readUInt32BE(0, true) const length = yield -1 const buf = yield length this.count++ return {type, buf} } } ``` There is also a shorter syntax for when you don't want to explicitly subclass: `BinaryParseStream.extend(function*())`. # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/buffer/master.svg [travis-url]: https://travis-ci.org/feross/buffer [npm-image]: https://img.shields.io/npm/v/buffer.svg [npm-url]: https://npmjs.org/package/buffer [downloads-image]: https://img.shields.io/npm/dm/buffer.svg [downloads-url]: https://npmjs.org/package/buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### The buffer module from [node.js](https://nodejs.org/), for the browser. [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg [saucelabs-url]: https://saucelabs.com/u/buffer With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. The goal is to provide an API that is 100% identical to [node's Buffer API](https://nodejs.org/api/buffer.html). Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. ## features - Manipulate binary data like a boss, in all browsers! - Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) - Extremely small bundle size (**6.75KB minified + gzipped**, 51.9KB with comments) - Excellent browser support (Chrome, Firefox, Edge, Safari 9+, IE 11, iOS 9+, Android, etc.) - Preserves Node API exactly, with one minor difference (see below) - Square-bracket `buf[4]` notation works! - Does not modify any browser prototypes or put anything on `window` - Comprehensive test suite (including all buffer tests from node.js core) ## install To use this module directly (without browserify), install it: ```bash npm install buffer ``` This module was previously called **native-buffer-browserify**, but please use **buffer** from now on. If you do not use a bundler, you can use the [standalone script](https://bundle.run/buffer). ## usage The module's API is identical to node's `Buffer` API. Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. As mentioned above, `require('buffer')` or use the `Buffer` global with [browserify](http://browserify.org) and this module will automatically be included in your bundle. Almost any npm module will work in the browser, even if it assumes that the node `Buffer` API will be available. To depend on this module explicitly (without browserify), require it like this: ```js var Buffer = require('buffer/').Buffer // note: the trailing slash is important! ``` To require this module explicitly, use `require('buffer/')` which tells the node.js module lookup algorithm (also used by browserify) to use the **npm module** named `buffer` instead of the **node.js core** module named `buffer`! ## how does it work? The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified. ## tracking the latest node api This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer API is considered **stable** in the [node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), so it is unlikely that there will ever be breaking changes. Nonetheless, when/if the Buffer API changes in node, this module's API will change accordingly. ## related packages - [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - Reverse a buffer - [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - Bitwise xor a buffer - [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package ## conversion packages ### convert typed array to buffer Use [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) to convert any kind of typed array to a `Buffer`. Does not perform a copy, so it's super fast. ### convert buffer to typed array `Buffer` is a subclass of `Uint8Array` (which is a typed array). So there is no need to explicitly convert to typed array. Just use the buffer as a `Uint8Array`. ### convert blob to buffer Use [`blob-to-buffer`](https://www.npmjs.com/package/blob-to-buffer) to convert a `Blob` to a `Buffer`. ### convert buffer to blob To convert a `Buffer` to a `Blob`, use the `Blob` constructor: ```js var blob = new Blob([ buffer ]) ``` Optionally, specify a mimetype: ```js var blob = new Blob([ buffer ], { type: 'text/html' }) ``` ### convert arraybuffer to buffer To convert an `ArrayBuffer` to a `Buffer`, use the `Buffer.from` function. Does not perform a copy, so it's super fast. ```js var buffer = Buffer.from(arrayBuffer) ``` ### convert buffer to arraybuffer To convert a `Buffer` to an `ArrayBuffer`, use the `.buffer` property (which is present on all `Uint8Array` objects): ```js var arrayBuffer = buffer.buffer.slice( buffer.byteOffset, buffer.byteOffset + buffer.byteLength ) ``` Alternatively, use the [`to-arraybuffer`](https://www.npmjs.com/package/to-arraybuffer) module. ## performance See perf tests in `/perf`. `BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, which is included to compare against. NOTE: Performance has improved since these benchmarks were taken. PR welcome to update the README. ### Chrome 38 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | | Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | | | | | | | BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | | Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | | Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | | Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | | Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | | Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | | DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | | | | | | | BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | | DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | | | | | | | BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | | DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | | | | | | | BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | | Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | | DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | ### Firefox 33 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | | Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | | | | | | | BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | | Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | | Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | | Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | | Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | | | | | | | BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | | Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | | DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | | DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | | DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | | | | | | | BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | | Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | | DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | ### Safari 8 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | | Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | | | | | | | BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | | Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | | Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | | | | | | | BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | | Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | | | | | | | BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | | Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | | | | | | | BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | | Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | | DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | | DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | | DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | | | | | | | BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | | Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | | DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | ### Node 0.11.14 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | | Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | | NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | | | | | | | BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | | Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | | NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | | | | | | | BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | | Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | | NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | | | | | | | BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | | Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | | NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | | | | | | | BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | | Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | | NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | | Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | | NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | | | | | | | BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | | DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | | NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | | | | | | | BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | | DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | | NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | | | | | | | BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | | DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | | NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | | | | | | | BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | | Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | | NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | | | | | | | BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | | DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | | NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | ### iojs 1.8.1 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | | Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | | NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | | | | | | | BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | | Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | | NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | | Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | | NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | | | | | | | BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | | Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | | NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | | | | | | | BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | | Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | | NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | | Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | | NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | | | | | | | BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | | DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | | NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | | | | | | | BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | | DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | | NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | | | | | | | BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | | DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | | NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | | | | | | | BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | | Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | | NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | | DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | | NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | | | | | | ## Testing the project First, install the project: npm install Then, to run tests in Node.js, run: npm run test-node To test locally in a browser, you can run: npm run test-browser-es5-local # For ES5 browsers that don't support ES6 npm run test-browser-es6-local # For ES6 compliant browsers This will print out a URL that you can then open in a browser to run the tests, using [airtap](https://www.npmjs.com/package/airtap). To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: npm test This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `bin/airtap-es5.yml` and `bin/airtap-es6.yml` files. ## JavaScript Standard Style This module uses [JavaScript Standard Style](https://github.com/feross/standard). [![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) To test that the code conforms to the style, `npm install` and run: ./node_modules/.bin/standard ## credit This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). ## Security Policies and Procedures The `buffer` team and community take all security bugs in `buffer` seriously. Please see our [security policies and procedures](https://github.com/feross/security) document to learn how to report issues. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. file-uri-to-path ================ ### Convert a `file:` URI to a file path [![Build Status](https://travis-ci.org/TooTallNate/file-uri-to-path.svg?branch=master)](https://travis-ci.org/TooTallNate/file-uri-to-path) Accepts a `file:` URI and returns a regular file path suitable for use with the `fs` module functions. Installation ------------ Install with `npm`: ``` bash $ npm install file-uri-to-path ``` Example ------- ``` js var uri2path = require('file-uri-to-path'); uri2path('file://localhost/c|/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file:///c|/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file://localhost/c:/WINDOWS/clock.avi'); // "c:\\WINDOWS\\clock.avi" uri2path('file://hostname/path/to/the%20file.txt'); // "\\\\hostname\\path\\to\\the file.txt" uri2path('file:///c:/path/to/the%20file.txt'); // "c:\\path\\to\\the file.txt" ``` API --- ### fileUriToPath(String uri) → String License ------- (The MIT License) Copyright (c) 2014 Nathan Rajlich &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <p align="center"> <img width="250" src="https://raw.githubusercontent.com/yargs/yargs/master/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> ![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Coverage][coverage-image]][coverage-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments: ``` mocha [spec..] Run tests with Mocha Commands mocha inspect [spec..] Run tests with Mocha [default] mocha init <path> create a client-side Mocha setup at <path> Rules & Behavior --allow-uncaught Allow uncaught errors to propagate [boolean] --async-only, -A Require all tests to use a callback (async) or return a Promise [boolean] ``` * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next ``` ## Usage ### Simple Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') const argv = yargs(hideBin(process.argv)).argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ``` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node const yargs = require('yargs/yargs') const { hideBin } = require('yargs/helpers') yargs(hideBin(process.argv)) .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', type: 'boolean', description: 'Run with verbose logging' }) .argv ``` Run the example above with `--help` to see the help for the application. ## Supported Platforms ### TypeScript yargs has type definitions at [@types/yargs][type-definitions]. ``` npm i @types/yargs --save-dev ``` See usage examples in [docs](/docs/typescript.md). ### Deno As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): ```typescript import yargs from 'https://deno.land/x/yargs/deno.ts' import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' yargs(Deno.args) .command('download <files...>', 'download a list of files', (yargs: any) => { return yargs.positional('files', { describe: 'a list of files to do something with' }) }, (argv: Arguments) => { console.info(argv) }) .strictCommands() .demandCommand(1) .argv ``` ### ESM As of `v16`,`yargs` supports ESM imports: ```js import yargs from 'yargs' import { hideBin } from 'yargs/helpers' yargs(hideBin(process.argv)) .command('curl <url>', 'fetch the contents of the URL', () => {}, (argv) => { console.info(argv) }) .demandCommand(1) .argv ``` ### Usage in Browser See examples of using yargs in the browser in [docs](/docs/browser.md). ## Community Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Quotes](/docs/tricks.md#quotes) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Bundling yargs](/docs/bundling.md) * [Contributing](/contributing.md) ## Supported Node.js Versions Libraries in this ecosystem make a best effort to track [Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com [type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs [coverage-image]: https://img.shields.io/nycrc/yargs/yargs [coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc write-file-atomic ----------------- This is an extension for node's `fs.writeFile` that makes its operation atomic and allows you set ownership (uid/gid of the file). ### var writeFileAtomic = require('write-file-atomic')<br>writeFileAtomic(filename, data, [options], [callback]) * filename **String** * data **String** | **Buffer** * options **Object** | **String** * chown **Object** default, uid & gid of existing file, if any * uid **Number** * gid **Number** * encoding **String** | **Null** default = 'utf8' * fsync **Boolean** default = true * mode **Number** default, from existing file, if any * tmpfileCreated **Function** called when the tmpfile is created * callback **Function** Atomically and asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer. The file is initially named `filename + "." + murmurhex(__filename, process.pid, ++invocations)`. Note that `require('worker_threads').threadId` is used in addition to `process.pid` if running inside of a worker thread. If writeFile completes successfully then, if passed the **chown** option it will change the ownership of the file. Finally it renames the file back to the filename you specified. If it encounters errors at any of these steps it will attempt to unlink the temporary file and then pass the error back to the caller. If multiple writes are concurrently issued to the same file, the write operations are put into a queue and serialized in the order they were called, using Promises. Writes to different files are still executed in parallel. If provided, the **chown** option requires both **uid** and **gid** properties or else you'll get an error. If **chown** is not specified it will default to using the owner of the previous file. To prevent chown from being ran you can also pass `false`, in which case the file will be created with the current user's credentials. If **mode** is not specified, it will default to using the permissions from an existing file, if any. Expicitly setting this to `false` remove this default, resulting in a file created with the system default permissions. If options is a String, it's assumed to be the **encoding** option. The **encoding** option is ignored if **data** is a buffer. It defaults to 'utf8'. If the **fsync** option is **false**, writeFile will skip the final fsync call. If the **tmpfileCreated** option is specified it will be called with the name of the tmpfile when created. Example: ```javascript writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}, function (err) { if (err) throw err; console.log('It\'s saved!'); }); ``` This function also supports async/await: ```javascript (async () => { try { await writeFileAtomic('message.txt', 'Hello Node', {chown:{uid:100,gid:50}}); console.log('It\'s saved!'); } catch (err) { console.error(err); process.exit(1); } })(); ``` ### var writeFileAtomicSync = require('write-file-atomic').sync<br>writeFileAtomicSync(filename, data, [options]) The synchronous version of **writeFileAtomic**. # json-buffer JSON functions that can convert buffers! [![build status](https://secure.travis-ci.org/dominictarr/json-buffer.png)](http://travis-ci.org/dominictarr/json-buffer) [![testling badge](https://ci.testling.com/dominictarr/json-buffer.png)](https://ci.testling.com/dominictarr/json-buffer) JSON mangles buffers by converting to an array... which isn't helpful. json-buffers converts to base64 instead, and deconverts base64 to a buffer. ``` js var JSONB = require('json-buffer') var Buffer = require('buffer').Buffer var str = JSONB.stringify(new Buffer('hello there!')) console.log(JSONB.parse(str)) //GET a BUFFER back ``` ## License MIT An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` <h1 align=center> <a href="http://chaijs.com" title="Chai Documentation"> <img alt="ChaiJS" src="http://chaijs.com/img/chai-logo.png"/> type-detect </a> </h1> <br> <p align=center> Improved typeof detection for <a href="http://nodejs.org">node</a> and the browser. </p> <p align=center> <a href="./LICENSE"> <img alt="license:mit" src="https://img.shields.io/badge/license-mit-green.svg?style=flat-square" /> </a> <a href="https://github.com/chaijs/type-detect/releases"> <img alt="tag:?" src="https://img.shields.io/github/tag/chaijs/type-detect.svg?style=flat-square" /> </a> <a href="https://travis-ci.org/chaijs/type-detect"> <img alt="build:?" src="https://img.shields.io/travis/chaijs/type-detect/master.svg?style=flat-square" /> </a> <a href="https://coveralls.io/r/chaijs/type-detect"> <img alt="coverage:?" src="https://img.shields.io/coveralls/chaijs/type-detect/master.svg?style=flat-square" /> </a> <a href="https://www.npmjs.com/packages/type-detect"> <img alt="npm:?" src="https://img.shields.io/npm/v/type-detect.svg?style=flat-square" /> </a> <a href="https://www.npmjs.com/packages/type-detect"> <img alt="dependencies:?" src="https://img.shields.io/npm/dm/type-detect.svg?style=flat-square" /> </a> <a href=""> <img alt="devDependencies:?" src="https://img.shields.io/david/chaijs/type-detect.svg?style=flat-square" /> </a> <br/> <table> <tr><th colspan=6>Supported Browsers</th></tr> <tr> <th align=center><img src="https://camo.githubusercontent.com/ab586f11dfcb49bf5f2c2fa9adadc5e857de122a/687474703a2f2f73766773686172652e636f6d2f692f3278532e737667" alt=""> Chrome</th> <th align=center><img src="https://camo.githubusercontent.com/98cca3108c18dcfaa62667b42046540c6822cdac/687474703a2f2f73766773686172652e636f6d2f692f3279352e737667" alt=""> Edge</th> <th align=center><img src="https://camo.githubusercontent.com/acdcb09840a9e1442cbaf1b684f95ab3c3f41cf4/687474703a2f2f73766773686172652e636f6d2f692f3279462e737667" alt=""> Firefox</th> <th align=center><img src="https://camo.githubusercontent.com/728f8cb0bee9ed58ab85e39266f1152c53e0dffd/687474703a2f2f73766773686172652e636f6d2f692f3278342e737667" alt=""> Safari</th> <th align=center><img src="https://camo.githubusercontent.com/96a2317034dee0040d0a762e7a30c3c650c45aac/687474703a2f2f73766773686172652e636f6d2f692f3279532e737667" alt=""> IE</th> </tr><tr> <td align=center>✅</td> <td align=center>✅</td> <td align=center>✅</td> <td align=center>✅</td> <td align=center>9, 10, 11</td> </tr> </table> <br> <a href="https://chai-slack.herokuapp.com/"> <img alt="Join the Slack chat" src="https://img.shields.io/badge/slack-join%20chat-E2206F.svg?style=flat-square" /> </a> <a href="https://gitter.im/chaijs/chai"> <img alt="Join the Gitter chat" src="https://img.shields.io/badge/gitter-join%20chat-D0104D.svg?style=flat-square" /> </a> </p> ## What is Type-Detect? Type Detect is a module which you can use to detect the type of a given object. It returns a string representation of the object's type, either using [`typeof`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-typeof-operator) or [`@@toStringTag`](http://www.ecma-international.org/ecma-262/6.0/index.html#sec-symbol.tostringtag). It also normalizes some object names for consistency among browsers. ## Why? The `typeof` operator will only specify primitive values; everything else is `"object"` (including `null`, arrays, regexps, etc). Many developers use `Object.prototype.toString()` - which is a fine alternative and returns many more types (null returns `[object Null]`, Arrays as `[object Array]`, regexps as `[object RegExp]` etc). Sadly, `Object.prototype.toString` is slow, and buggy. By slow - we mean it is slower than `typeof`. By buggy - we mean that some values (like Promises, the global object, iterators, dataviews, a bunch of HTML elements) all report different things in different browsers. `type-detect` fixes all of the shortcomings with `Object.prototype.toString`. We have extra code to speed up checks of JS and DOM objects, as much as 20-30x faster for some values. `type-detect` also fixes any consistencies with these objects. ## Installation ### Node.js `type-detect` is available on [npm](http://npmjs.org). To install it, type: $ npm install type-detect ### Browsers You can also use it within the browser; install via npm and use the `type-detect.js` file found within the download. For example: ```html <script src="./node_modules/type-detect/type-detect.js"></script> ``` ## Usage The primary export of `type-detect` is function that can serve as a replacement for `typeof`. The results of this function will be more specific than that of native `typeof`. ```js var type = require('type-detect'); ``` #### array ```js assert(type([]) === 'Array'); assert(type(new Array()) === 'Array'); ``` #### regexp ```js assert(type(/a-z/gi) === 'RegExp'); assert(type(new RegExp('a-z')) === 'RegExp'); ``` #### function ```js assert(type(function () {}) === 'function'); ``` #### arguments ```js (function () { assert(type(arguments) === 'Arguments'); })(); ``` #### date ```js assert(type(new Date) === 'Date'); ``` #### number ```js assert(type(1) === 'number'); assert(type(1.234) === 'number'); assert(type(-1) === 'number'); assert(type(-1.234) === 'number'); assert(type(Infinity) === 'number'); assert(type(NaN) === 'number'); assert(type(new Number(1)) === 'Number'); // note - the object version has a capital N ``` #### string ```js assert(type('hello world') === 'string'); assert(type(new String('hello')) === 'String'); // note - the object version has a capital S ``` #### null ```js assert(type(null) === 'null'); assert(type(undefined) !== 'null'); ``` #### undefined ```js assert(type(undefined) === 'undefined'); assert(type(null) !== 'undefined'); ``` #### object ```js var Noop = function () {}; assert(type({}) === 'Object'); assert(type(Noop) !== 'Object'); assert(type(new Noop) === 'Object'); assert(type(new Object) === 'Object'); ``` #### ECMA6 Types All new ECMAScript 2015 objects are also supported, such as Promises and Symbols: ```js assert(type(new Map() === 'Map'); assert(type(new WeakMap()) === 'WeakMap'); assert(type(new Set()) === 'Set'); assert(type(new WeakSet()) === 'WeakSet'); assert(type(Symbol()) === 'symbol'); assert(type(new Promise(callback) === 'Promise'); assert(type(new Int8Array()) === 'Int8Array'); assert(type(new Uint8Array()) === 'Uint8Array'); assert(type(new UInt8ClampedArray()) === 'Uint8ClampedArray'); assert(type(new Int16Array()) === 'Int16Array'); assert(type(new Uint16Array()) === 'Uint16Array'); assert(type(new Int32Array()) === 'Int32Array'); assert(type(new UInt32Array()) === 'Uint32Array'); assert(type(new Float32Array()) === 'Float32Array'); assert(type(new Float64Array()) === 'Float64Array'); assert(type(new ArrayBuffer()) === 'ArrayBuffer'); assert(type(new DataView(arrayBuffer)) === 'DataView'); ``` Also, if you use `Symbol.toStringTag` to change an Objects return value of the `toString()` Method, `type()` will return this value, e.g: ```js var myObject = {}; myObject[Symbol.toStringTag] = 'myCustomType'; assert(type(myObject) === 'myCustomType'); ``` # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` Like `chown -R`. Takes the same arguments as `fs.chown()` # Ozone - Javascript Class Framework [![Build Status](https://travis-ci.org/inf3rno/o3.png?branch=master)](https://travis-ci.org/inf3rno/o3) The Ozone class framework contains enhanced class support to ease the development of object-oriented javascript applications in an ES5 environment. Another alternative to get a better class support to use ES6 classes and compilers like Babel, Traceur or TypeScript until native ES6 support arrives. ## Documentation ### Installation ```bash npm install o3 ``` ```bash bower install o3 ``` #### Environment compatibility The framework succeeded the tests on - node v4.2 and v5.x - chrome 51.0 - firefox 47.0 and 48.0 - internet explorer 11.0 - phantomjs 2.1 by the usage of npm scripts under win7 x64. I wasn't able to test the framework by Opera since the Karma launcher is buggy, so I decided not to support Opera. I used [Yadda](https://github.com/acuminous/yadda) to write BDD tests. I used [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. On pre-ES5 environments there will be bugs in the Class module due to pre-ES5 enumeration and the lack of some ES5 methods, so pre-ES5 environments are not supported. #### Requirements An ES5 capable environment is required with - `Object.create` - ES5 compatible property enumeration: `Object.defineProperty`, `Object.getOwnPropertyDescriptor`, `Object.prototype.hasOwnProperty`, etc. - `Array.prototype.forEach` #### Usage In this documentation I used the framework as follows: ```js var o3 = require("o3"), Class = o3.Class; ``` ### Inheritance #### Inheriting from native classes (from the Error class in these examples) You can extend native classes by calling the Class() function. ```js var UserError = Class(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` An alternative to call Class.extend() with the Ancestor as the context. The Class() function uses this in the background. ```js var UserError = Class.extend.call(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` #### Inheriting from custom classes You can use Class.extend() by any other class, not just by native classes. ```js var Ancestor = Class(Object, { prototype: { a: 1, b: 2 } }); var Descendant = Class.extend.call(Ancestor, { prototype: { c: 3 } }); ``` Or you can simply add it as a static method, so you don't have to pass context any time you want to use it. The only drawback, that this static method will be inherited as well. ```js var Ancestor = Class(Object, { extend: Class.extend, prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheriting from the Class class You can inherit the extend() method and other utility methods from the Class class. Probably this is the simplest solution if you need the Class API and you don't need to inherit from special native classes like Error. ```js var Ancestor = Class.extend({ prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheritance with clone and merge The static extend() method uses the clone() and merge() utility methods to inherit from the ancestor and add properties from the config. ```js var MyClass = Class.clone.call(Object, function MyClass(){ // ... }); Class.merge.call(MyClass, { prototype: { x: 1, y: 2 } }); ``` Or with utility methods. ```js var MyClass = Class.clone(function MyClass() { // ... }).merge({ prototype: { x: 1, y: 2 } }); ``` #### Inheritance with clone and absorb You can fill in missing properties with the usage of absorb. ```js var MyClass = Class(SomeAncestor, {...}); Class.absorb.call(MyClass, Class); MyClass.merge({...}); ``` For example if you don't have Class methods and your class already has an ancestor, then you can use absorb() to add Class methods. #### Abstract classes Using abstract classes with instantiation verification won't be implemented in this lib, however we provide an `abstractMethod`, which you can put to not implemented parts of your abstract class. ```js var AbstractA = Class({ prototype: { doA: function (){ // ... var b = this.getB(); // ... // do something with b // ... }, getB: abstractMethod } }); var AB1 = Class(AbstractA, { prototype: { getB: function (){ return new B1(); } } }); var ab1 = new AB1(); ``` I strongly support the composition over inheritance principle and I think you should use dependency injection instead of abstract classes. ```js var A = Class({ prototype: { init: function (b){ this.b = b; }, doA: function (){ // ... // do something with this.b // ... } } }); var b = new B1(); var ab1 = new A(b); ``` ### Constructors #### Using a custom constructor You can pass your custom constructor as a config option by creating the class. ```js var MyClass = Class(Object, { prototype: { constructor: function () { // ... } } }); ``` #### Using a custom factory to create the constructor Or you can pass a static factory method to create your custom constructor. ```js var MyClass = Class(Object, { factory: function () { return function () { // ... } } }); ``` #### Using an inherited factory to create the constructor By inheritance the constructors of the descendant classes will be automatically created as well. ```js var Ancestor = Class(Object, { factory: function () { return function () { // ... } } }); var Descendant = Class(Ancestor, {}); ``` #### Using the default factory to create the constructor You don't need to pass anything if you need a noop function as constructor. The Class.factory() will create a noop constructor by default. ```js var MyClass = Class(Object, {}); ``` In fact you don't need to pass any arguments to the Class function if you need an empty class inheriting from the Object native class. ```js var MyClass = Class(); ``` The default factory calls the build() and init() methods if they are given. ```js var MyClass = Class({ prototype: { build: function (options) { console.log("build", options); }, init: function (options) { console.log("init", options); } } }); var my = new MyClass({a: 1, b: 2}); // build {a: 1, b: 2} // init {a: 1, b: 2} var my2 = my.clone({c: 3}); // build {c: 3} var MyClass2 = MyClass.extend({}, [{d: 4}]); // build {d: 4} ``` ### Instantiation #### Creating new instance with the new operator Ofc. you can create a new instance in the javascript way. ```js var MyClass = Class(); var my = new MyClass(); ``` #### Creating a new instance with the static newInstance method If you want to pass an array of arguments then you can do it the following way. ```js var MyClass = Class.extend({ prototype: { constructor: function () { for (var i in arguments) console.log(arguments[i]); } } }); var my = MyClass.newInstance.apply(MyClass, ["a", "b", "c"]); // a // b // c ``` #### Creating new instance with clone You can create a new instance by cloning the prototype of the class. ```js var MyClass = Class(); var my = Class.prototype.clone.call(MyClass.prototype); ``` Or you can inherit the utility methods to make this easier. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); ``` Just be aware that by default cloning calls only the `build()` method, so the `init()` method won't be called by the new instance. #### Cloning instances You can clone an existing instance with the clone method. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); var my2 = my.clone(); ``` Be aware that this is prototypal inheritance with Object.create(), so the inherited properties won't be enumerable. The clone() method calls the build() method on the new instance if it is given. #### Using clone in the constructor You can use the same behavior both by cloning and by creating a new instance using the constructor ```js var MyClass = Class.extend({ lastIndex: 0, prototype: { index: undefined, constructor: function MyClass() { return MyClass.prototype.clone(); }, clone: function () { var instance = Class.prototype.clone.call(this); instance.index = ++MyClass.lastIndex; return instance; } } }); var my1 = new MyClass(); var my2 = MyClass.prototype.clone(); var my3 = my1.clone(); var my4 = my2.clone(); ``` Be aware that this way the constructor will drop the instance created with the `new` operator. Be aware that the clone() method is used by inheritance, so creating the prototype of a descendant class will use the clone() method as well. ```js var Descendant = MyClass.clone(function Descendant() { return Descendant.prototype.clone(); }); var my5 = Descendant.prototype; var my6 = new Descendant(); // ... ``` #### Using absorb(), merge() or inheritance to set the defaults values on properties You can use absorb() to set default values after configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(config); this.absorb(theDefaults); } } }); ``` You can use merge() to set default values before configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(theDefaults); this.merge(config); } } }); ``` You can use inheritance to set default values on class level. ```js var MyClass = Class.extend({ prototype: { aProperty: defaultValue, // ... constructor: function (config) { this.merge(config); } } }); ``` ## License MIT - 2015 Jánszky László Lajos # Arrgv Parsing string to array of args like node on bash do. [![Build Status][travis-image]][travis-url] [![NPM version][npm-image]][npm-url] When you type something like `node script.js bla bla bla` in shell and do `myArgs = process.argv.slice(2)` you get the same. All slashes, quotes and special symbols are handled same way. ## Install ```bash npm install arrgv ``` ## Tests ```bash $ npm test ``` ## Use cases 1. `spawn` a command that is given as a string 2. test `argv` parser with complicated example string 3. something else ## Example ```js var arrgv = require('arrgv'); var str = '-param --format="hh:mm:ss" filename.ext'; console.log(arrgv(str)); /* ['-param', '--format=hh:mm:ss', 'filename.ext' ] */ ``` ## License MIT [travis-url]: https://travis-ci.org/astur/arrgv [travis-image]: https://travis-ci.org/astur/arrgv.svg?branch=master [npm-url]: https://npmjs.org/package/arrgv [npm-image]: https://badge.fury.io/js/arrgv.svg # npmlog The logger util that npm uses. This logger is very basic. It does the logging for npm. It supports custom levels and colored output. By default, logs are written to stderr. If you want to send log messages to outputs other than streams, then you can change the `log.stream` member, or you can just listen to the events that it emits, and do whatever you want with them. # Installation ```console npm install npmlog --save ``` # Basic Usage ```javascript var log = require('npmlog') // additional stuff ---------------------------+ // message ----------+ | // prefix ----+ | | // level -+ | | | // v v v v log.info('fyi', 'I have a kitty cat: %j', myKittyCat) ``` ## log.level * {String} The level to display logs at. Any logs at or above this level will be displayed. The special level `silent` will prevent anything from being displayed ever. ## log.record * {Array} An array of all the log messages that have been entered. ## log.maxRecordSize * {Number} The maximum number of records to keep. If log.record gets bigger than 10% over this value, then it is sliced down to 90% of this value. The reason for the 10% window is so that it doesn't have to resize a large array on every log entry. ## log.prefixStyle * {Object} A style object that specifies how prefixes are styled. (See below) ## log.headingStyle * {Object} A style object that specifies how the heading is styled. (See below) ## log.heading * {String} Default: "" If set, a heading that is printed at the start of every line. ## log.stream * {Stream} Default: `process.stderr` The stream where output is written. ## log.enableColor() Force colors to be used on all messages, regardless of the output stream. ## log.disableColor() Disable colors on all messages. ## log.enableProgress() Enable the display of log activity spinner and progress bar ## log.disableProgress() Disable the display of a progress bar ## log.enableUnicode() Force the unicode theme to be used for the progress bar. ## log.disableUnicode() Disable the use of unicode in the progress bar. ## log.setGaugeTemplate(template) Set a template for outputting the progress bar. See the [gauge documentation] for details. [gauge documentation]: https://npmjs.com/package/gauge ## log.setGaugeThemeset(themes) Select a themeset to pick themes from for the progress bar. See the [gauge documentation] for details. ## log.pause() Stop emitting messages to the stream, but do not drop them. ## log.resume() Emit all buffered messages that were written while paused. ## log.log(level, prefix, message, ...) * `level` {String} The level to emit the message at * `prefix` {String} A string prefix. Set to "" to skip. * `message...` Arguments to `util.format` Emit a log message at the specified level. ## log\[level](prefix, message, ...) For example, * log.silly(prefix, message, ...) * log.verbose(prefix, message, ...) * log.info(prefix, message, ...) * log.http(prefix, message, ...) * log.warn(prefix, message, ...) * log.error(prefix, message, ...) Like `log.log(level, prefix, message, ...)`. In this way, each level is given a shorthand, so you can do `log.info(prefix, message)`. ## log.addLevel(level, n, style, disp) * `level` {String} Level indicator * `n` {Number} The numeric level * `style` {Object} Object with fg, bg, inverse, etc. * `disp` {String} Optional replacement for `level` in the output. Sets up a new level with a shorthand function and so forth. Note that if the number is `Infinity`, then setting the level to that will cause all log messages to be suppressed. If the number is `-Infinity`, then the only way to show it is to enable all log messages. ## log.newItem(name, todo, weight) * `name` {String} Optional; progress item name. * `todo` {Number} Optional; total amount of work to be done. Default 0. * `weight` {Number} Optional; the weight of this item relative to others. Default 1. This adds a new `are-we-there-yet` item tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `Tracker` object. ## log.newStream(name, todo, weight) This adds a new `are-we-there-yet` stream tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerStream` object. ## log.newGroup(name, weight) This adds a new `are-we-there-yet` tracker group to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerGroup` object. # Events Events are all emitted with the message object. * `log` Emitted for all messages * `log.<level>` Emitted for all messages with the `<level>` level. * `<prefix>` Messages with prefixes also emit their prefix as an event. # Style Objects Style objects can have the following fields: * `fg` {String} Color for the foreground text * `bg` {String} Color for the background * `bold`, `inverse`, `underline` {Boolean} Set the associated property * `bell` {Boolean} Make a noise (This is pretty annoying, probably.) # Message Objects Every log event is emitted with a message object, and the `log.record` list contains all of them that have been created. They have the following fields: * `id` {Number} * `level` {String} * `prefix` {String} * `message` {String} Result of `util.format()` * `messageRaw` {Array} Arguments to `util.format()` # Blocking TTYs We use [`set-blocking`](https://npmjs.com/package/set-blocking) to set stderr and stdout blocking if they are tty's and have the setBlocking call. This is a work around for an issue in early versions of Node.js 6.x, which made stderr and stdout non-blocking on OSX. (They are always blocking Windows and were never blocking on Linux.) `npmlog` needs them to be blocking so that it can allow output to stdout and stderr to be interlaced. # Read This! **These files are not meant to be edited by hand.** If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. Running `gulp LKG` will then appropriately update the files in this directory. # fill-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) > Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fill-range ``` ## Usage Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. ```js const fill = require('fill-range'); // fill(from, to[, step, options]); console.log(fill('1', '10')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] console.log(fill('1', '10', { toRegex: true })); //=> [1-9]|10 ``` **Params** * `from`: **{String|Number}** the number or letter to start with * `to`: **{String|Number}** the number or letter to end with * `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. * `options`: **{Object|Function}**: See all available [options](#options) ## Examples By default, an array of values is returned. **Alphabetical ranges** ```js console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] ``` **Numerical ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] ``` **Negative ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] ``` **Steps (increments)** ```js // numerical ranges with increments console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] // alphabetical ranges with increments console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] ``` ## Options ### options.step **Type**: `number` (formatted as a string or number) **Default**: `undefined` **Description**: The increment to use for the range. Can be used with letters or numbers. **Example(s)** ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` ### options.strictRanges **Type**: `boolean` **Default**: `false` **Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. **Example(s)** The following are all invalid: ```js fill('1.1', '2'); // decimals not supported in ranges fill('a', '2'); // incompatible range values fill(1, 10, 'foo'); // invalid "step" argument ``` ### options.stringify **Type**: `boolean` **Default**: `undefined` **Description**: Cast all returned values to strings. By default, integers are returned as numbers. **Example(s)** ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill(1, 5, { stringify: true })); //=> [ '1', '2', '3', '4', '5' ] ``` ### options.toRegex **Type**: `boolean` **Default**: `undefined` **Description**: Create a regex-compatible source string, instead of expanding values to an array. **Example(s)** ```js // alphabetical range console.log(fill('a', 'e', { toRegex: true })); //=> '[a-e]' // alphabetical with step console.log(fill('a', 'z', 3, { toRegex: true })); //=> 'a|d|g|j|m|p|s|v|y' // numerical range console.log(fill('1', '100', { toRegex: true })); //=> '[1-9]|[1-9][0-9]|100' // numerical range with zero padding console.log(fill('000001', '100000', { toRegex: true })); //=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' ``` ### options.transform **Type**: `function` **Default**: `undefined` **Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. **Example(s)** ```js // add zero padding console.log(fill(1, 5, value => String(value).padStart(4, '0'))); //=> ['0001', '0002', '0003', '0004', '0005'] ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 116 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [paulmillr](https://github.com/paulmillr) | | 2 | [realityking](https://github.com/realityking) | | 2 | [bluelovers](https://github.com/bluelovers) | | 1 | [edorivai](https://github.com/edorivai) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._ tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # typedarray-to-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/typedarray-to-buffer/master.svg [travis-url]: https://travis-ci.org/feross/typedarray-to-buffer [npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg [npm-url]: https://npmjs.org/package/typedarray-to-buffer [downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg [downloads-url]: https://npmjs.org/package/typedarray-to-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg [saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or [browserify](http://browserify.org/) and you're working with lots of binary data. Unfortunately, sometimes the browser or someone else's API gives you a typed array like `Uint8Array` to work with and you need to convert it to a `Buffer`. What do you do? Of course: `Buffer.from(uint8array)` But, alas, every time you do `Buffer.from(uint8array)` **the entire array gets copied**. The `Buffer` constructor does a copy; this is defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module matches the node API exactly. So, how can we avoid this expensive copy in [performance critical applications](https://github.com/feross/buffer/issues/22)? ***Simply use this module, of course!*** If you have an `ArrayBuffer`, you don't need this module, because `Buffer.from(arrayBuffer)` [is already efficient](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length). ## install ```bash npm install typedarray-to-buffer ``` ## usage To convert a typed array to a `Buffer` **without a copy**, do this: ```js var toBuffer = require('typedarray-to-buffer') var arr = new Uint8Array([1, 2, 3]) arr = toBuffer(arr) // arr is a buffer now! arr.toString() // '\u0001\u0002\u0003' arr.readUInt16BE(0) // 258 ``` ## how it works If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you pass in with the `Buffer` methods and return it. See [how does Buffer work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation works. This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't require a copy. If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` object, copy the data into it, and return it. There's no simple performance optimization we can do for old browsers. Oh well. If this module is used in node, then it will just call `Buffer.from`. This is just for the convenience of modules that work in both node and the browser. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). # ripemd160 [![NPM Package](https://img.shields.io/npm/v/ripemd160.svg?style=flat-square)](https://www.npmjs.org/package/ripemd160) [![Build Status](https://img.shields.io/travis/crypto-browserify/ripemd160.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/ripemd160) [![Dependency status](https://img.shields.io/david/crypto-browserify/ripemd160.svg?style=flat-square)](https://david-dm.org/crypto-browserify/ripemd160#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `ripemd160` on pure JavaScript. ## Example ```js var RIPEMD160 = require('ripemd160') console.log(new RIPEMD160().update('42').digest('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 var ripemd160stream = new RIPEMD160() ripemd160stream.end('42') console.log(ripemd160stream.read().toString('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 ``` ## LICENSE MIT # Node.js ABI [![Build Status](https://travis-ci.org/lgeiger/node-abi.svg?branch=v1.0.0)](https://travis-ci.org/lgeiger/node-abi) [![Greenkeeper badge](https://badges.greenkeeper.io/lgeiger/node-abi.svg)](https://greenkeeper.io/) Get the Node ABI for a given target and runtime, and vice versa. ## Installation ``` npm install node-abi ``` ## Usage ```javascript const nodeAbi = require('node-abi') nodeAbi.getAbi('7.2.0', 'node') // '51' nodeAbi.getAbi('1.4.10', 'electron') // '50' nodeAbi.getTarget('51', 'node') // '7.2.0' nodeAbi.getTarget('50', 'electron') // '1.4.15' nodeAbi.allTargets // [ // { runtime: 'node', target: '0.10.48', abi: '11', lts: false }, // { runtime: 'node', target: '0.12.17', abi: '14', lts: false }, // { runtime: 'node', target: '4.6.1', abi: '46', lts: true }, // { runtime: 'node', target: '5.12.0', abi: '47', lts: false }, // { runtime: 'node', target: '6.9.4', abi: '48', lts: true }, // { runtime: 'node', target: '7.4.0', abi: '51', lts: false }, // { runtime: 'electron', target: '1.0.2', abi: '47', lts: false }, // { runtime: 'electron', target: '1.2.8', abi: '48', lts: false }, // { runtime: 'electron', target: '1.3.13', abi: '49', lts: false }, // { runtime: 'electron', target: '1.4.15', abi: '50', lts: false } // ] nodeAbi.deprecatedTargets nodeAbi.supportedTargets nodeAbi.additionalTargets nodeAbi.futureTargets // ... ``` ## References - https://github.com/lgeiger/electron-abi - https://nodejs.org/en/download/releases/ - https://github.com/nodejs/Release # md5.js [![NPM Package](https://img.shields.io/npm/v/md5.js.svg?style=flat-square)](https://www.npmjs.org/package/md5.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/md5.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/md5.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/md5.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/md5.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `md5` on pure JavaScript. From [NIST SP 800-131A][1]: *md5 is no longer acceptable where collision resistance is required such as digital signatures.* ## Example ```js var MD5 = require('md5.js') console.log(new MD5().update('42').digest('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 var md5stream = new MD5() md5stream.end('42') console.log(md5stream.read().toString('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 ``` ## LICENSE [MIT](LICENSE) [1]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` [![codecov](https://codecov.io/gh/alepop/ed25519-hd-key/branch/master/graph/badge.svg)](https://codecov.io/gh/alepop/ed25519-hd-key) ed25519 HD Key ===== Key Derivation for `ed25519` ------------ [SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) - Specification Installation ------------ npm i --save ed25519-hd-key Usage ----- **example:** ```js const { derivePath, getMasterKeyFromSeed, getPublicKey } = require('ed25519-hd-key') const hexSeed = 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'; const { key, chainCode } = getMasterKeyFromSeed(hexSeed); console.log(key.toString('hex')) // => 2b4be7f19ee27bbf30c667b642d5f4aa69fd169872f8fc3059c08ebae2eb19e7 console.log(chainCode.toString('hex')); // => 90046a93de5380a72b5e45010748567d5ea02bbf6522f979e05c0d8d8ca9fffb const { key, chainCode} = derivePath("m/0'/2147483647'", hexSeed); console.log(key.toString('hex')) // => ea4f5bfe8694d8bb74b7b59404632fd5968b774ed545e810de9c32a4fb4192f4 console.log(chainCode.toString('hex')); // => 138f0b2551bcafeca6ff2aa88ba8ed0ed8de070841f0c4ef0165df8181eaad7f console.log(getPublicKey(key).toString('hex')) // => 005ba3b9ac6e90e83effcd25ac4e58a1365a9e35a3d3ae5eb07b9e4d90bcf7506d ``` Tests ----- ``` npm test ``` References ---------- [SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) [BIP-0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) [BIP-0044](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki) cipher-base === [![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) Abstract base class to inherit from if you want to create streams implementing the same api as node crypto streams. Requires you to implement 2 methods `_final` and `_update`. `_update` takes a buffer and should return a buffer, `_final` takes no arguments and should return a buffer. The constructor takes one argument and that is a string which if present switches it into hash mode, i.e. the object you get from crypto.createHash or crypto.createSign, this switches the name of the final method to be the string you passed instead of `final` and returns `this` from update. # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # mime-types [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] The ultimate javascript content-type utility. Similar to [the `[email protected]` module](https://www.npmjs.com/package/mime), except: - __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. - No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. - No `.define()` functionality - Bug fixes for `.lookup(path)` Otherwise, the API is compatible with `mime` 1.x. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install mime-types ``` ## Adding Types All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), so open a PR there if you'd like to add mime types. ## API ```js var mime = require('mime-types') ``` All functions return `false` if input is invalid or not found. ### mime.lookup(path) Lookup the content-type associated with a file. ```js mime.lookup('json') // 'application/json' mime.lookup('.md') // 'text/markdown' mime.lookup('file.html') // 'text/html' mime.lookup('folder/file.js') // 'application/javascript' mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` ### mime.contentType(type) Create a full content-type header given a content-type or extension. When given an extension, `mime.lookup` is used to get the matching content-type, otherwise the given content-type is used. Then if the content-type does not already have a `charset` parameter, `mime.charset` is used to get the default charset and add to the returned content-type. ```js mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' mime.contentType('file.json') // 'application/json; charset=utf-8' mime.contentType('text/html') // 'text/html; charset=utf-8' mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' // from a full path mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' ``` ### mime.extension(type) Get the default extension for a content-type. ```js mime.extension('application/octet-stream') // 'bin' ``` ### mime.charset(type) Lookup the implied default charset of a content-type. ```js mime.charset('text/markdown') // 'UTF-8' ``` ### var type = mime.types[extension] A map of content-types by extension. ### [extensions...] = mime.extensions[type] A map of extensions by content-type. ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci [ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master [node-version-image]: https://badgen.net/npm/node/mime-types [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-types [npm-url]: https://npmjs.org/package/mime-types [npm-version-image]: https://badgen.net/npm/v/mime-types text-encoding-utf-8 ============== This is a **partial** polyfill for the [Encoding Living Standard](https://encoding.spec.whatwg.org/) API for the Web, allowing encoding and decoding of textual data to and from Typed Array buffers for binary data in JavaScript. This is fork of [text-encoding](https://github.com/inexorabletash/text-encoding) that **only** support **UTF-8**. Basic examples and tests are included. ### Install ### There are a few ways you can get the `text-encoding-utf-8` library. #### Node #### `text-encoding-utf-8` is on `npm`. Simply run: ```js npm install text-encoding-utf-8 ``` Or add it to your `package.json` dependencies. ### HTML Page Usage ### ```html <script src="encoding.js"></script> ``` ### API Overview ### Basic Usage ```js var uint8array = TextEncoder(encoding).encode(string); var string = TextDecoder(encoding).decode(uint8array); ``` Streaming Decode ```js var string = "", decoder = TextDecoder(encoding), buffer; while (buffer = next_chunk()) { string += decoder.decode(buffer, {stream:true}); } string += decoder.decode(); // finish the stream ``` ### Encodings ### Only `utf-8` and `UTF-8` are supported. ### Non-Standard Behavior ### Only `utf-8` and `UTF-8` are supported. ### Motivation Binary size matters, especially on a mobile phone. Safari on iOS does not support TextDecoder or TextEncoder. # axios // core The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are: - Dispatching requests - Requests sent via `adapters/` (see lib/adapters/README.md) - Managing interceptors - Handling config # is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![NPM total downloads](https://img.shields.io/npm/dt/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-number) > Returns true if the value is a finite number. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-number ``` ## Why is this needed? In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use `+`, `-`, or `Number()` to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results: ```js console.log(+[]); //=> 0 console.log(+''); //=> 0 console.log(+' '); //=> 0 console.log(typeof NaN); //=> 'number' ``` This library offers a performant way to smooth out edge cases like these. ## Usage ```js const isNumber = require('is-number'); ``` See the [tests](./test.js) for more examples. ### true ```js isNumber(5e3); // true isNumber(0xff); // true isNumber(-1.1); // true isNumber(0); // true isNumber(1); // true isNumber(1.1); // true isNumber(10); // true isNumber(10.10); // true isNumber(100); // true isNumber('-1.1'); // true isNumber('0'); // true isNumber('012'); // true isNumber('0xff'); // true isNumber('1'); // true isNumber('1.1'); // true isNumber('10'); // true isNumber('10.10'); // true isNumber('100'); // true isNumber('5e3'); // true isNumber(parseInt('012')); // true isNumber(parseFloat('012')); // true ``` ### False Everything else is false, as you would expect: ```js isNumber(Infinity); // false isNumber(NaN); // false isNumber(null); // false isNumber(undefined); // false isNumber(''); // false isNumber(' '); // false isNumber('foo'); // false isNumber([1]); // false isNumber([]); // false isNumber(function () {}); // false isNumber({}); // false ``` ## Release history ### 7.0.0 * Refactor. Now uses `.isFinite` if it exists. * Performance is about the same as v6.0 when the value is a string or number. But it's now 3x-4x faster when the value is not a string or number. ### 6.0.0 * Optimizations, thanks to @benaadams. ### 5.0.0 **Breaking changes** * removed support for `instanceof Number` and `instanceof String` ## Benchmarks As with all benchmarks, take these with a grain of salt. See the [benchmarks](./benchmark/index.js) for more detail. ``` # all v7.0 x 413,222 ops/sec ±2.02% (86 runs sampled) v6.0 x 111,061 ops/sec ±1.29% (85 runs sampled) parseFloat x 317,596 ops/sec ±1.36% (86 runs sampled) fastest is 'v7.0' # string v7.0 x 3,054,496 ops/sec ±1.05% (89 runs sampled) v6.0 x 2,957,781 ops/sec ±0.98% (88 runs sampled) parseFloat x 3,071,060 ops/sec ±1.13% (88 runs sampled) fastest is 'parseFloat,v7.0' # number v7.0 x 3,146,895 ops/sec ±0.89% (89 runs sampled) v6.0 x 3,214,038 ops/sec ±1.07% (89 runs sampled) parseFloat x 3,077,588 ops/sec ±1.07% (87 runs sampled) fastest is 'v6.0' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 49 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [charlike-old](https://github.com/charlike-old) | | 1 | [benaadams](https://github.com/benaadams) | | 1 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 15, 2018._ # concordance Compare, format, diff and serialize any JavaScript value. Built for Node.js 10 and above. ## Behavior Concordance recursively describes JavaScript values, whether they're booleans or complex object structures. It recurses through all enumerable properties, list items (e.g. arrays) and iterator entries. The same algorithm is used when comparing, formatting or diffing values. This means Concordance's behavior is consistent, no matter how you use it. ### Comparison details * [Object wrappers](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/types%20%26%20grammar/ch3.md#boxing-wrappers) are compared both as objects and unwrapped values. Thus Concordance always treats `Object(1)` as different from `1`. * `-0` is distinct from `0`. * `NaN` equals `NaN`. * The `Argument` values can be compared to a regular array. * `Error` names and messages are always compared, even if these are not enumerable properties. * `Function` values are compared by identity only. Names are always formatted and serialized. * `Global` objects are considered equal. * `Map` keys and `Set` items are compared in-order. * `Object` string properties are compared according to the [traversal order](http://2ality.com/2015/10/property-traversal-order-es6.html). Symbol properties are compared by identity. * `Promise` values are compared by identity only. * `Symbol` values are compared by identity only. * Recursion stops whenever a circular reference is encountered. If the same cycle is present in the actual and expected values they're considered equal, but they're unequal otherwise. ### Formatting details Concordance strives to format every aspect of a value that is used for comparisons. Formatting is optimized for human legibility. Strings enjoy special formatting: * When used as keys, line break characters are escaped * Otherwise, multi-line strings are formatted using backticks, and line break characters are replaced by [control pictures](http://graphemica.com/blocks/control-pictures). Similarly, line breaks in symbol descriptions are escaped. ### Diffing details Concordance tries to minimize diff lines. This is difficult with object values, which may have similar properties but a different constructor. Multi-line strings are compared line-by-line. ### Serialization details Concordance can serialize any value for later use. Deserialized values can be compared to each other or to regular JavaScript values. The deserialized value should be passed as the **actual** value to the comparison and diffing methods. Certain value comparisons behave differently when the **actual** value is deserialized: * `Argument` values can only be compared to other `Argument` values. * `Function` values are compared by name. * `Promise` values are compared by their constructor and additional enumerable properties, but not by identity. * `Symbol` values are compared by their string serialization. [Registered](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Shared_symbols_in_the_global_symbol_registry) and [well-known symbols](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Well-known_symbols) will never equal symbols with similar descriptions. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: ```js const emojiRegex = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # minimatch A minimal matching utility. [![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ### partial Compare a partial path to a pattern. As long as the parts of the path that are present are not contradicted by the pattern, it will be treated as a match. This is useful in applications where you're walking through a folder structure, and don't yet have the full path, but want to ensure that you do not walk down paths that can never be a match. For example, ```js minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a ``` ### allowWindowsEscape Windows path separator `\` is by default converted to `/`, which prohibits the usage of `\` as a escape character. This flag skips that behavior and allows using the escape character. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # defer-to-connect > The safe way to handle the `connect` socket event [![Coverage Status](https://coveralls.io/repos/github/szmarczak/defer-to-connect/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/defer-to-connect?branch=master) Once you receive the socket, it may be already connected (or disconnected).<br> To avoid checking that, use `defer-to-connect`. It'll do that for you. ## Usage ```js const deferToConnect = require('defer-to-connect'); deferToConnect(socket, () => { console.log('Connected!'); }); ``` ## API ### deferToConnect(socket, connectListener) Calls `connectListener()` when connected. ### deferToConnect(socket, listeners) #### listeners An object representing `connect`, `secureConnect` and `close` properties. Calls `connect()` when the socket is connected.<br> Calls `secureConnect()` when the socket is securely connected.<br> Calls `close()` when the socket is destroyed. ## License MIT text-encoding-utf-8 ============== This is a **partial** polyfill for the [Encoding Living Standard](https://encoding.spec.whatwg.org/) API for the Web, allowing encoding and decoding of textual data to and from Typed Array buffers for binary data in JavaScript. This is fork of [text-encoding](https://github.com/inexorabletash/text-encoding) that **only** support **UTF-8**. Basic examples and tests are included. ### Install ### There are a few ways you can get the `text-encoding-utf-8` library. #### Node #### `text-encoding-utf-8` is on `npm`. Simply run: ```js npm install text-encoding-utf-8 ``` Or add it to your `package.json` dependencies. ### HTML Page Usage ### ```html <script src="encoding.js"></script> ``` ### API Overview ### Basic Usage ```js var uint8array = TextEncoder(encoding).encode(string); var string = TextDecoder(encoding).decode(uint8array); ``` Streaming Decode ```js var string = "", decoder = TextDecoder(encoding), buffer; while (buffer = next_chunk()) { string += decoder.decode(buffer, {stream:true}); } string += decoder.decode(); // finish the stream ``` ### Encodings ### Only `utf-8` and `UTF-8` are supported. ### Non-Standard Behavior ### Only `utf-8` and `UTF-8` are supported. ### Motivation Binary size matters, especially on a mobile phone. Safari on iOS does not support TextDecoder or TextEncoder. # emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=main)](https://travis-ci.org/mathiasbynens/emoji-regex) _emoji-regex_ offers a regular expression to match all emoji symbols and sequences (including textual representations of emoji) as per the Unicode Standard. This repository contains a script that generates this regular expression based on [Unicode data](https://github.com/node-unicode/node-unicode-data). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install emoji-regex ``` In [Node.js](https://nodejs.org/): ```js const emojiRegex = require('emoji-regex/RGI_Emoji.js'); // Note: because the regular expression has the global flag set, this module // exports a function that returns the regex rather than exporting the regular // expression itself, to make it impossible to (accidentally) mutate the // original regular expression. const text = ` \u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) \u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji \u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) \u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier `; const regex = emojiRegex(); let match; while (match = regex.exec(text)) { const emoji = match[0]; console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); } ``` Console output: ``` Matched sequence ⌚ — code points: 1 Matched sequence ⌚ — code points: 1 Matched sequence ↔️ — code points: 2 Matched sequence ↔️ — code points: 2 Matched sequence 👩 — code points: 1 Matched sequence 👩 — code points: 1 Matched sequence 👩🏿 — code points: 2 Matched sequence 👩🏿 — code points: 2 ``` ## Regular expression flavors The package comes with three distinct regular expressions: ```js // This is the recommended regular expression to use. It matches all // emoji recommended for general interchange, as defined via the // `RGI_Emoji` property in the Unicode Standard. // https://unicode.org/reports/tr51/#def_rgi_set // When in doubt, use this! const emojiRegexRGI = require('emoji-regex/RGI_Emoji.js'); // This is the old regular expression, prior to `RGI_Emoji` being // standardized. In addition to all `RGI_Emoji` sequences, it matches // some emoji you probably don’t want to match (such as emoji component // symbols that are not meant to be used separately). const emojiRegex = require('emoji-regex/index.js'); // This regular expression matches even more emoji than the previous // one, including emoji that render as text instead of icons (i.e. // emoji that are not `Emoji_Presentation` symbols and that aren’t // forced to render as emoji by a variation selector). const emojiRegexText = require('emoji-regex/text.js'); ``` Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: ```js const emojiRegexRGI = require('emoji-regex/es2015/RGI_Emoji.js'); const emojiRegex = require('emoji-regex/es2015/index.js'); const emojiRegexText = require('emoji-regex/es2015/text.js'); ``` ## For maintainers ### How to update emoji-regex after new Unicode Standard releases 1. Update the Unicode data dependency in `package.json` by running the following commands: ```sh # Example: updating from Unicode v12 to Unicode v13. npm uninstall @unicode/unicode-12.0.0 npm install @unicode/unicode-13.0.0 --save-dev ```` 1. Generate the new output: ```sh npm run build ``` 1. Verify that tests still pass: ```sh npm test ``` 1. Send a pull request with the changes, and get it reviewed & merged. 1. On the `main` branch, bump the emoji-regex version number in `package.json`: ```sh npm version patch -m 'Release v%s' ``` Instead of `patch`, use `minor` or `major` [as needed](https://semver.org/). Note that this produces a Git commit + tag. 1. Push the release commit and tag: ```sh git push ``` Our CI then automatically publishes the new release to npm. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _emoji-regex_ is available under the [MIT](https://mths.be/mit) license. # bl *(BufferList)* [![Build Status](https://api.travis-ci.com/rvagg/bl.svg?branch=master)](https://travis-ci.com/rvagg/bl/) **A Node.js Buffer list collector, reader and streamer thingy.** [![NPM](https://nodei.co/npm/bl.svg)](https://nodei.co/npm/bl/) **bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. ```js const { BufferList } = require('bl') const bl = new BufferList() bl.append(Buffer.from('abcd')) bl.append(Buffer.from('efg')) bl.append('hi') // bl will also accept & convert Strings bl.append(Buffer.from('j')) bl.append(Buffer.from([ 0x3, 0x4 ])) console.log(bl.length) // 12 console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' console.log(bl.slice(3, 6).toString('ascii')) // 'def' console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' console.log(bl.indexOf('def')) // 3 console.log(bl.indexOf('asdf')) // -1 // or just use toString! console.log(bl.toString()) // 'abcdefghij\u0003\u0004' console.log(bl.toString('ascii', 3, 8)) // 'defgh' console.log(bl.toString('ascii', 5, 10)) // 'fghij' // other standard Buffer readables console.log(bl.readUInt16BE(10)) // 0x0304 console.log(bl.readUInt16LE(10)) // 0x0403 ``` Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: ```js const { BufferListStream } = require('bl') const fs = require('fs') fs.createReadStream('README.md') .pipe(BufferListStream((err, data) => { // note 'new' isn't strictly required // `data` is a complete Buffer object containing the full data console.log(data.toString()) })) ``` Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): ```js const hyperquest = require('hyperquest') const { BufferListStream } = require('bl') const url = 'https://raw.github.com/rvagg/bl/master/README.md' hyperquest(url).pipe(BufferListStream((err, data) => { console.log(data.toString()) })) ``` Or, use it as a readable stream to recompose a list of Buffers to an output source: ```js const { BufferListStream } = require('bl') const fs = require('fs') var bl = new BufferListStream() bl.append(Buffer.from('abcd')) bl.append(Buffer.from('efg')) bl.append(Buffer.from('hi')) bl.append(Buffer.from('j')) bl.pipe(fs.createWriteStream('gibberish.txt')) ``` ## API * <a href="#ctor"><code><b>new BufferList([ buf ])</b></code></a> * <a href="#isBufferList"><code><b>BufferList.isBufferList(obj)</b></code></a> * <a href="#length"><code>bl.<b>length</b></code></a> * <a href="#append"><code>bl.<b>append(buffer)</b></code></a> * <a href="#get"><code>bl.<b>get(index)</b></code></a> * <a href="#indexOf"><code>bl.<b>indexOf(value[, byteOffset][, encoding])</b></code></a> * <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a> * <a href="#shallowSlice"><code>bl.<b>shallowSlice([ start[, end ] ])</b></code></a> * <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a> * <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a> * <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a> * <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a> * <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a> * <a href="#ctorStream"><code><b>new BufferListStream([ callback ])</b></code></a> -------------------------------------------------------- <a name="ctor"></a> ### new BufferList([ Buffer | Buffer array | BufferList | BufferList array | String ]) No arguments are _required_ for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` objects. `new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: ```js const { BufferList } = require('bl') const bl = BufferList() // equivalent to: const { BufferList } = require('bl') const bl = new BufferList() ``` -------------------------------------------------------- <a name="isBufferList"></a> ### BufferList.isBufferList(obj) Determines if the passed object is a `BufferList`. It will return `true` if the passed object is an instance of `BufferList` **or** `BufferListStream` and `false` otherwise. N.B. this won't return `true` for `BufferList` or `BufferListStream` instances created by versions of this library before this static method was added. -------------------------------------------------------- <a name="length"></a> ### bl.length Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. -------------------------------------------------------- <a name="append"></a> ### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) `append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. -------------------------------------------------------- <a name="get"></a> ### bl.get(index) `get()` will return the byte at the specified index. -------------------------------------------------------- <a name="indexOf"></a> ### bl.indexOf(value[, byteOffset][, encoding]) `get()` will return the byte at the specified index. `indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. -------------------------------------------------------- <a name="slice"></a> ### bl.slice([ start, [ end ] ]) `slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. -------------------------------------------------------- <a name="shallowSlice"></a> ### bl.shallowSlice([ start, [ end ] ]) `shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. No copies will be performed. All buffers in the result share memory with the original list. -------------------------------------------------------- <a name="copy"></a> ### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) `copy()` 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`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. -------------------------------------------------------- <a name="duplicate"></a> ### bl.duplicate() `duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: ```js var bl = new BufferListStream() bl.append('hello') bl.append(' world') bl.append('\n') bl.duplicate().pipe(process.stdout, { end: false }) console.log(bl.toString()) ``` -------------------------------------------------------- <a name="consume"></a> ### bl.consume(bytes) `consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers&mdash;initial offsets will be calculated accordingly in order to give you a consistent view of the data. -------------------------------------------------------- <a name="toString"></a> ### bl.toString([encoding, [ start, [ end ]]]) `toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. -------------------------------------------------------- <a name="readXX"></a> ### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work. -------------------------------------------------------- <a name="ctorStream"></a> ### new BufferListStream([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) **BufferListStream** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **BufferListStream** instance. The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. `new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: ```js const { BufferListStream } = require('bl') const bl = BufferListStream() // equivalent to: const { BufferListStream } = require('bl') const bl = new BufferListStream() ``` N.B. For backwards compatibility reasons, `BufferListStream` is the **default** export when you `require('bl')`: ```js const { BufferListStream } = require('bl') // equivalent to: const BufferListStream = require('bl') ``` -------------------------------------------------------- ## Contributors **bl** is brought to you by the following hackers: * [Rod Vagg](https://github.com/rvagg) * [Matteo Collina](https://github.com/mcollina) * [Jarett Cruger](https://github.com/jcrugzz) <a name="license"></a> ## License &amp; copyright Copyright (c) 2013-2019 bl contributors (listed above). bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. # u3 - Utility Functions This lib contains utility functions for e3, dataflower and other projects. ## Documentation ### Installation ```bash npm install u3 ``` ```bash bower install u3 ``` #### Usage In this documentation I used the lib as follows: ```js var u3 = require("u3"), cache = u3.cache, eachCombination = u3.eachCombination; ``` ### Function wrappers #### cache The `cache(fn)` function caches the fn results, so by the next calls it will return the result of the first call. You can use different arguments, but they won't affect the return value. ```js var a = cache(function fn(x, y, z){ return x + y + z; }); console.log(a(1, 2, 3)); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` It is possible to cache a value too. ```js var a = cache(1 + 2 + 3); console.log(a()); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` ### Math #### eachCombination The `eachCombination(alternativesByDimension, callback)` calls the `callback(a,b,c,...)` on each combination of the `alternatives[a[],b[],c[],...]`. ```js eachCombination([ [1, 2, 3], ["a", "b"] ], console.log); /* 1, "a" 1, "b" 2, "a" 2, "b" 3, "a" 3, "b" */ ``` You can use any dimension and number of alternatives. In the current example we used 2 dimensions. By the first dimension we used 3 alternatives: `[1, 2, 3]` and by the second dimension we used 2 alternatives: `["a", "b"]`. ## License MIT - 2016 Jánszky László Lajos # http-errors [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][node-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Test Coverage][coveralls-image]][coveralls-url] Create HTTP errors for Express, Koa, Connect, etc. with ease. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install http-errors ``` ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ## API This is the current API, currently extracted from Koa and subject to change. ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ### createError([status], [message], [properties]) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ### createError([status], [error], [properties]) Extend the given `error` object with `createError.HttpError` properties. This will not alter the inheritance of the given `error` object, and the modified `error` object is the return value. <!-- eslint-disable no-redeclare --> ```js fs.readFile('foo.txt', function (err, buf) { if (err) { if (err.code === 'ENOENT') { var httpError = createError(404, err, { expose: false }) } else { var httpError = createError(500, err) } } }) ``` - `status` - the status code as a number - `error` - the error object to extend - `properties` - custom properties to attach to the object ### createError.isHttpError(val) Determine if the provided `val` is an `HttpError`. This will return `true` if the error inherits from the `HttpError` constructor of this module or matches the "duck type" for an error this module creates. All outputs from the `createError` factory will return `true` for this function, including if an non-`HttpError` was passed into the factory. ### new createError\[code || name\](\[msg]\)) Create a new error object with the given message `msg`. The error object inherits from `createError.HttpError`. ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. #### List of all constructors |Status Code|Constructor Name | |-----------|-----------------------------| |400 |BadRequest | |401 |Unauthorized | |402 |PaymentRequired | |403 |Forbidden | |404 |NotFound | |405 |MethodNotAllowed | |406 |NotAcceptable | |407 |ProxyAuthenticationRequired | |408 |RequestTimeout | |409 |Conflict | |410 |Gone | |411 |LengthRequired | |412 |PreconditionFailed | |413 |PayloadTooLarge | |414 |URITooLong | |415 |UnsupportedMediaType | |416 |RangeNotSatisfiable | |417 |ExpectationFailed | |418 |ImATeapot | |421 |MisdirectedRequest | |422 |UnprocessableEntity | |423 |Locked | |424 |FailedDependency | |425 |UnorderedCollection | |426 |UpgradeRequired | |428 |PreconditionRequired | |429 |TooManyRequests | |431 |RequestHeaderFieldsTooLarge | |451 |UnavailableForLegalReasons | |500 |InternalServerError | |501 |NotImplemented | |502 |BadGateway | |503 |ServiceUnavailable | |504 |GatewayTimeout | |505 |HTTPVersionNotSupported | |506 |VariantAlsoNegotiates | |507 |InsufficientStorage | |508 |LoopDetected | |509 |BandwidthLimitExceeded | |510 |NotExtended | |511 |NetworkAuthenticationRequired| ## License [MIT](LICENSE) [ci-image]: https://badgen.net/github/checks/jshttp/http-errors/master?label=ci [ci-url]: https://github.com/jshttp/http-errors/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master [coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master [node-image]: https://badgen.net/npm/node/http-errors [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/http-errors [npm-url]: https://npmjs.org/package/http-errors [npm-version-image]: https://badgen.net/npm/v/http-errors [travis-image]: https://badgen.net/travis/jshttp/http-errors/master [travis-url]: https://travis-ci.org/jshttp/http-errors # bip39-light A lightweight fork of [bitcoinjs/bip39](https://github.com/bitcoinjs/bip39). Only english wordlist and removed some dependendecies. JavaScript implementation of [Bitcoin BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki): Mnemonic code for generating deterministic keys ## Reminder for developers ***Please remember to allow recovery from mnemonic phrases that have invalid checksums (or that you don't have the wordlist)*** When a checksum is invalid, warn the user that the phrase is not something generated by your app, and ask if they would like to use it anyway. This way, your app only needs to hold the wordlists for your supported languages, but you can recover phrases made by other apps in other languages. However, there should be other checks in place, such as checking to make sure the user is inputting 12 words or more separated by a space. ie. `phrase.trim().split(/\s+/g).length >= 12` ## Examples ``` js // Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 128-bits of entropy var mnemonic = bip39.generateMnemonic() // => 'seed sock milk update focus rotate barely fade car face mechanic mercy' bip39.mnemonicToSeedHex('basket actual') // => '5cf2d4a8b0355e90295bdfc565a022a409af063d5365bb57bf74d9528f494bfa4400f53d8349b80fdae44082d7f9541e1dba2b003bcfec9d0d53781ca676651f' bip39.mnemonicToSeed('basket actual') // => <Buffer 5c f2 d4 a8 b0 35 5e 90 29 5b df c5 65 a0 22 a4 09 af 06 3d 53 65 bb 57 bf 74 d9 52 8f 49 4b fa 44 00 f5 3d 83 49 b8 0f da e4 40 82 d7 f9 54 1e 1d ba 2b ...> bip39.validateMnemonic(mnemonic) // => true bip39.validateMnemonic('basket actual') // => false ``` ``` js var bip39 = require('bip39-light') // defaults to BIP39 English word list // uses HEX strings for entropy var mnemonic = bip39.entropyToMnemonic('00000000000000000000000000000000') // => abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about // reversible bip39.mnemonicToEntropy(mnemonic) // => '00000000000000000000000000000000' ``` # Arg [![CircleCI](https://circleci.com/gh/zeit/arg.svg?style=svg)](https://circleci.com/gh/zeit/arg) `arg` is yet another command line option parser. ## Installation Use Yarn or NPM to install. ```console $ yarn add arg ``` or ```console $ npm install arg ``` ## Usage `arg()` takes either 1 or 2 arguments: 1. Command line specification object (see below) 2. Parse options (_Optional_, defaults to `{permissive: false, argv: process.argv.slice(2), stopAtPositional: false}`) It returns an object with any values present on the command-line (missing options are thus missing from the resulting object). Arg performs no validation/requirement checking - we leave that up to the application. All parameters that aren't consumed by options (commonly referred to as "extra" parameters) are added to `result._`, which is _always_ an array (even if no extra parameters are passed, in which case an empty array is returned). ```javascript const arg = require('arg'); // `options` is an optional parameter const args = arg(spec, options = {permissive: false, argv: process.argv.slice(2)}); ``` For example: ```console $ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar ``` ```javascript // hello.js const arg = require('arg'); const args = arg({ // Types '--help': Boolean, '--version': Boolean, '--verbose': arg.COUNT, // Counts the number of times --verbose is passed '--port': Number, // --port <number> or --port=<number> '--name': String, // --name <string> or --name=<string> '--tag': [String], // --tag <string> or --tag=<string> // Aliases '-v': '--verbose', '-n': '--name', // -n <string>; result is stored in --name '--label': '--name' // --label <string> or --label=<string>; // result is stored in --name }); console.log(args); /* { _: ["foo", "bar", "--foobar"], '--port': 1234, '--verbose': 4, '--name': "My name", '--tag': ["qux", "qix"] } */ ``` The values for each key=&gt;value pair is either a type (function or [function]) or a string (indicating an alias). - In the case of a function, the string value of the argument's value is passed to it, and the return value is used as the ultimate value. - In the case of an array, the only element _must_ be a type function. Array types indicate that the argument may be passed multiple times, and as such the resulting value in the returned object is an array with all of the values that were passed using the specified flag. - In the case of a string, an alias is established. If a flag is passed that matches the _key_, then the _value_ is substituted in its place. Type functions are passed three arguments: 1. The parameter value (always a string) 2. The parameter name (e.g. `--label`) 3. The previous value for the destination (useful for reduce-like operations or for supporting `-v` multiple times, etc.) This means the built-in `String`, `Number`, and `Boolean` type constructors "just work" as type functions. Note that `Boolean` and `[Boolean]` have special treatment - an option argument is _not_ consumed or passed, but instead `true` is returned. These options are called "flags". For custom handlers that wish to behave as flags, you may pass the function through `arg.flag()`: ```javascript const arg = require('arg'); const argv = ['--foo', 'bar', '-ff', 'baz', '--foo', '--foo', 'qux', '-fff', 'qix']; function myHandler(value, argName, previousValue) { /* `value` is always `true` */ return 'na ' + (previousValue || 'batman!'); } const args = arg({ '--foo': arg.flag(myHandler), '-f': '--foo' }, { argv }); console.log(args); /* { _: ['bar', 'baz', 'qux', 'qix'], '--foo': 'na na na na na na na na batman!' } */ ``` As well, `arg` supplies a helper argument handler called `arg.COUNT`, which equivalent to a `[Boolean]` argument's `.length` property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line.. For example, this is how you could implement `ssh`'s multiple levels of verbosity (`-vvvv` being the most verbose). ```javascript const arg = require('arg'); const argv = ['-AAAA', '-BBBB']; const args = arg({ '-A': arg.COUNT, '-B': [Boolean] }, { argv }); console.log(args); /* { _: [], '-A': 4, '-B': [true, true, true, true] } */ ``` ### Options If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of `arg()`. #### `argv` If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting `arg` slice them from `process.argv`) you may specify them in the `argv` option. For example: ```javascript const args = arg( { '--foo': String }, { argv: ['hello', '--foo', 'world'] } ); ``` results in: ```javascript const args = { _: ['hello'], '--foo': 'world' }; ``` #### `permissive` When `permissive` set to `true`, `arg` will push any unknown arguments onto the "extra" argument array (`result._`) instead of throwing an error about an unknown flag. For example: ```javascript const arg = require('arg'); const argv = ['--foo', 'hello', '--qux', 'qix', '--bar', '12345', 'hello again']; const args = arg( { '--foo': String, '--bar': Number }, { argv, permissive: true } ); ``` results in: ```javascript const args = { _: ['--qux', 'qix', 'hello again'], '--foo': 'hello', '--bar': 12345 } ``` #### `stopAtPositional` When `stopAtPositional` is set to `true`, `arg` will halt parsing at the first positional argument. For example: ```javascript const arg = require('arg'); const argv = ['--foo', 'hello', '--bar']; const args = arg( { '--foo': Boolean, '--bar': Boolean }, { argv, stopAtPositional: true } ); ``` results in: ```javascript const args = { _: ['hello', '--bar'], '--foo': true }; ``` ### Errors Some errors that `arg` throws provide a `.code` property in order to aid in recovering from user error, or to differentiate between user error and developer error (bug). ##### ARG_UNKNOWN_OPTION If an unknown option (not defined in the spec object) is passed, an error with code `ARG_UNKNOWN_OPTION` will be thrown: ```js // cli.js try { require('arg')({ '--hi': String }); } catch (err) { if (err.code === 'ARG_UNKNOWN_OPTION') { console.log(err.message); } else { throw err; } } ``` ```shell node cli.js --extraneous true Unknown or unexpected option: --extraneous ``` # License Copyright &copy; 2017-2019 by ZEIT, Inc. Released under the [MIT License](LICENSE.md). # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # lodash.isstring v4.0.1 The [lodash](https://lodash.com/) method `_.isString` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.isstring ``` In Node.js: ```js var isString = require('lodash.isstring'); ``` See the [documentation](https://lodash.com/docs#isString) or [package source](https://github.com/lodash/lodash/blob/4.0.1-npm-packages/lodash.isstring) for more details. # prebuild-install > **A command line tool to easily install prebuilt binaries for multiple versions of Node.js & Electron on a specific platform.** > By default it downloads prebuilt binaries from a GitHub release. [![npm](https://img.shields.io/npm/v/prebuild-install.svg)](https://www.npmjs.com/package/prebuild-install) ![Node version](https://img.shields.io/node/v/prebuild-install.svg) [![Test](https://img.shields.io/github/workflow/status/prebuild/prebuild-install/Test?label=test)](https://github.com/prebuild/prebuild-install/actions/workflows/test.yml) [![Standard](https://img.shields.io/badge/standard-informational?logo=javascript\&logoColor=fff)](https://standardjs.com) [![Common Changelog](https://common-changelog.org/badge.svg)](https://common-changelog.org) ## Note **Instead of [`prebuild`](https://github.com/prebuild/prebuild) paired with [`prebuild-install`](https://github.com/prebuild/prebuild-install), we recommend [`prebuildify`](https://github.com/prebuild/prebuildify) paired with [`node-gyp-build`](https://github.com/prebuild/node-gyp-build).** With `prebuildify`, all prebuilt binaries are shipped inside the package that is published to npm, which means there's no need for a separate download step like you find in `prebuild`. The irony of this approach is that it is faster to download all prebuilt binaries for every platform when they are bundled than it is to download a single prebuilt binary as an install script. Upsides: 1. No extra download step, making it more reliable and faster to install. 2. Supports changing runtime versions locally and using the same install between Node.js and Electron. Reinstalling or rebuilding is not necessary, as all prebuilt binaries are in the npm tarball and the correct one is simply picked on runtime. 3. The `node-gyp-build` runtime dependency is dependency-free and will remain so out of principle, because introducing dependencies would negate the shorter install time. 4. Prebuilt binaries work even if npm install scripts are disabled. 5. The npm package checksum covers prebuilt binaries too. Downsides: 1. The installed npm package is larger on disk. Using [Node-API](https://nodejs.org/api/n-api.html) alleviates this because Node-API binaries are runtime-agnostic and forward-compatible. 2. Publishing is mildly more complicated, because `npm publish` must be done after compiling and fetching prebuilt binaries (typically in CI). ## Usage Use [`prebuild`](https://github.com/prebuild/prebuild) to create and upload prebuilt binaries. Then change your package.json install script to: ```json { "scripts": { "install": "prebuild-install || node-gyp rebuild" } } ``` When a consumer then installs your package with npm thus triggering the above install script, `prebuild-install` will download a suitable prebuilt binary, or exit with a non-zero exit code if there is none, which triggers `node-gyp rebuild` in order to build from source. Options (see below) can be passed to `prebuild-install` like so: ```json { "scripts": { "install": "prebuild-install -r napi || node-gyp rebuild" } } ``` ### Help ``` prebuild-install [options] --download -d [url] (download prebuilds, no url means github) --target -t version (version to install for) --runtime -r runtime (Node runtime [node, napi or electron] to build or install for, default is node) --path -p path (make a prebuild-install here) --token -T gh-token (github token for private repos) --arch arch (target CPU architecture, see Node OS module docs, default is current arch) --platform platform (target platform, see Node OS module docs, default is current platform) --tag-prefix <prefix> (github tag prefix, default is "v") --build-from-source (skip prebuild download) --verbose (log verbosely) --libc (use provided libc rather than system default) --debug (set Debug or Release configuration) --version (print prebuild-install version and exit) ``` When `prebuild-install` is run via an `npm` script, options `--build-from-source`, `--debug`, `--download`, `--target`, `--runtime`, `--arch` `--platform` and `--libc` may be passed through via arguments given to the `npm` command. Alternatively you can set environment variables `npm_config_build_from_source=true`, `npm_config_platform`, `npm_config_arch`, `npm_config_target` `npm_config_runtime` and `npm_config_libc`. ### Libc On non-glibc Linux platforms, the Libc name is appended to platform name. For example, musl-based environments are called `linuxmusl`. If `--libc=glibc` is passed as option, glibc is discarded and platform is called as just `linux`. This can be used for example to build cross-platform packages on Alpine Linux. ### Private Repositories `prebuild-install` supports downloading prebuilds from private GitHub repositories using the `-T <github-token>`: ``` $ prebuild-install -T <github-token> ``` If you don't want to use the token on cli you can put it in `~/.prebuild-installrc`: ``` token=<github-token> ``` Alternatively you can specify it in the `prebuild-install_token` environment variable. Note that using a GitHub token uses the API to resolve the correct release meaning that you are subject to the ([GitHub Rate Limit](https://developer.github.com/v3/rate_limit/)). ### Create GitHub Token To create a token: - Go to [this page](https://github.com/settings/tokens) - Click the `Generate new token` button - Give the token a name and click the `Generate token` button, see below ![prebuild-token](https://cloud.githubusercontent.com/assets/13285808/20844584/d0b85268-b8c0-11e6-8b08-2b19522165a9.png) The default scopes should be fine. ### Custom binaries The end user can override binary download location through environment variables in their .npmrc file. The variable needs to meet the mask `% your package name %_binary_host` or `% your package name %_binary_host_mirror`. For example: ``` leveldown_binary_host=http://overriden-host.com/overriden-path ``` Note that the package version subpath and file name will still be appended. So if you are installing `[email protected]` the resulting url will be: ``` http://overriden-host.com/overriden-path/v1.2.3/leveldown-v1.2.3-node-v57-win32-x64.tar.gz ``` #### Local prebuilds If you want to use prebuilds from your local filesystem, you can use the `% your package name %_local_prebuilds` .npmrc variable to set a path to the folder containing prebuilds. For example: ``` leveldown_local_prebuilds=/path/to/prebuilds ``` This option will look directly in that folder for bundles created with `prebuild`, for example: ``` /path/to/prebuilds/leveldown-v1.2.3-node-v57-win32-x64.tar.gz ``` Non-absolute paths resolve relative to the directory of the package invoking prebuild-install, e.g. for nested dependencies. ### Cache All prebuilt binaries are cached to minimize traffic. So first `prebuild-install` picks binaries from the cache and if no binary could be found, it will be downloaded. Depending on the environment, the cache folder is determined in the following order: - `${npm_config_cache}/_prebuilds` - `${APP_DATA}/npm-cache/_prebuilds` - `${HOME}/.npm/_prebuilds` ## Install With [npm](https://npmjs.org) do: ``` npm install prebuild-install ``` ## License [MIT](./LICENSE) # base-x [![NPM Package](https://img.shields.io/npm/v/base-x.svg?style=flat-square)](https://www.npmjs.org/package/base-x) [![Build Status](https://img.shields.io/travis/cryptocoinjs/base-x.svg?branch=master&style=flat-square)](https://travis-ci.org/cryptocoinjs/base-x) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Fast base encoding / decoding of any given alphabet using bitcoin style leading zero compression. **WARNING:** This module is **NOT RFC3548** compliant, it cannot be used for base16 (hex), base32, or base64 encoding in a standards compliant manner. ## Example Base58 ``` javascript var BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' var bs58 = require('base-x')(BASE58) var decoded = bs58.decode('5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr') console.log(decoded) // => <Buffer 80 ed db dc 11 68 f1 da ea db d3 e4 4c 1e 3f 8f 5a 28 4c 20 29 f7 8a d2 6a f9 85 83 a4 99 de 5b 19> console.log(bs58.encode(decoded)) // => 5Kd3NBUAdUnhyzenEwVLy9pBKxSwXvE9FMPyR4UKZvpe6E3AgLr ``` ### Alphabets See below for a list of commonly recognized alphabets, and their respective base. Base | Alphabet ------------- | ------------- 2 | `01` 8 | `01234567` 11 | `0123456789a` 16 | `0123456789abcdef` 32 | `0123456789ABCDEFGHJKMNPQRSTVWXYZ` 32 | `ybndrfg8ejkmcpqxot1uwisza345h769` (z-base-32) 36 | `0123456789abcdefghijklmnopqrstuvwxyz` 58 | `123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz` 62 | `0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ` 64 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/` 67 | `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.!~` ## How it works It encodes octet arrays by doing long divisions on all significant digits in the array, creating a representation of that number in the new base. Then for every leading zero in the input (not significant as a number) it will encode as a single leader character. This is the first in the alphabet and will decode as 8 bits. The other characters depend upon the base. For example, a base58 alphabet packs roughly 5.858 bits per character. This means the encoded string 000f (using a base16, 0-f alphabet) will actually decode to 4 bytes unlike a canonical hex encoding which uniformly packs 4 bits into each character. While unusual, this does mean that no padding is required and it works for bases like 43. ## LICENSE [MIT](LICENSE) A direct derivation of the base58 implementation from [`bitcoin/bitcoin`](https://github.com/bitcoin/bitcoin/blob/f1e2f2a85962c1664e4e55471061af0eaa798d40/src/base58.cpp), generalized for variable length alphabets. # cacheable-lookup > A cacheable [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) that respects TTL :tada: [![Node CI](https://github.com/szmarczak/cacheable-lookup/workflows/Node%20CI/badge.svg)](https://github.com/szmarczak/cacheable-lookup/actions) [![Coverage Status](https://coveralls.io/repos/github/szmarczak/cacheable-lookup/badge.svg?branch=master)](https://coveralls.io/github/szmarczak/cacheable-lookup?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-lookup.svg)](https://www.npmjs.com/package/cacheable-lookup) [![install size](https://packagephobia.now.sh/badge?p=cacheable-lookup)](https://packagephobia.now.sh/result?p=cacheable-lookup) Making lots of HTTP requests? You can save some time by caching DNS lookups :zap: ## Usage ### Using the `lookup` option ```js const http = require('http'); const CacheableLookup = require('cacheable-lookup'); const cacheable = new CacheableLookup(); http.get('http://example.com', {lookup: cacheable.lookup}, response => { // Handle the response here }); ``` ### Attaching CacheableLookup to an Agent ```js const http = require('http'); const CacheableLookup = require('cacheable-lookup'); const cacheable = new CacheableLookup(); cacheable.install(http.globalAgent); http.get('http://example.com', response => { // Handle the response here }); ``` ## API ### new CacheableLookup(options) Returns a new instance of `CacheableLookup`. #### options Type: `object`<br> Default: `{}` Options used to cache the DNS lookups. ##### cache Type: `Map` | [`Keyv`](https://github.com/lukechilds/keyv/)<br> Default: `new Map()` Custom cache instance. If `undefined`, it will create a new one. **Note**: If you decide to use Keyv instead of the native implementation, the performance will drop by 10x. Memory leaks may occur as it doesn't provide any way to remove all the deprecated values at once. **Tip**: [`QuickLRU`](https://github.com/sindresorhus/quick-lru) is fully compatible with the Map API, you can use it to limit the amount of cached entries. Example: ```js const http = require('http'); const CacheableLookup = require('cacheable-lookup'); const QuickLRU = require('quick-lru'); const cacheable = new CacheableLookup({ cache: new QuickLRU({maxSize: 1000}) }); http.get('http://example.com', {lookup: cacheable.lookup}, response => { // Handle the response here }); ``` ##### options.maxTtl Type: `number`<br> Default: `Infinity` The maximum lifetime of the entries received from the specifed DNS server (TTL in seconds). If set to `0`, it will make a new DNS query each time. **Pro Tip**: This shouldn't be lower than your DNS server response time in order to prevent bottlenecks. For example, if you use Cloudflare, this value should be greater than `0.01`. ##### options.fallbackDuration Type: `number`<br> Default: `3600` (1 hour) When the DNS server responds with `ENOTFOUND` or `ENODATA` and the OS reports that the entry is available, it will use `dns.lookup(...)` directly for the requested hostnames for the specified amount of time (in seconds). If you don't query internal hostnames (such as `localhost`, `database.local` etc.), it is strongly recommended to set this value to `0`. ##### options.errorTtl Type: `number`<br> Default: `0.15` The time how long it needs to remember queries that threw `ENOTFOUND` or `ENODATA` (TTL in seconds). **Note**: This option is independent, `options.maxTtl` does not affect this. **Pro Tip**: This shouldn't be lower than your DNS server response time in order to prevent bottlenecks. For example, if you use Cloudflare, this value should be greater than `0.01`. ##### options.resolver Type: `dns.Resolver | dns.promises.Resolver`<br> Default: [`new dns.promises.Resolver()`](https://nodejs.org/api/dns.html#dns_class_dns_resolver) An instance of [DNS Resolver](https://nodejs.org/api/dns.html#dns_class_dns_resolver) used to make DNS queries. ##### options.lookup Type: `Function`<br> Default: [`dns.lookup`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) The fallback function to use when the DNS server responds with `ENOTFOUND` or `ENODATA`. **Note**: This has no effect if the `fallbackDuration` option is less than `1`. ### Entry object Type: `object` #### address Type: `string` The IP address (can be an IPv4 or IPv6 address). #### family Type: `number` The IP family (`4` or `6`). ##### expires Type: `number` **Note**: This is not present when falling back to `dns.lookup(...)`! The timestamp (`Date.now() + ttl * 1000`) when the entry expires. #### ttl **Note**: This is not present when falling back to `dns.lookup(...)`! The time in seconds for its lifetime. ### Entry object (callback-style) When `options.all` is `false`, then `callback(error, address, family, expires, ttl)` is called. <br> When `options.all` is `true`, then `callback(error, entries)` is called. ### CacheableLookup instance #### servers Type: `Array` The DNS servers used to make queries. Can be overridden - doing so will clear the cache. #### [lookup(hostname, options, callback)](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) #### lookupAsync(hostname, options) The asynchronous version of `dns.lookup(…)`. Returns an [entry object](#entry-object).<br> If `options.all` is true, returns an array of entry objects. ##### hostname Type: `string` ##### options Type: `object` The same as the [`dns.lookup(…)`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) options. #### query(hostname) An asynchronous function which returns cached DNS lookup entries.<br> This is the base for `lookupAsync(hostname, options)` and `lookup(hostname, options, callback)`. **Note**: This function has no options. Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. #### queryAndCache(hostname) An asynchronous function which makes two DNS queries: A and AAAA. The result is cached.<br> This is used by `query(hostname)` if no entry in the database is present. Returns an array of objects with `address`, `family`, `ttl` and `expires` properties. #### updateInterfaceInfo() Updates interface info. For example, you need to run this when you plug or unplug your WiFi driver. **Note:** Running `updateInterfaceInfo()` will trigger `clear()` only on network interface removal. #### clear(hostname?) Clears the cache for the given hostname. If the hostname argument is not present, the entire cache will be emptied. ## High performance Performed on: - Query: `example.com` - CPU: i7-7700k - CPU governor: performance ``` CacheableLookup#lookupAsync x 2,896,251 ops/sec ±1.07% (85 runs sampled) CacheableLookup#lookupAsync.all x 2,842,664 ops/sec ±1.11% (88 runs sampled) CacheableLookup#lookupAsync.all.ADDRCONFIG x 2,598,283 ops/sec ±1.21% (88 runs sampled) CacheableLookup#lookup x 2,565,913 ops/sec ±1.56% (85 runs sampled) CacheableLookup#lookup.all x 2,609,039 ops/sec ±1.01% (86 runs sampled) CacheableLookup#lookup.all.ADDRCONFIG x 2,416,242 ops/sec ±0.89% (85 runs sampled) dns#lookup x 7,272 ops/sec ±0.36% (86 runs sampled) dns#lookup.all x 7,249 ops/sec ±0.40% (86 runs sampled) dns#lookup.all.ADDRCONFIG x 5,693 ops/sec ±0.28% (85 runs sampled) Fastest is CacheableLookup#lookupAsync.all ``` ## Related - [cacheable-request](https://github.com/lukechilds/cacheable-request) - Wrap native HTTP requests with RFC compliant cache support ## License MIT # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # Platform.js v1.3.5 A platform detection library that works on nearly all JavaScript platforms. ## Disclaimer Platform.js is for informational purposes only & **not** intended as a substitution for feature detection/inference checks. ## Documentation * [doc/README.md](https://github.com/bestiejs/platform.js/blob/master/doc/README.md#readme) * [wiki/Changelog](https://github.com/bestiejs/platform.js/wiki/Changelog) * [wiki/Roadmap](https://github.com/bestiejs/platform.js/wiki/Roadmap) * [platform.js demo](https://bestiejs.github.io/platform.js/) (See also [whatsmyua.info](https://www.whatsmyua.info/) for comparisons between platform.js and other platform detection libraries) ## Installation In a browser: ```html <script src="platform.js"></script> ``` In an AMD loader: ```js require(['platform'], function(platform) {/*…*/}); ``` Using npm: ```shell $ npm i --save platform ``` In Node.js: ```js var platform = require('platform'); ``` Usage example: ```js // on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition platform.name; // 'IE' platform.version; // '10.0' platform.layout; // 'Trident' platform.os; // 'Windows Server 2008 R2 / 7 x64' platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64' // or on an iPad platform.name; // 'Safari' platform.version; // '5.1' platform.product; // 'iPad' platform.manufacturer; // 'Apple' platform.layout; // 'WebKit' platform.os; // 'iOS 5.0' platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)' // or parsing a given UA string var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52'); info.name; // 'Opera' info.version; // '11.52' info.layout; // 'Presto' info.os; // 'Mac OS X 10.7.2' info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2' ``` ## Support Tested in Chrome 82-83, Firefox 77-78, IE 11, Edge 82-83, Safari 12-13, Node.js 4-14, & PhantomJS 2.1.1. ## BestieJS Platform.js is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5+ precedents, unit testing, & plenty of documentation. util-deprecate ============== ### The Node.js `util.deprecate()` function with browser support In Node.js, this module simply re-exports the `util.deprecate()` function. In the web browser (i.e. via browserify), a browser-specific implementation of the `util.deprecate()` function is used. ## API A `deprecate()` function is the only thing exposed by this module. ``` javascript // setup: exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); // users see: foo(); // foo() is deprecated, use bar() instead foo(); foo(); ``` ## License (The MIT License) Copyright (c) 2014 Nathan Rajlich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. USB Library for Node.JS =============================== [![Build Status](https://github.com/node-usb/node-usb/workflows/prebuild/badge.svg)](https://github.com/node-usb/node-usb/actions) Node.JS library for communicating with USB devices in JavaScript / CoffeeScript. This is a refactoring / rewrite of Christopher Klein's [node-usb](https://github.com/schakko/node-usb). The API is not compatible (hopefully you find it an improvement). It's based entirely on libusb's asynchronous API for better efficiency, and provides a stream API for continuously streaming data or events. Installation ============ Libusb is included as a submodule. On Linux, you'll need libudev to build libusb. On Ubuntu/Debian: `sudo apt-get install build-essential libudev-dev` Then, just run npm install usb to install from npm. See the bottom of this page for instructions for building from a git checkout. ### Windows Use [Zadig](http://zadig.akeo.ie/) to install the WinUSB driver for your USB device. Otherwise you will get `LIBUSB_ERROR_NOT_SUPPORTED` when attempting to open devices. API === var usb = require('usb') usb --- Top-level object. ### usb.getDeviceList() Return a list of `Device` objects for the USB devices attached to the system. ### usb.findByIds(vid, pid) Convenience method to get the first device with the specified VID and PID, or `undefined` if no such device is present. ### usb.LIBUSB_* Constant properties from libusb ### usb.setDebugLevel(level : int) Set the libusb debug level (between 0 and 4) Device ------ Represents a USB device. ### .busNumber Integer USB device number ### .deviceAddress Integer USB device address ### .portNumbers Array containing the USB device port numbers, or `undefined` if not supported on this platform. ### .deviceDescriptor Object with properties for the fields of the device descriptor: - bLength - bDescriptorType - bcdUSB - bDeviceClass - bDeviceSubClass - bDeviceProtocol - bMaxPacketSize0 - idVendor - idProduct - bcdDevice - iManufacturer - iProduct - iSerialNumber - bNumConfigurations ### .configDescriptor Object with properties for the fields of the configuration descriptor: - bLength - bDescriptorType - wTotalLength - bNumInterfaces - bConfigurationValue - iConfiguration - bmAttributes - bMaxPower - extra (Buffer containing any extra data or additional descriptors) ### .allConfigDescriptors Contains all config descriptors of the device (same structure as .configDescriptor above) ### .parent Contains the parent of the device, such as a hub. If there is no parent this property is set to `null`. ### .open() Open the device. All methods below require the device to be open before use. ### .close() Close the device. ### .controlTransfer(bmRequestType, bRequest, wValue, wIndex, data_or_length, callback(error, data)) Perform a control transfer with `libusb_control_transfer`. Parameter `data_or_length` can be a integer length for an IN transfer, or a Buffer for an out transfer. The type must match the direction specified in the MSB of bmRequestType. The `data` parameter of the callback is always undefined for OUT transfers, or will be passed a Buffer for IN transfers. A [package is available to calculate bmRequestType](https://www.npmjs.com/package/bmrequesttype) if needed. ### .setConfiguration(id, callback(error)) Set the device configuration to something other than the default (0). To use this, first call `.open(false)` (which tells it not to auto configure), then before claiming an interface, call this method. ### .getStringDescriptor(index, callback(error, data)) Perform a control transfer to retrieve a string descriptor ### .getBosDescriptor(callback(error, bosDescriptor)) Perform a control transfer to retrieve an object with properties for the fields of the Binary Object Store descriptor: - bLength - bDescriptorType - wTotalLength - bNumDeviceCaps ### .getCapabilities(callback(error, capabilities)) Retrieve a list of Capability objects for the Binary Object Store capabilities of the device. ### .interface(interface) Return the interface with the specified interface number. ### .interfaces List of Interface objects for the interfaces of the default configuration of the device. ### .timeout Timeout in milliseconds to use for control transfers. ### .reset(callback(error)) Performs a reset of the device. Callback is called when complete. Interface --------- ### .endpoint(address) Return the InEndpoint or OutEndpoint with the specified address. ### .endpoints List of endpoints on this interface: InEndpoint and OutEndpoint objects. ### .interface Integer interface number. ### .altSetting Integer alternate setting number. ### .setAltSetting(altSetting, callback(error)) Sets the alternate setting. It updates the `interface.endpoints` array to reflect the endpoints found in the alternate setting. ### .claim() Claims the interface. This method must be called before using any endpoints of this interface. ### .release([closeEndpoints], callback(error)) Releases the interface and resets the alternate setting. Calls callback when complete. It is an error to release an interface with pending transfers. If the optional closeEndpoints parameter is true, any active endpoint streams are stopped (see `Endpoint.stopStream`), and the interface is released after the stream transfers are cancelled. Transfers submitted individually with `Endpoint.transfer` are not affected by this parameter. ### .isKernelDriverActive() Returns `false` if a kernel driver is not active; `true` if active. ### .detachKernelDriver() Detaches the kernel driver from the interface. ### .attachKernelDriver() Re-attaches the kernel driver for the interface. ### .descriptor Object with fields from the interface descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bInterfaceNumber - bAlternateSetting - bNumEndpoints - bInterfaceClass - bInterfaceSubClass - bInterfaceProtocol - iInterface - extra (Buffer containing any extra data or additional descriptors) Capability --------- ### .type Integer capability type. ### .data Buffer capability data. ### .descriptor Object with fields from the capability descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bDevCapabilityType Endpoint -------- Common base for InEndpoint and OutEndpoint, see below. ### .direction Endpoint direction: `"in"` or `"out"`. ### .transferType Endpoint type: `usb.LIBUSB_TRANSFER_TYPE_BULK`, `usb.LIBUSB_TRANSFER_TYPE_INTERRUPT`, or `usb.LIBUSB_TRANSFER_TYPE_ISOCHRONOUS`. ### .descriptor Object with fields from the endpoint descriptor -- see libusb documentation or USB spec. - bLength - bDescriptorType - bEndpointAddress - bmAttributes - wMaxPacketSize - bInterval - bRefresh - bSynchAddress - extra (Buffer containing any extra data or additional descriptors) ### .timeout Sets the timeout in milliseconds for transfers on this endpoint. The default, `0`, is infinite timeout. ### .clearHalt(callback(error)) Clear the halt/stall condition for this endpoint. InEndpoint ---------- Endpoints in the IN direction (device->PC) have this type. ### .transfer(length, callback(error, data)) Perform a transfer to read data from the endpoint. If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback with all data once all packets are complete. `this` in the callback is the InEndpoint object. ### .startPoll(nTransfers=3, transferSize=maxPacketSize) Start polling the endpoint. The library will keep `nTransfers` transfers of size `transferSize` pending in the kernel at all times to ensure continuous data flow. This is handled by the libusb event thread, so it continues even if the Node v8 thread is busy. The `data` and `error` events are emitted as transfers complete. ### .stopPoll(cb) Stop polling. Further data may still be received. The `end` event is emitted and the callback is called once all transfers have completed or canceled. ### Event: data(data : Buffer) Emitted with data received by the polling transfers ### Event: error(error) Emitted when polling encounters an error. All in flight transfers will be automatically canceled and no further polling will be done. You have to wait for the `end` event before you can start polling again. ### Event: end Emitted when polling has been canceled OutEndpoint ----------- Endpoints in the OUT direction (PC->device) have this type. ### .transfer(data, callback(error)) Perform a transfer to write `data` to the endpoint. If length is greater than maxPacketSize, libusb will automatically split the transfer in multiple packets, and you will receive one callback once all packets are complete. `this` in the callback is the OutEndpoint object. ### Event: error(error) Emitted when the stream encounters an error. ### Event: end Emitted when the stream has been stopped and all pending requests have been completed. UsbDetection ------------ ### usb.on('attach', function(device) { ... }); Attaches a callback to plugging in a `device`. ### usb.on('detach', function(device) { ... }); Attaches a callback to unplugging a `device`. ### usb.refHotplugEvents(); Restore (re-reference) the hotplug events unreferenced by `unrefHotplugEvents()` ### usb.unrefHotplugEvents(); Listening to events will prevent the process to exit. By calling this function, hotplug events will be unreferenced by the event loop, allowing the process to exit even when listening for the `attach` and `detach` events. Development and testing ======================= To build from git: git clone --recursive https://github.com/node-usb/node-usb.git cd node-usb npm install To execute the unit tests, [CoffeeScript](http://coffeescript.org) is required. Run npm test Some tests require an [attached STM32F103 Microprocessor USB device with specific firmware](https://github.com/thegecko/node-usb-test-firmware). npm run --silent full-test npm run --silent valgrind Limitations =========== Does not support: - Configurations other than the default one - Isochronous transfers License ======= MIT Note that the compiled Node extension includes Libusb, and is thus subject to the LGPL. # estree-walker Simple utility for walking an [ESTree](https://github.com/estree/estree)-compliant AST, such as one generated by [acorn](https://github.com/marijnh/acorn). ## Installation ```bash npm i estree-walker ``` ## Usage ```js var walk = require( 'estree-walker' ).walk; var acorn = require( 'acorn' ); ast = acorn.parse( sourceCode, options ); // https://github.com/acornjs/acorn walk( ast, { enter: function ( node, parent, prop, index ) { // some code happens }, leave: function ( node, parent, prop, index ) { // some code happens } }); ``` Inside the `enter` function, calling `this.skip()` will prevent the node's children being walked, or the `leave` function (which is optional) being called. Call `this.replace(new_node)` in either `enter` or `leave` to replace the current node with a new one. Call `this.remove()` in either `enter` or `leave` to remove the current node. ## Why not use estraverse? The ESTree spec is evolving to accommodate ES6/7. I've had a couple of experiences where [estraverse](https://github.com/estools/estraverse) was unable to handle an AST generated by recent versions of acorn, because it hard-codes visitor keys. estree-walker, by contrast, simply enumerates a node's properties to find child nodes (and child lists of nodes), and is therefore resistant to spec changes. It's also much smaller. (The performance, if you're wondering, is basically identical.) None of which should be taken as criticism of estraverse, which has more features and has been battle-tested in many more situations, and for which I'm very grateful. ## License MIT # near-api-js [![Build Status](https://travis-ci.com/near/near-api-js.svg?branch=master)](https://travis-ci.com/near/near-api-js) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-api-js) A JavaScript/TypeScript library for development of DApps on the NEAR platform # Documentation [Read the TypeDoc API documentation](https://near.github.io/near-api-js/) --- # Examples ## [Quick Reference](https://github.com/near/near-api-js/blob/master/examples/quick-reference.md) _(Cheat sheet / quick reference)_ ## [Cookbook](https://github.com/near/near-api-js/blob/master/examples/cookbook/README.md) _(Common use cases / more complex examples)_ --- # Contribute to this library 1. Install dependencies yarn 2. Run continuous build with: yarn build -- -w # Publish Prepare `dist` version by running: yarn dist When publishing to npm use [np](https://github.com/sindresorhus/np). --- # Integration Test Start the node by following instructions from [nearcore](https://github.com/nearprotocol/nearcore), then yarn test Tests use sample contract from `near-hello` npm package, see https://github.com/nearprotocol/near-hello # Update error schema Follow next steps: 1. [Change hash for the commit with errors in the nearcore](https://github.com/near/near-api-js/blob/master/gen_error_types.js#L7-L9) 2. Fetch new schema: `node fetch_error_schema.js` 3. `yarn build` to update `lib/**.js` files # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # end-of-stream A node module that calls a callback when a readable/writable/duplex stream has completed or failed. npm install end-of-stream [![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream) ## Usage Simply pass a stream and a callback to the `eos`. Both legacy streams, streams2 and stream3 are supported. ``` js var eos = require('end-of-stream'); eos(readableStream, function(err) { // this will be set to the stream instance if (err) return console.log('stream had an error or closed early'); console.log('stream has ended', this === readableStream); }); eos(writableStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished', this === writableStream); }); eos(duplexStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended and finished', this === duplexStream); }); eos(duplexStream, {readable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished but might still be readable'); }); eos(duplexStream, {writable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended but might still be writable'); }); eos(readableStream, {error:false}, function(err) { // do not treat emit('error', err) as a end-of-stream }); ``` ## License MIT ## Related `end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # fast-glob > It's a very fast and efficient [glob][glob_definition] library for [Node.js][node_js]. This package provides methods for traversing the file system and returning pathnames that matched a defined set of a specified pattern according to the rules used by the Unix Bash shell with some simplifications, meanwhile results are returned in **arbitrary order**. Quick, simple, effective. ## Table of Contents <details> <summary><strong>Details</strong></summary> * [Highlights](#highlights) * [Donation](#donation) * [Old and modern mode](#old-and-modern-mode) * [Pattern syntax](#pattern-syntax) * [Basic syntax](#basic-syntax) * [Advanced syntax](#advanced-syntax) * [Installation](#installation) * [API](#api) * [Asynchronous](#asynchronous) * [Synchronous](#synchronous) * [Stream](#stream) * [patterns](#patterns) * [[options]](#options) * [Helpers](#helpers) * [generateTasks](#generatetaskspatterns-options) * [isDynamicPattern](#isdynamicpatternpattern-options) * [escapePath](#escapepathpattern) * [Options](#options-3) * [Common](#common) * [concurrency](#concurrency) * [cwd](#cwd) * [deep](#deep) * [followSymbolicLinks](#followsymboliclinks) * [fs](#fs) * [ignore](#ignore) * [suppressErrors](#suppresserrors) * [throwErrorOnBrokenSymbolicLink](#throwerroronbrokensymboliclink) * [Output control](#output-control) * [absolute](#absolute) * [markDirectories](#markdirectories) * [objectMode](#objectmode) * [onlyDirectories](#onlydirectories) * [onlyFiles](#onlyfiles) * [stats](#stats) * [unique](#unique) * [Matching control](#matching-control) * [braceExpansion](#braceexpansion) * [caseSensitiveMatch](#casesensitivematch) * [dot](#dot) * [extglob](#extglob) * [globstar](#globstar) * [baseNameMatch](#basenamematch) * [FAQ](#faq) * [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) * [How to write patterns on Windows?](#how-to-write-patterns-on-windows) * [Why are parentheses match wrong?](#why-are-parentheses-match-wrong) * [How to exclude directory from reading?](#how-to-exclude-directory-from-reading) * [How to use UNC path?](#how-to-use-unc-path) * [Compatible with `node-glob`?](#compatible-with-node-glob) * [Benchmarks](#benchmarks) * [Server](#server) * [Nettop](#nettop) * [Changelog](#changelog) * [License](#license) </details> ## Highlights * Fast. Probably the fastest. * Supports multiple and negative patterns. * Synchronous, Promise and Stream API. * Object mode. Can return more than just strings. * Error-tolerant. ## Donation Do you like this project? Support it by donating, creating an issue or pull request. [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)][paypal_mrmlnc] ## Old and modern mode This package works in two modes, depending on the environment in which it is used. * **Old mode**. Node.js below 10.10 or when the [`stats`](#stats) option is *enabled*. * **Modern mode**. Node.js 10.10+ and the [`stats`](#stats) option is *disabled*. The modern mode is faster. Learn more about the [internal mechanism][nodelib_fs_scandir_old_and_modern_modern]. ## Pattern syntax > :warning: Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. There is more than one form of syntax: basic and advanced. Below is a brief overview of the supported features. Also pay attention to our [FAQ](#faq). > :book: This package uses a [`micromatch`][micromatch] as a library for pattern matching. ### Basic syntax * An asterisk (`*`) — matches everything except slashes (path separators), hidden files (names starting with `.`). * A double star or globstar (`**`) — matches zero or more directories. * Question mark (`?`) – matches any single character except slashes (path separators). * Sequence (`[seq]`) — matches any character in sequence. > :book: A few additional words about the [basic matching behavior][picomatch_matching_behavior]. Some examples: * `src/**/*.js` — matches all files in the `src` directory (any level of nesting) that have the `.js` extension. * `src/*.??` — matches all files in the `src` directory (only first level of nesting) that have a two-character extension. * `file-[01].js` — matches files: `file-0.js`, `file-1.js`. ### Advanced syntax * [Escapes characters][micromatch_backslashes] (`\\`) — matching special characters (`$^*+?()[]`) as literals. * [POSIX character classes][picomatch_posix_brackets] (`[[:digit:]]`). * [Extended globs][micromatch_extglobs] (`?(pattern-list)`). * [Bash style brace expansions][micromatch_braces] (`{}`). * [Regexp character classes][micromatch_regex_character_classes] (`[1-5]`). * [Regex groups][regular_expressions_brackets] (`(a|b)`). > :book: A few additional words about the [advanced matching behavior][micromatch_extended_globbing]. Some examples: * `src/**/*.{css,scss}` — matches all files in the `src` directory (any level of nesting) that have the `.css` or `.scss` extension. * `file-[[:digit:]].js` — matches files: `file-0.js`, `file-1.js`, …, `file-9.js`. * `file-{1..3}.js` — matches files: `file-1.js`, `file-2.js`, `file-3.js`. * `file-(1|2)` — matches files: `file-1.js`, `file-2.js`. ## Installation ```console npm install fast-glob ``` ## API ### Asynchronous ```js fg(patterns, [options]) ``` Returns a `Promise` with an array of matching entries. ```js const fg = require('fast-glob'); const entries = await fg(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Synchronous ```js fg.sync(patterns, [options]) ``` Returns an array of matching entries. ```js const fg = require('fast-glob'); const entries = fg.sync(['.editorconfig', '**/index.js'], { dot: true }); // ['.editorconfig', 'services/index.js'] ``` ### Stream ```js fg.stream(patterns, [options]) ``` Returns a [`ReadableStream`][node_js_stream_readable_streams] when the `data` event will be emitted with matching entry. ```js const fg = require('fast-glob'); const stream = fg.stream(['.editorconfig', '**/index.js'], { dot: true }); for await (const entry of stream) { // .editorconfig // services/index.js } ``` #### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). > :1234: [Pattern syntax](#pattern-syntax) > > :warning: This package does not respect the order of patterns. First, all the negative patterns are applied, and only then the positive patterns. If you want to get a certain order of records, use sorting or split calls. #### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. ### Helpers #### `generateTasks(patterns, [options])` Returns the internal representation of patterns ([`Task`](./src/managers/tasks.ts) is a combining patterns by base directory). ```js fg.generateTasks('*'); [{ base: '.', // Parent directory for all patterns inside this task dynamic: true, // Dynamic or static patterns are in this task patterns: ['*'], positive: ['*'], negative: [] }] ``` ##### patterns * Required: `true` * Type: `string | string[]` Any correct pattern(s). ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `isDynamicPattern(pattern, [options])` Returns `true` if the passed pattern is a dynamic pattern. > :1234: [What is a static or dynamic pattern?](#what-is-a-static-or-dynamic-pattern) ```js fg.isDynamicPattern('*'); // true fg.isDynamicPattern('abc'); // false ``` ##### pattern * Required: `true` * Type: `string` Any correct pattern. ##### [options] * Required: `false` * Type: [`Options`](#options-3) See [Options](#options-3) section. #### `escapePath(pattern)` Returns a path with escaped special characters (`*?|(){}[]`, `!` at the beginning of line, `@+!` before the opening parenthesis). ```js fg.escapePath('!abc'); // \\!abc fg.escapePath('C:/Program Files (x86)'); // C:/Program Files \\(x86\\) ``` ##### pattern * Required: `true` * Type: `string` Any string, for example, a path to a file. ## Options ### Common options #### concurrency * Type: `number` * Default: `os.cpus().length` Specifies the maximum number of concurrent requests from a reader to read directories. > :book: The higher the number, the higher the performance and load on the file system. If you want to read in quiet mode, set the value to a comfortable number or `1`. #### cwd * Type: `string` * Default: `process.cwd()` The current working directory in which to search. #### deep * Type: `number` * Default: `Infinity` Specifies the maximum depth of a read directory relative to the start directory. For example, you have the following tree: ```js dir/ └── one/ // 1 └── two/ // 2 └── file.js // 3 ``` ```js // With base directory fg.sync('dir/**', { onlyFiles: false, deep: 1 }); // ['dir/one'] fg.sync('dir/**', { onlyFiles: false, deep: 2 }); // ['dir/one', 'dir/one/two'] // With cwd option fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 1 }); // ['one'] fg.sync('**', { onlyFiles: false, cwd: 'dir', deep: 2 }); // ['one', 'one/two'] ``` > :book: If you specify a pattern with some base directory, this directory will not participate in the calculation of the depth of the found directories. Think of it as a [`cwd`](#cwd) option. #### followSymbolicLinks * Type: `boolean` * Default: `true` Indicates whether to traverse descendants of symbolic link directories when expanding `**` patterns. > :book: Note that this option does not affect the base directory of the pattern. For example, if `./a` is a symlink to directory `./b` and you specified `['./a**', './b/**']` patterns, then directory `./a` will still be read. > :book: If the [`stats`](#stats) option is specified, the information about the symbolic link (`fs.lstat`) will be replaced with information about the entry (`fs.stat`) behind it. #### fs * Type: `FileSystemAdapter` * Default: `fs.*` Custom implementation of methods for working with the file system. ```ts export interface FileSystemAdapter { lstat?: typeof fs.lstat; stat?: typeof fs.stat; lstatSync?: typeof fs.lstatSync; statSync?: typeof fs.statSync; readdir?: typeof fs.readdir; readdirSync?: typeof fs.readdirSync; } ``` #### ignore * Type: `string[]` * Default: `[]` An array of glob patterns to exclude matches. This is an alternative way to use negative patterns. ```js dir/ ├── package-lock.json └── package.json ``` ```js fg.sync(['*.json', '!package-lock.json']); // ['package.json'] fg.sync('*.json', { ignore: ['package-lock.json'] }); // ['package.json'] ``` #### suppressErrors * Type: `boolean` * Default: `false` By default this package suppress only `ENOENT` errors. Set to `true` to suppress any error. > :book: Can be useful when the directory has entries with a special level of access. #### throwErrorOnBrokenSymbolicLink * Type: `boolean` * Default: `false` Throw an error when symbolic link is broken if `true` or safely return `lstat` call if `false`. > :book: This option has no effect on errors when reading the symbolic link directory. ### Output control #### absolute * Type: `boolean` * Default: `false` Return the absolute path for entries. ```js fg.sync('*.js', { absolute: false }); // ['index.js'] fg.sync('*.js', { absolute: true }); // ['/home/user/index.js'] ``` > :book: This option is required if you want to use negative patterns with absolute path, for example, `!${__dirname}/*.js`. #### markDirectories * Type: `boolean` * Default: `false` Mark the directory path with the final slash. ```js fg.sync('*', { onlyFiles: false, markDirectories: false }); // ['index.js', 'controllers'] fg.sync('*', { onlyFiles: false, markDirectories: true }); // ['index.js', 'controllers/'] ``` #### objectMode * Type: `boolean` * Default: `false` Returns objects (instead of strings) describing entries. ```js fg.sync('*', { objectMode: false }); // ['src/index.js'] fg.sync('*', { objectMode: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent> }] ``` The object has the following fields: * name (`string`) — the last part of the path (basename) * path (`string`) — full path relative to the pattern base directory * dirent ([`fs.Dirent`][node_js_fs_class_fs_dirent]) — instance of `fs.Dirent` > :book: An object is an internal representation of entry, so getting it does not affect performance. #### onlyDirectories * Type: `boolean` * Default: `false` Return only directories. ```js fg.sync('*', { onlyDirectories: false }); // ['index.js', 'src'] fg.sync('*', { onlyDirectories: true }); // ['src'] ``` > :book: If `true`, the [`onlyFiles`](#onlyfiles) option is automatically `false`. #### onlyFiles * Type: `boolean` * Default: `true` Return only files. ```js fg.sync('*', { onlyFiles: false }); // ['index.js', 'src'] fg.sync('*', { onlyFiles: true }); // ['index.js'] ``` #### stats * Type: `boolean` * Default: `false` Enables an [object mode](#objectmode) with an additional field: * stats ([`fs.Stats`][node_js_fs_class_fs_stats]) — instance of `fs.Stats` ```js fg.sync('*', { stats: false }); // ['src/index.js'] fg.sync('*', { stats: true }); // [{ name: 'index.js', path: 'src/index.js', dirent: <fs.Dirent>, stats: <fs.Stats> }] ``` > :book: Returns `fs.stat` instead of `fs.lstat` for symbolic links when the [`followSymbolicLinks`](#followsymboliclinks) option is specified. > > :warning: Unlike [object mode](#objectmode) this mode requires additional calls to the file system. On average, this mode is slower at least twice. See [old and modern mode](#old-and-modern-mode) for more details. #### unique * Type: `boolean` * Default: `true` Ensures that the returned entries are unique. ```js fg.sync(['*.json', 'package.json'], { unique: false }); // ['package.json', 'package.json'] fg.sync(['*.json', 'package.json'], { unique: true }); // ['package.json'] ``` If `true` and similar entries are found, the result is the first found. ### Matching control #### braceExpansion * Type: `boolean` * Default: `true` Enables Bash-like brace expansion. > :1234: [Syntax description][bash_hackers_syntax_expansion_brace] or more [detailed description][micromatch_braces]. ```js dir/ ├── abd ├── acd └── a{b,c}d ``` ```js fg.sync('a{b,c}d', { braceExpansion: false }); // ['a{b,c}d'] fg.sync('a{b,c}d', { braceExpansion: true }); // ['abd', 'acd'] ``` #### caseSensitiveMatch * Type: `boolean` * Default: `true` Enables a [case-sensitive][wikipedia_case_sensitivity] mode for matching files. ```js dir/ ├── file.txt └── File.txt ``` ```js fg.sync('file.txt', { caseSensitiveMatch: false }); // ['file.txt', 'File.txt'] fg.sync('file.txt', { caseSensitiveMatch: true }); // ['file.txt'] ``` #### dot * Type: `boolean` * Default: `false` Allow patterns to match entries that begin with a period (`.`). > :book: Note that an explicit dot in a portion of the pattern will always match dot files. ```js dir/ ├── .editorconfig └── package.json ``` ```js fg.sync('*', { dot: false }); // ['package.json'] fg.sync('*', { dot: true }); // ['.editorconfig', 'package.json'] ``` #### extglob * Type: `boolean` * Default: `true` Enables Bash-like `extglob` functionality. > :1234: [Syntax description][micromatch_extglobs]. ```js dir/ ├── README.md └── package.json ``` ```js fg.sync('*.+(json|md)', { extglob: false }); // [] fg.sync('*.+(json|md)', { extglob: true }); // ['README.md', 'package.json'] ``` #### globstar * Type: `boolean` * Default: `true` Enables recursively repeats a pattern containing `**`. If `false`, `**` behaves exactly like `*`. ```js dir/ └── a └── b ``` ```js fg.sync('**', { onlyFiles: false, globstar: false }); // ['a'] fg.sync('**', { onlyFiles: false, globstar: true }); // ['a', 'a/b'] ``` #### baseNameMatch * Type: `boolean` * Default: `false` If set to `true`, then patterns without slashes will be matched against the basename of the path if it contains slashes. ```js dir/ └── one/ └── file.md ``` ```js fg.sync('*.md', { baseNameMatch: false }); // [] fg.sync('*.md', { baseNameMatch: true }); // ['one/file.md'] ``` ## FAQ ## What is a static or dynamic pattern? All patterns can be divided into two types: * **static**. A pattern is considered static if it can be used to get an entry on the file system without using matching mechanisms. For example, the `file.js` pattern is a static pattern because we can just verify that it exists on the file system. * **dynamic**. A pattern is considered dynamic if it cannot be used directly to find occurrences without using a matching mechanisms. For example, the `*` pattern is a dynamic pattern because we cannot use this pattern directly. A pattern is considered dynamic if it contains the following characters (`…` — any characters or their absence) or options: * The [`caseSensitiveMatch`](#casesensitivematch) option is disabled * `\\` (the escape character) * `*`, `?`, `!` (at the beginning of line) * `[…]` * `(…|…)` * `@(…)`, `!(…)`, `*(…)`, `?(…)`, `+(…)` (respects the [`extglob`](#extglob) option) * `{…,…}`, `{…..…}` (respects the [`braceExpansion`](#braceexpansion) option) ## How to write patterns on Windows? Always use forward-slashes in glob expressions (patterns and [`ignore`](#ignore) option). Use backslashes for escaping characters. With the [`cwd`](#cwd) option use a convenient format. **Bad** ```ts [ 'directory\\*', path.join(process.cwd(), '**') ] ``` **Good** ```ts [ 'directory/*', path.join(process.cwd(), '**').replace(/\\/g, '/') ] ``` > :book: Use the [`normalize-path`][npm_normalize_path] or the [`unixify`][npm_unixify] package to convert Windows-style path to a Unix-style path. Read more about [matching with backslashes][micromatch_backslashes]. ## Why are parentheses match wrong? ```js dir/ └── (special-*file).txt ``` ```js fg.sync(['(special-*file).txt']) // [] ``` Refers to Bash. You need to escape special characters: ```js fg.sync(['\\(special-*file\\).txt']) // ['(special-*file).txt'] ``` Read more about [matching special characters as literals][picomatch_matching_special_characters_as_literals]. ## How to exclude directory from reading? You can use a negative pattern like this: `!**/node_modules` or `!**/node_modules/**`. Also you can use [`ignore`](#ignore) option. Just look at the example below. ```js first/ ├── file.md └── second/ └── file.txt ``` If you don't want to read the `second` directory, you must write the following pattern: `!**/second` or `!**/second/**`. ```js fg.sync(['**/*.md', '!**/second']); // ['first/file.md'] fg.sync(['**/*.md'], { ignore: ['**/second/**'] }); // ['first/file.md'] ``` > :warning: When you write `!**/second/**/*` it means that the directory will be **read**, but all the entries will not be included in the results. You have to understand that if you write the pattern to exclude directories, then the directory will not be read under any circumstances. ## How to use UNC path? You cannot use [Uniform Naming Convention (UNC)][unc_path] paths as patterns (due to syntax), but you can use them as [`cwd`](#cwd) directory. ```ts fg.sync('*', { cwd: '\\\\?\\C:\\Python27' /* or //?/C:/Python27 */ }); fg.sync('Python27/*', { cwd: '\\\\?\\C:\\' /* or //?/C:/ */ }); ``` ## Compatible with `node-glob`? | node-glob | fast-glob | | :----------: | :-------: | | `cwd` | [`cwd`](#cwd) | | `root` | – | | `dot` | [`dot`](#dot) | | `nomount` | – | | `mark` | [`markDirectories`](#markdirectories) | | `nosort` | – | | `nounique` | [`unique`](#unique) | | `nobrace` | [`braceExpansion`](#braceexpansion) | | `noglobstar` | [`globstar`](#globstar) | | `noext` | [`extglob`](#extglob) | | `nocase` | [`caseSensitiveMatch`](#casesensitivematch) | | `matchBase` | [`baseNameMatch`](#basenamematch) | | `nodir` | [`onlyFiles`](#onlyfiles) | | `ignore` | [`ignore`](#ignore) | | `follow` | [`followSymbolicLinks`](#followsymboliclinks) | | `realpath` | – | | `absolute` | [`absolute`](#absolute) | ## Benchmarks ### Server Link: [Vultr Bare Metal][vultr_pricing_baremetal] * Processor: E3-1270v6 (8 CPU) * RAM: 32GB * Disk: SSD ([Intel DC S3520 SSDSC2BB240G7][intel_ssd]) You can see results [here][github_gist_benchmark_server] for latest release. ### Nettop Link: [Zotac bi323][zotac_bi323] * Processor: Intel N3150 (4 CPU) * RAM: 8GB * Disk: SSD ([Silicon Power SP060GBSS3S55S25][silicon_power_ssd]) You can see results [here][github_gist_benchmark_nettop] for latest release. ## Changelog See the [Releases section of our GitHub project][github_releases] for changelog for each release version. ## License This software is released under the terms of the MIT license. [bash_hackers_syntax_expansion_brace]: https://wiki.bash-hackers.org/syntax/expansion/brace [github_gist_benchmark_nettop]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-nettop-product-txt [github_gist_benchmark_server]: https://gist.github.com/mrmlnc/f06246b197f53c356895fa35355a367c#file-fg-benchmark-server-product-txt [github_releases]: https://github.com/mrmlnc/fast-glob/releases [glob_definition]: https://en.wikipedia.org/wiki/Glob_(programming) [glob_linux_man]: http://man7.org/linux/man-pages/man3/glob.3.html [intel_ssd]: https://ark.intel.com/content/www/us/en/ark/products/93012/intel-ssd-dc-s3520-series-240gb-2-5in-sata-6gb-s-3d1-mlc.html [micromatch_backslashes]: https://github.com/micromatch/micromatch#backslashes [micromatch_braces]: https://github.com/micromatch/braces [micromatch_extended_globbing]: https://github.com/micromatch/micromatch#extended-globbing [micromatch_extglobs]: https://github.com/micromatch/micromatch#extglobs [micromatch_regex_character_classes]: https://github.com/micromatch/micromatch#regex-character-classes [micromatch]: https://github.com/micromatch/micromatch [node_js_fs_class_fs_dirent]: https://nodejs.org/api/fs.html#fs_class_fs_dirent [node_js_fs_class_fs_stats]: https://nodejs.org/api/fs.html#fs_class_fs_stats [node_js_stream_readable_streams]: https://nodejs.org/api/stream.html#stream_readable_streams [node_js]: https://nodejs.org/en [nodelib_fs_scandir_old_and_modern_modern]: https://github.com/nodelib/nodelib/blob/master/packages/fs/fs.scandir/README.md#old-and-modern-mode [npm_normalize_path]: https://www.npmjs.com/package/normalize-path [npm_unixify]: https://www.npmjs.com/package/unixify [paypal_mrmlnc]:https://paypal.me/mrmlnc [picomatch_matching_behavior]: https://github.com/micromatch/picomatch#matching-behavior-vs-bash [picomatch_matching_special_characters_as_literals]: https://github.com/micromatch/picomatch#matching-special-characters-as-literals [picomatch_posix_brackets]: https://github.com/micromatch/picomatch#posix-brackets [regular_expressions_brackets]: https://www.regular-expressions.info/brackets.html [silicon_power_ssd]: https://www.silicon-power.com/web/product-1 [unc_path]: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/62e862f4-2a51-452e-8eeb-dc4ff5ee33cc [vultr_pricing_baremetal]: https://www.vultr.com/pricing/baremetal [wikipedia_case_sensitivity]: https://en.wikipedia.org/wiki/Case_sensitivity [zotac_bi323]: https://www.zotac.com/ee/product/mini_pcs/zbox-bi323 # Tools ## clang-format The clang-format checking tools is designed to check changed lines of code compared to given git-refs. ## Migration Script The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. ### How To Use To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. ``` npm install node-addon-api ``` Then run the script passing your project directory ``` node ./node_modules/node-addon-api/tools/conversion.js ./ ``` After finish, recompile and debug things that are missed by the script. ### Quick Fixes Here is the list of things that can be fixed easily. 1. Change your methods' return value to void if it doesn't return value to JavaScript. 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); ### Major Reconstructions The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as ``` [ClassName](const Napi::CallbackInfo& info); ``` and define it as ``` [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ ... } ``` This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 2. Move your original constructor code into the new constructor. Delete your original constructor. 3. In your class initialization function, associate native methods in the following way. ``` Napi::FunctionReference constructor; void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { Napi::HandleScope scope(env); Napi::Function ctor = DefineClass(env, "Canvas", { InstanceMethod<&[ClassName]::Func1>("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. node-bindings ============= ### Helper module for loading your native module's `.node` file This is a helper module for authors of Node.js native addon modules. It is basically the "swiss army knife" of `require()`ing your native module's `.node` file. Throughout the course of Node's native addon history, addons have ended up being compiled in a variety of different places, depending on which build tool and which version of node was used. To make matters worse, now the `gyp` build tool can produce either a __Release__ or __Debug__ build, each being built into different locations. This module checks _all_ the possible locations that a native addon would be built at, and returns the first one that loads successfully. Installation ------------ Install with `npm`: ``` bash $ npm install --save bindings ``` Or add it to the `"dependencies"` section of your `package.json` file. Example ------- `require()`ing the proper bindings file for the current node version, platform and architecture is as simple as: ``` js var bindings = require('bindings')('binding.node') // Use your bindings defined in your C files bindings.your_c_function() ``` Nice Error Output ----------------- When the `.node` file could not be loaded, `node-bindings` throws an Error with a nice error message telling you exactly what was tried. You can also check the `err.tries` Array property. ``` Error: Could not load the bindings file. Tried: → /Users/nrajlich/ref/build/binding.node → /Users/nrajlich/ref/build/Debug/binding.node → /Users/nrajlich/ref/build/Release/binding.node → /Users/nrajlich/ref/out/Debug/binding.node → /Users/nrajlich/ref/Debug/binding.node → /Users/nrajlich/ref/out/Release/binding.node → /Users/nrajlich/ref/Release/binding.node → /Users/nrajlich/ref/build/default/binding.node → /Users/nrajlich/ref/compiled/0.8.2/darwin/x64/binding.node at bindings (/Users/nrajlich/ref/node_modules/bindings/bindings.js:84:13) at Object.<anonymous> (/Users/nrajlich/ref/lib/ref.js:5:47) at Module._compile (module.js:449:26) at Object.Module._extensions..js (module.js:467:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) ... ``` The searching for the `.node` file will originate from the first directory in which has a `package.json` file is found. License ------- (The MIT License) Copyright (c) 2012 Nathan Rajlich &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Javascript Error Polyfill [![Build Status](https://travis-ci.org/inf3rno/error-polyfill.png?branch=master)](https://travis-ci.org/inf3rno/error-polyfill) Implementing the [V8 Stack Trace API](https://github.com/v8/v8/wiki/Stack-Trace-API) in non-V8 environments as much as possible ## Installation ```bash npm install error-polyfill ``` ```bash bower install error-polyfill ``` ### Environment compatibility Tested on the following environments: Windows 7 - **Node.js** 9.6 - **Chrome** 64.0 - **Firefox** 58.0 - **Internet Explorer** 10.0, 11.0 - **PhantomJS** 2.1 - **Opera** 51.0 Travis - **Node.js** 8, 9 - **Chrome** - **Firefox** - **PhantomJS** The polyfill might work on other environments too due to its adaptive design. I use [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. ### Requirements ES5 support is required, without that the lib throws an Error and stops working. The ES5 features are tested by the [capability](https://github.com/inf3rno/capability) lib run time. Classes are created by the [o3](https://github.com/inf3rno/o3) lib. Utility functions are implemented in the [u3](https://github.com/inf3rno/u3) lib. ## API documentation ### Usage In this documentation I used the framework as follows: ```js require("error-polyfill"); // <- your code here ``` It is recommended to require the polyfill in your main script. ### Getting a past stack trace with `Error.getStackTrace` This static method is not part of the V8 Stack Trace API, but it is recommended to **use `Error.getStackTrace(throwable)` instead of `throwable.stack`** to get the stack trace of Error instances! Explanation: By non-V8 environments we cannot replace the default stack generation algorithm, so we need a workaround to generate the stack when somebody tries to access it. So the original stack string will be parsed and the result will be properly formatted by accessing the stack using the `Error.getStackTrace` method. Arguments and return values: - The `throwable` argument should be an `Error` (descendant) instance, but it can be an `Object` instance as well. - The return value is the generated `stack` of the `throwable` argument. Example: ```js try { theNotDefinedFunction(); } catch (error) { console.log(Error.getStackTrace(error)); // ReferenceError: theNotDefinedFunction is not defined // at ... // ... } ``` ### Capturing the present stack trace with `Error.captureStackTrace` The `Error.captureStackTrace(throwable [, terminator])` sets the present stack above the `terminator` on the `throwable`. Arguments and return values: - The `throwable` argument should be an instance of an `Error` descendant, but it can be an `Object` instance as well. It is recommended to use `Error` descendant instances instead of inline objects, because we can recognize them by type e.g. `error instanceof UserError`. - The optional `terminator` argument should be a `Function`. Only the calls before this function will be reported in the stack, so without a `terminator` argument, the last call in the stack will be the call of the `Error.captureStackTrace`. - There is no return value, the `stack` will be set on the `throwable` so you will be able to access it using `Error.getStackTrace`. The format of the stack depends on the `Error.prepareStackTrace` implementation. Example: ```js var UserError = function (message){ this.name = "UserError"; this.message = message; Error.captureStackTrace(this, this.constructor); }; UserError.prototype = Object.create(Error.prototype); function codeSmells(){ throw new UserError("What's going on?!"); } codeSmells(); // UserError: What's going on?! // at codeSmells (myModule.js:23:1) // ... ``` Limitations: By the current implementation the `terminator` can be only the `Error.captureStackTrace` caller function. This will change soon, but in certain conditions, e.g. by using strict mode (`"use strict";`) it is not possible to access the information necessary to implement this feature. You will get an empty `frames` array and a `warning` in the `Error.prepareStackTrace` when the stack parser meets with such conditions. ### Formatting the stack trace with `Error.prepareStackTrace` The `Error.prepareStackTrace(throwable, frames [, warnings])` formats the stack `frames` and returns the `stack` value for `Error.captureStackTrace` or `Error.getStackTrace`. The native implementation returns a stack string, but you can override that by setting a new function value. Arguments and return values: - The `throwable` argument is an `Error` or `Object` instance coming from the `Error.captureStackTrace` or from the creation of a new `Error` instance. Be aware that in some environments you need to throw that instance to get a parsable stack. Without that you will get only a `warning` by trying to access the stack with `Error.getStackTrace`. - The `frames` argument is an array of `Frame` instances. Each `frame` represents a function call in the stack. You can use these frames to build a stack string. To access information about individual frames you can use the following methods. - `frame.toString()` - Returns the string representation of the frame, e.g. `codeSmells (myModule.js:23:1)`. - `frame.getThis()` - **Cannot be supported.** Returns the context of the call, only V8 environments support this natively. - `frame.getTypeName()` - **Not implemented yet.** Returns the type name of the context, by the global namespace it is `Window` in Chrome. - `frame.getFunction()` - Returns the called function or `undefined` by strict mode. - `frame.getFunctionName()` - **Not implemented yet.** Returns the name of the called function. - `frame.getMethodName()` - **Not implemented yet.** Returns the method name of the called function is a method of an object. - `frame.getFileName()` - **Not implemented yet.** Returns the file name where the function was called. - `frame.getLineNumber()` - **Not implemented yet.** Returns at which line the function was called in the file. - `frame.getColumnNumber()` - **Not implemented yet.** Returns at which column the function was called in the file. This information is not always available. - `frame.getEvalOrigin()` - **Not implemented yet.** Returns the original of an `eval` call. - `frame.isTopLevel()` - **Not implemented yet.** Returns whether the function was called from the top level. - `frame.isEval()` - **Not implemented yet.** Returns whether the called function was `eval`. - `frame.isNative()` - **Not implemented yet.** Returns whether the called function was native. - `frame.isConstructor()` - **Not implemented yet.** Returns whether the called function was a constructor. - The optional `warnings` argument contains warning messages coming from the stack parser. It is not part of the V8 Stack Trace API. - The return value will be the stack you can access with `Error.getStackTrace(throwable)`. If it is an object, it is recommended to add a `toString` method, so you will be able to read it in the console. Example: ```js Error.prepareStackTrace = function (throwable, frames, warnings) { var string = ""; string += throwable.name || "Error"; string += ": " + (throwable.message || ""); if (warnings instanceof Array) for (var warningIndex in warnings) { var warning = warnings[warningIndex]; string += "\n # " + warning; } for (var frameIndex in frames) { var frame = frames[frameIndex]; string += "\n at " + frame.toString(); } return string; }; ``` ### Stack trace size limits with `Error.stackTraceLimit` **Not implemented yet.** You can set size limits on the stack trace, so you won't have any problems because of too long stack traces. Example: ```js Error.stackTraceLimit = 10; ``` ### Handling uncaught errors and rejections **Not implemented yet.** ## Differences between environments and modes Since there is no Stack Trace API standard, every browsers solves this problem differently. I try to document what I've found about these differences as detailed as possible, so it will be easier to follow the code. Overriding the `error.stack` property with custom Stack instances - by Node.js and Chrome the `Error.prepareStackTrace()` can override every `error.stack` automatically right by creation - by Firefox, Internet Explorer and Opera you cannot automatically override every `error.stack` by native errors - by PhantomJS you cannot override the `error.stack` property of native errors, it is not configurable Capturing the current stack trace - by Node.js, Chrome, Firefox and Opera the stack property is added by instantiating a native error - by Node.js and Chrome the stack creation is lazy loaded and cached, so the `Error.prepareStackTrace()` is called only by the first access - by Node.js and Chrome the current stack can be added to any object with `Error.captureStackTrace()` - by Internet Explorer the stack is created by throwing a native error - by PhantomJS the stack is created by throwing any object, but not a primitive Accessing the stack - by Node.js, Chrome, Firefox, Internet Explorer, Opera and PhantomJS you can use the `error.stack` property - by old Opera you have to use the `error.stacktrace` property to get the stack Prefixes and postfixes on the stack string - by Node.js, Chrome, Internet Explorer and Opera you have the `error.name` and the `error.message` in a `{name}: {message}` format at the beginning of the stack string - by Firefox and PhantomJS the stack string does not contain the `error.name` and the `error.message` - by Firefox you have an empty line at the end of the stack string Accessing the stack frames array - by Node.js and Chrome you can access the frame objects directly by overriding the `Error.prepareStackTrace()` - by Firefox, Internet Explorer, PhantomJS, and Opera you need to parse the stack string in order to get the frames The structure of the frame string - by Node.js and Chrome - the frame string of calling a function from a module: `thirdFn (http://localhost/myModule.js:45:29)` - the frame strings contain an ` at ` prefix, which is not present by the `frame.toString()` output, so it is added by the `stack.toString()` - by Firefox - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Internet Explorer - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45:29)` - by PhantomJS - the frame string of calling a function from a module: `thirdFn@http://localhost/myModule.js:45:29` - by Opera - the frame string of calling a function from a module: ` at thirdFn (http://localhost/myModule.js:45)` Accessing information by individual frames - by Node.js and Chrome the `frame.getThis()` and the `frame.getFunction()` returns `undefined` by frames originate from [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) code - by Firefox, Internet Explorer, PhantomJS, and Opera the context of the function calls is not accessible, so the `frame.getThis()` cannot be implemented - by Firefox, Internet Explorer, PhantomJS, and Opera functions are not accessible with `arguments.callee.caller` by frames originate from strict mode, so by these frames `frame.getFunction()` can return only `undefined` (this is consistent with V8 behavior) ## License MIT - 2016 Jánszky László Lajos # cliui ![ci](https://github.com/yargs/cliui/workflows/ci/badge.svg) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) ![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/cliui) easily create complex multi-column command-line-interfaces. ## Example ```js const ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` ## Deno/ESM Support As of `v7` `cliui` supports [Deno](https://github.com/denoland/deno) and [ESM](https://nodejs.org/api/esm.html#esm_ecmascript_modules): ```typescript import cliui from "https://deno.land/x/cliui/deno.ts"; const ui = cliui({}) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 1, 0] }) ui.div({ text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.div`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## Security contact information To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # v8flags [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Get available v8 and Node.js flags. ## Usage ```js const v8flags = require('v8flags'); v8flags(function(err, results) { console.log(results); // [ '--use_strict', // '--es5_readonly', // '--es52_globals', // '--harmony_typeof', // '--harmony_scoping', // '--harmony_modules', // '--harmony_proxies', // '--harmony_collections', // '--harmony', // ... }); ``` ## API ### `v8flags(cb)` Finds the available flags and calls the passed callback with any errors and an array of flag results. ### `v8flags.configfile` The name of the cache file for flags. ### `v8flags.configPath` The filepath location of the `configfile` above. ## License MIT [downloads-image]: http://img.shields.io/npm/dm/v8flags.svg [npm-url]: https://www.npmjs.com/package/v8flags [npm-image]: http://img.shields.io/npm/v/v8flags.svg [travis-url]: https://travis-ci.org/gulpjs/v8flags [travis-image]: http://img.shields.io/travis/gulpjs/v8flags.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/v8flags [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/v8flags.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/v8flags [coveralls-image]: http://img.shields.io/coveralls/gulpjs/v8flags/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # mkdirp-classic Just a non-deprecated mirror of [mkdirp 0.5.2](https://github.com/substack/node-mkdirp/tree/0.5.1) for use in modules where we depend on the non promise interface. ``` npm install mkdirp-classic ``` ## Usage ``` js // See the above link ``` ## License MIT # rc The non-configurable configuration loader for lazy people. ## Usage The only option is to pass rc the name of your app, and your default configuration. ```javascript var conf = require('rc')(appname, { //defaults go here. port: 2468, //defaults which are objects will be merged, not replaced views: { engine: 'jade' } }); ``` `rc` will return your configuration options merged with the defaults you specify. If you pass in a predefined defaults object, it will be mutated: ```javascript var conf = {}; require('rc')(appname, conf); ``` If `rc` finds any config files for your app, the returned config object will have a `configs` array containing their paths: ```javascript var appCfg = require('rc')(appname, conf); appCfg.configs[0] // /etc/appnamerc appCfg.configs[1] // /home/dominictarr/.config/appname appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] ``` ## Standards Given your application name (`appname`), rc will look in all the obvious places for configuration. * command line arguments, parsed by minimist _(e.g. `--foo baz`, also nested: `--foo.bar=baz`)_ * environment variables prefixed with `${appname}_` * or use "\_\_" to indicate nested properties <br/> _(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ * if you passed an option `--config file` then from that file * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. * `$HOME/.${appname}rc` * `$HOME/.${appname}/config` * `$HOME/.config/${appname}` * `$HOME/.config/${appname}/config` * `/etc/${appname}rc` * `/etc/${appname}/config` * the defaults object you passed in. All configuration sources that were found will be flattened into one object, so that sources **earlier** in this list override later ones. ## Configuration File Formats Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. **No** file extension (`.json` or `.ini`) should be used. The example configurations below are equivalent: #### Formatted as `ini` ``` ; You can include comments in `ini` format if you want. dependsOn=0.10.0 ; `rc` has built-in support for ini sections, see? [commands] www = ./commands/www console = ./commands/repl ; You can even do nested sections [generators.options] engine = ejs [generators.modules] new = generate-new engine = generate-backend ``` #### Formatted as `json` ```javascript { // You can even comment your JSON, if you want "dependsOn": "0.10.0", "commands": { "www": "./commands/www", "console": "./commands/repl" }, "generators": { "options": { "engine": "ejs" }, "modules": { "new": "generate-new", "backend": "generate-backend" } } } ``` Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). > Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. To ensure that string representations of booleans and numbers are always converted into their proper types (especially useful if you intend to do strict `===` comparisons), consider using a module such as [parse-strings-in-object](https://github.com/anselanza/parse-strings-in-object) to wrap the config object returned from rc. ## Simple example demonstrating precedence Assume you have an application like this (notice the hard-coded defaults passed to rc): ``` const conf = require('rc')('myapp', { port: 12345, mode: 'test' }); console.log(JSON.stringify(conf, null, 2)); ``` You also have a file `config.json`, with these contents: ``` { "port": 9000, "foo": "from config json", "something": "else" } ``` And a file `.myapprc` in the same folder, with these contents: ``` { "port": "3001", "foo": "bar" } ``` Here is the expected output from various commands: `node .` ``` { "port": "3001", "mode": "test", "foo": "bar", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Default `mode` from hard-coded object is retained, but port is overridden by `.myapprc` file (automatically found based on appname match), and `foo` is added.* `node . --foo baz` ``` { "port": "3001", "mode": "test", "foo": "baz", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Same result as above but `foo` is overridden because command-line arguments take precedence over `.myapprc` file.* `node . --foo barbar --config config.json` ``` { "port": 9000, "mode": "test", "foo": "barbar", "something": "else", "_": [], "config": "config.json", "configs": [ "/Users/stephen/repos/conftest/.myapprc", "config.json" ] } ``` *Now the `port` comes from the `config.json` file specified (overriding the value from `.myapprc`), and `foo` value is overriden by command-line despite also being specified in the `config.json` file.* ## Advanced Usage #### Pass in your own `argv` You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). ```javascript require('rc')(appname, defaults, customArgvParser); ``` ## Pass in your own parser If you have a special need to use a non-standard parser, you can do so by passing in the parser as the 4th argument. (leave the 3rd as null to get the default args parser) ```javascript require('rc')(appname, defaults, null, parser); ``` This may also be used to force a more strict format, such as strict, valid JSON only. ## Note on Performance `rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) ## License Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 # axios // helpers The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like: - Browser polyfills - Managing cookies - Parsing HTTP headers # mime-db [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][ci-image]][ci-url] [![Coverage Status][coveralls-image]][coveralls-url] This is a large database of mime types and information about them. It consists of a single, public JSON file and does not include any logic, allowing it to remain as un-opinionated as possible with an API. It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation ```bash npm install mime-db ``` ### Database Download If you're crazy enough to use this in the browser, you can just grab the JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the JSON format may change in the future. ``` https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json ``` ## Usage ```js var db = require('mime-db') // grab data on .js files var data = db['application/javascript'] ``` ## Data Structure The JSON file is a map lookup for lowercased mime types. Each mime type has the following properties: - `.source` - where the mime type is defined. If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type can be gzipped. - `.charset` - the default charset associated with this type, if any. If unknown, every property could be `undefined`. ## Contributing To edit the database, only make PRs against `src/custom-types.json` or `src/custom-suffix.json`. The `src/custom-types.json` file is a JSON object with the MIME type as the keys and the values being an object with the following keys: - `compressible` - leave out if you don't know, otherwise `true`/`false` to indicate whether the data represented by the type is typically compressible. - `extensions` - include an array of file extensions that are associated with the type. - `notes` - human-readable notes about the type, typically what the type is. - `sources` - include an array of URLs of where the MIME type and the associated extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); links to type aggregating sites and Wikipedia are _not acceptable_. To update the build, run `npm run build`. ### Adding Custom Media Types The best way to get new media types included in this library is to register them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. If that is not possible / feasible, they can be added directly here as a "custom" type. To do this, it is required to have a primary source that definitively lists the media type. If an extension is going to be listed as associateed with this media type, the source must definitively link the media type and extension as well. [ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci [ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master [node-image]: https://badgen.net/npm/node/mime-db [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-db [npm-url]: https://npmjs.org/package/mime-db [npm-version-image]: https://badgen.net/npm/v/mime-db # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # node-gyp-build > Build tool and bindings loader for [`node-gyp`][node-gyp] that supports prebuilds. ``` npm install node-gyp-build ``` [![Test](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml/badge.svg)](https://github.com/prebuild/node-gyp-build/actions/workflows/test.yml) Use together with [`prebuildify`][prebuildify] to easily support prebuilds for your native modules. ## Usage > **Note.** Prebuild names have changed in [`prebuildify@3`][prebuildify] and `node-gyp-build@4`. Please see the documentation below. `node-gyp-build` works similar to [`node-gyp build`][node-gyp] except that it will check if a build or prebuild is present before rebuilding your project. It's main intended use is as an npm install script and bindings loader for native modules that bundle prebuilds using [`prebuildify`][prebuildify]. First add `node-gyp-build` as an install script to your native project ``` js { ... "scripts": { "install": "node-gyp-build" } } ``` Then in your `index.js`, instead of using the [`bindings`](https://www.npmjs.com/package/bindings) module use `node-gyp-build` to load your binding. ``` js var binding = require('node-gyp-build')(__dirname) ``` If you do these two things and bundle prebuilds with [`prebuildify`][prebuildify] your native module will work for most platforms without having to compile on install time AND will work in both node and electron without the need to recompile between usage. Users can override `node-gyp-build` and force compiling by doing `npm install --build-from-source`. Prebuilds will be attempted loaded from `MODULE_PATH/prebuilds/...` and then next `EXEC_PATH/prebuilds/...` (the latter allowing use with `zeit/pkg`) ## Supported prebuild names If so desired you can bundle more specific flavors, for example `musl` builds to support Alpine, or targeting a numbered ARM architecture version. These prebuilds can be bundled in addition to generic prebuilds; `node-gyp-build` will try to find the most specific flavor first. Prebuild filenames are composed of _tags_. The runtime tag takes precedence, as does an `abi` tag over `napi`. For more details on tags, please see [`prebuildify`][prebuildify]. Values for the `libc` and `armv` tags are auto-detected but can be overridden through the `LIBC` and `ARM_VERSION` environment variables, respectively. ## License MIT [prebuildify]: https://github.com/prebuild/prebuildify [node-gyp]: https://www.npmjs.com/package/node-gyp # NEAR CLI (command line interface) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/near/near-cli) NEAR CLI is a Node.js application that relies on [`near-api-js`](https://github.com/near/near-api-js) to connect to and interact with the NEAR blockchain. Create accounts, access keys, sign & send transactions with this versatile command line interface tool. **Note:** Node.js version 10+ is required to run NEAR CLI. ## Release notes **Release notes and unreleased changes can be found in the [CHANGELOG](CHANGELOG.md)** ## Overview _Click on a command for more information and examples._ | Command | Description | | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | **ACCESS KEYS** | | | [`near login`](#near-login) | stores a full access key locally using [NEAR Wallet](https://wallet.testnet.near.org/) | | [`near keys`](#near-keys) | displays all access keys and their details for a given account | | [`near generate-key`](#near-generate-key) | generates a local key pair **or** shows public key & [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) | | [`near add-key`](#near-add-key) | adds a new access key to an account | | [`near delete-key`](#near-delete-key) | deletes an access key from an account | | **ACCOUNTS** | | | [`near create-account`](#near-create-account) | creates an account | | [`near state`](#near-state) | shows general details of an account | | [`near keys`](#near-keys) | displays all access keys for a given account | | [`near send`](#near-send) | sends tokens from one account to another | | [`near delete`](#near-delete) | deletes an account and transfers remaining balance to a beneficiary account | | **CONTRACTS** | | | [`near deploy`](#near-deploy) | deploys a smart contract to the NEAR blockchain | | [`near dev-deploy`](#near-dev-deploy) | creates a development account and deploys a contract to it _(`testnet` only)_ | | [`near call`](#near-call) | makes a contract call which can invoke `change` _or_ `view` methods | | [`near view`](#near-view) | makes a contract call which can **only** invoke a `view` method | | **TRANSACTIONS** | | | [`near tx-status`](#near-tx-status) | queries a transaction's status by `txHash` | | **VALIDATORS** | | | [`near validators current`](#near-validators-current) | displays current [epoch](http://docs.near.org/docs/concepts/epoch) validator pool details | | [`near validators next`](#near-validators-next) | displays validator details for the next [epoch](http://docs.near.org/docs/concepts/epoch) | | [`near proposals`](#near-proposals) | displays validator proposals for the [epoch](http://docs.near.org/docs/concepts/epoch) _after_ next | | **JS-SDK** | | | [`near js`](#near-js) | Work with JS contract enclave | | **REPL** | | | [`near repl`](#near-repl) | launches an interactive connection to the NEAR blockchain ([REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) | | | can also run a JS/TS file which exports an async main function that takes a [context](./context/index.d.ts) object | [ [**OPTIONS**](#options) ] > For EVM support see [Project Aurora's](https://aurora.dev) [`aurora-cli`](https://github.com/aurora-is-near/aurora-cli). --- ## Setup ### Installation > Make sure you have a current version of `npm` and `NodeJS` installed. #### Mac and Linux 1. Install `npm` and `node` using a package manager like `nvm` as sometimes there are issues using Ledger due to how OS X handles node packages related to USB devices. [[click here]](https://nodejs.org/en/download/package-manager/) 2. Ensure you have installed Node version 12 or above. 3. Install `near-cli` globally by running: ```bash npm install -g near-cli ``` #### Windows > For Windows users, we recommend using Windows Subsystem for Linux (`WSL`). 1. Install `WSL` [[click here]](https://docs.microsoft.com/en-us/windows/wsl/install-manual#downloading-distros) 2. Install `npm` [[click here]](https://www.npmjs.com/get-npm) 3. Install ` Node.js` [ [ click here ]](https://nodejs.org/en/download/package-manager/) 4. Change `npm` default directory [ [ click here ] ](https://docs.npmjs.com/resolving-eacces-permissions-errors-when-installing-packages-globally#manually-change-npms-default-directory) - This is to avoid any permission issues with `WSL` 5. Open `WSL` and install `near-cli` globally by running: ```bash npm install -g near-cli ``` --- ### Network selection > The default network for `near-cli` is `testnet`. - You can change the network by prepending an environment variable to your command. ```bash NEAR_ENV=betanet near send ... ``` - Alternatively, you can set up a global environment variable by running: ```bash export NEAR_ENV=mainnet ``` --- ### Custom RPC server selection You can set custom RPC server URL by setting this env variables: ```bash NEAR_CLI_MAINNET_RPC_SERVER_URL NEAR_CLI_TESTNET_RPC_SERVER_URL NEAR_CLI_BETANET_RPC_SERVER_URL NEAR_CLI_GUILDNET_RPC_SERVER_URL NEAR_CLI_LOCALNET_RPC_SERVER_URL NEAR_CLI_SHARDNET_RPC_SERVER_URL NEAR_CLI_CI_RPC_SERVER_URL ``` Clear them in case you want to get back to the default RPC server. Example: ```bash export NEAR_CLI_TESTNET_RPC_SERVER_URL=<put_your_rpc_server_url_here> ``` --- ### RPC server API Keys Some RPC servers may require that you provide a valid API key to use them. You can set `x-api-key` for a server by running the next command: ```bash near set-api-key <rpc-server-url> <api-key> ``` This API Key will be saved in a config and used for each command you execute with this RPC URL. --- ## Access Keys ### `near login` > locally stores a full access key of an account you created with [NEAR Wallet](https://wallet.testnet.near.org/). - arguments: `none` - options: `default` **Example:** ```bash near login ``` #### Access Key Location: - Once complete you will now have your Access Key stored locally in a hidden directory called `.near-credentials` - This directory is located at the root of your `HOME` directory: - `~/.near-credentials` _(MAC / Linux)_ - `C:\Users\YOUR_ACCOUNT\.near-credentials` _(Windows)_ - Inside `.near-credentials`, access keys are organized in network subdirectories: - `default` _for `testnet`_ - `betanet` - `mainnet` - These network subdirectories contain `.JSON` objects with an: - `account_id` - `private_key` - `public_key` **Example:** ```json { "account_id": "example-acct.testnet", "public_key": "ed25519:7ns2AZVaG8XZrFrgRw7g8qhgddNTN64Zkz7Eo8JBnV5g", "private_key": "ed25519:4Ijd3vNUmdWJ4L922BxcsGN1aDrdpvUHEgqLQAUSLmL7S2qE9tYR9fqL6DqabGGDxCSHkKwdaAGNcHJ2Sfd" } ``` --- ### `near keys` > Displays all access keys for a given account. - arguments: `accountId` - options: `default` **Example:** ```bash near keys client.chainlink.testnet ``` <details> <summary> <strong>Example Response</strong> </summary> <p> ``` Keys for account client.chainlink.testnet [ { public_key: 'ed25519:4wrVrZbHrurMYgkcyusfvSJGLburmaw7m3gmCApxgvY4', access_key: { nonce: 97, permission: 'FullAccess' } }, { public_key: 'ed25519:H9k5eiU4xXS3M4z8HzKJSLaZdqGdGwBG49o7orNC4eZW', access_key: { nonce: 88, permission: { FunctionCall: { allowance: '18483247987345065500000000', receiver_id: 'client.chainlink.testnet', method_names: [ 'get_token_price', [length]: 1 ] } } } }, [length]: 2 ] ``` </p> </details> --- ### `near generate-key` > Creates a key pair locally in `.near-credentials` **or** displays public key from Ledger or seed phrase. - arguments: `accountId` or `none` - options: `--useLedgerKey`, `--seedPhrase`, or `--seedPath` **Note:** There are several ways to use `generate-key` that return very different results. Please reference the examples below for further details. --- #### 1) `near generate-key` > Creates a key pair locally in `.near-credentials` with an [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) as the accountId. _(hash representation of the public key)_ ```bash near generate-key ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Key pair with ed25519:33Vn9VtNEtWQPPd1f4jf5HzJ5weLcvGHU8oz7o5UnPqy public key for an account "1e5b1346bdb4fc5ccd465f6757a9082a84bcacfd396e7d80b0c726252fe8b3e8" ``` </p> </details> --- #### 2) `near generate-key accountId` > Creates a key pair locally in `.near-credentials` with an `accountId` that you specify. **Note:** This does NOT create an account with this name, and will overwrite an existing `.json` file with the same name. ```bash near generate-key example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Key pair with ed25519:CcH3oMEFg8tpJLekyvF7Wp49G81K3QLhGbaWEFwtCjht public key for an account "example.testnet" ``` </p> </details> --- #### 3a) `near generate-key --useLedgerKey` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) using the default HD path (`"44'/397'/0'/0'/1'"`) ```bash near generate-key --useLedgerKey ``` You should then see the following prompt to confirm this request on your Ledger device: Make sure to connect your Ledger and open NEAR app Waiting for confirmation on Ledger... After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wyeRvKIWv61NjmQZEkWTMzAYgdfx6oSeB2 Implicit account: 42c320xc20739fd9a6bqf2f89z61rd14efe5d3de234199bc771235a4bb8b0e1 ``` </p> </details> --- #### 3b) `near generate-key --useLedgerKey="HD path you specify"` > Uses a connected Ledger device to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) using a custom HD path. ```bash near generate-key --useLedgerKey="44'/397'/0'/0'/2'" ``` You should then see the following prompt to confirm this request on your Ledger device: Make sure to connect your Ledger and open NEAR app Waiting for confirmation on Ledger... After confirming the request on your Ledger device, a public key and implicit accountId will be displayed. <details> <summary><strong>Example Response</strong></summary> <p> ```bash Using public key: ed25519:B22RP10g695wye3dfa32rDjmQZEkWTMzAYgCX6oSeB2 Implicit account: 42c320xc20739ASD9a6bqf2Dsaf289z61rd14efe5d3de23213789009afDsd5bb8b0e1 ``` </p> </details> --- #### 4a) `near generate-key --seedPhrase="your seed phrase"` > Uses a seed phrase to display a public key and [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts) ```bash near generate-key --seedPhrase="cow moon right send now cool dense quark pretty see light after" ``` <details> <summary><strong>Example Response</strong></summary> <p> Key pair with ed25519:GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi public key for an account "e9fa50ac20522987a87e566fcd6febdc97bd35c8c489999ca8aff465c56969c3" </p> </details> --- #### 4b) `near generate-key accountId --seedPhrase="your seed phrase"` > Uses a seed phrase to display a public key **without** the [implicit account](http://docs.near.org/docs/roles/integrator/implicit-accounts). ```bash near generate-key example.testnet --seedPhrase="cow moon right send now cool dense quark pretty see light after" ``` <details> <summary><strong>Example Response</strong></summary> <p> Key pair with ed25519:GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi public key for an account "example.testnet" </p> </details> --- ### `near add-key` > Adds an either a **full access** or **function access** key to a given account. **Note:** You will use an _existing_ full access key for the account you would like to add a _new_ key to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) #### 1) add a `full access` key - arguments: `accountId` `publicKey` **Example:** ```bash near add-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> Adding full access key = Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S to example-acct.testnet. Transaction Id EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/EwU1ooEvkR42HvGoJHu5ou3xLYT3JcgQwFV3fAwevGJg </p> </details> #### 2) add a `function access` key - arguments: `accountId` `publicKey` `--contract-id` - options: `--method-names` `--allowance` > `accountId` is the account you are adding the key to > > `--contract-id` is the contract you are allowing methods to be called on > > `--method-names` are optional and if omitted, all methods of the `--contract-id` can be called. > > `--allowance` is the amount of Ⓝ the key is allowed to spend on gas fees _only_. If omitted then key will only be able to call view methods. **Note:** Each transaction made with this key will have gas fees deducted from the initial allowance and once it runs out a new key must be issued. **Example:** ```bash near add-key example-acct.testnet GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi --contract-id example-contract.testnet --method-names example_method --allowance 30000000000 ``` <details> <summary><strong>Example Response</strong></summary> <p> Adding function call access key = GkMNfc92fwM1AmwH1MTjF4b7UZuceamsq96XPkHsQ9vi to example-acct.testnet. Transaction Id H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/H2BQL9fXVmdTbwkXcMFfZ7qhZqC8fFhsA8KDHFdT9q2r </p> </details> --- ### `near delete-key` > Deletes an existing key for a given account. - arguments: `accountId` `publicKey` - options: `default` **Note:** You will need separate full access key for the account you would like to delete a key from. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near delete-key example-acct.testnet Cxg2wgFYrdLTEkMu6j5D6aEZqTb3kXbmJygS48ZKbo1S ``` <details> <summary><strong>Example Response</strong></summary> <p> Transaction Id 4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4PwW7vjzTCno7W433nu4ieA6FvsAjp7zNFwicNLKjQFT </p> </details> --- ## Accounts ### `near create-account` > Creates an account using a `--masterAccount` that will pay for the account's creation and any initial balance. - arguments: `accountId` `--masterAccount` - options: `--initialBalance` **Note:** You will only be able to create subaccounts of the `--masterAccount` unless the name of the new account is ≥ 32 characters. **Example**: ```bash near create-account 12345678901234567890123456789012 --masterAccount example-acct.testnet ``` **Subaccount example:** ```bash near create-account sub-acct.example-acct.testnet --masterAccount example-acct.testnet ``` **Example using `--initialBalance`:** ```bash near create-account sub-acct2.example-acct.testnet --masterAccount example-acct.testnet --initialBalance 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> Saving key to '/HOME_DIR/.near-credentials/default/sub-acct2.example-acct.testnet.json' Account sub-acct2.example-acct.testnet for network "default" was created. </p> </details> --- ### `near state` > Shows details of an account's state. - arguments: `accountId` - options: `default` **Example:** ```bash near state example.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json { "amount": "99999999303364037168535000", "locked": "0", "code_hash": "G1PCjeQbvbUsJ8piXNb7Yg6dn3mfivDQN7QkvsVuMt4e", "storage_usage": 53528, "storage_paid_at": 0, "block_height": 21577354, "block_hash": "AWu1mrT3eMJLjqyhNHvMKrrbahN6DqcNxXanB5UH1RjB", "formattedAmount": "99.999999303364037168535" } ``` </p> </details> --- ### `near send` > Sends NEAR tokens (Ⓝ) from one account to another. - arguments: `senderId` `receiverId` `amount` - options: `default` **Note:** You will need a full access key for the sending account. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near send sender.testnet receiver.testnet 10 ``` <details> <summary><strong>Example Response</strong></summary> <p> Sending 10 NEAR to receiver.testnet from sender.testnet Transaction Id BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/BYTr6WNyaEy2ykAiQB9P5VvTyrJcFk6Yw95HPhXC6KfN </p> </details> --- ### `near delete` > Deletes an account and transfers remaining balance to a beneficiary account. - arguments: `accountId` `beneficiaryId` - options: `default` **Example:** ```bash near delete sub-acct2.example-acct.testnet example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> Deleting account. Account id: sub-acct2.example-acct.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, beneficiary: example-acct.testnet Transaction Id 4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4x8xohER1E3yxeYdXPfG8GvXin1ShiaroqE5GdCd5YxX Account sub-acct2.example-acct.testnet for network "default" was deleted. </p> </details> --- ## Contracts ### `near deploy` > Deploys a smart contract to a given accountId. - arguments: `accountId` `.wasmFile` - options: `initFunction` `initArgs` `initGas` `initDeposit` **Note:** You will need a full access key for the account you are deploying the contract to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near deploy --accountId example-contract.testnet --wasmFile out/example.wasm ``` **Initialize Example:** ```bash near deploy --accountId example-contract.testnet --wasmFile out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}' ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: main.wasm Transaction Id G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/G8GhhPuujMHTRnwursPXE1Lv5iUZ8WUecwiST1PcKWMt Done deploying to example-contract.testnet </p> </details> ### `near dev-deploy` > Creates a development account and deploys a smart contract to it. No access keys needed. **_(`testnet` only)_** - options: `wasmFile`, `initFunction`, `initArgs`, `initGas`, `initDeposit`, `initialBalance`, `force` **Example:** ```bash near dev-deploy --wasmFile out/example.wasm ``` **Initialize Example:** ```bash near dev-deploy --wasmFile out/example.wasm --initFunction new --initArgs '{"owner_id": "example-contract.testnet", "total_supply": "10000000"}' ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: dev-1603749005325-6432576, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/main.wasm Transaction Id 5nixQT87KeN3eZFX7zwBLUAKSY4nyjhwzLF27SWWKkAp To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/5nixQT87KeN3eZFX7zwBLUAKSY4nyjhwzLF27SWWKkAp Done deploying to dev-1603749005325-6432576 </p> </details> --- ### `near call` > makes a contract call which can modify _or_ view state. **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `contractName` `method_name` `{ args }` `--accountId` - options: `--gas` `--deposit` **Example:** ```bash near call guest-book.testnet addMessage '{"text": "Aloha"}' --account-id example-acct.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call: guest-book.testnet.addMessage({"text": "Aloha"}) Transaction Id FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK '' </p> </details> --- ### `near view` > Makes a contract call which can **only** view state. _(Call is free of charge)_ - arguments: `contractName` `method_name` `{ args }` - options: `default` **Example:** ```bash near view guest-book.testnet getMessages '{}' ``` <details> <summary><strong>Example Response</strong></summary> <p> View call: guest-book.testnet.getMessages({}) [ { premium: false, sender: 'waverlymaven.testnet', text: 'TGIF' }, { premium: true, sender: 'waverlymaven.testnet', text: 'Hello from New York 🌈' }, { premium: false, sender: 'fhr.testnet', text: 'Hi' }, { premium: true, sender: 'eugenethedream', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'test' }, { premium: false, sender: 'dongri.testnet', text: 'hello' }, { premium: true, sender: 'dongri.testnet', text: 'hey' }, { premium: false, sender: 'hirokihori.testnet', text: 'hello' }, { premium: true, sender: 'eugenethedream', text: 'hello' }, { premium: false, sender: 'example-acct.testnet', text: 'Aloha' }, [length]: 10 ] </p> </details> --- ## NEAR EVM Contracts ### `near evm-view` > Makes an EVM contract call which can **only** view state. _(Call is free of charge)_ - arguments: `evmAccount` `contractName` `methodName` `[arguments]` `--abi` `--accountId` - options: `default` **Example:** ```bash near evm-view evm 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521 getAdopters '[]' --abi /path/to/contract/abi/Adoption.json --accountId test.near ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json [ "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0xCBdA96B3F2B8eb962f97AE50C3852CA976740e2B", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000" ] ``` </p> </details> --- ### `near evm-call (deprecated)` > makes an EVM contract call which can modify _or_ view state. **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `evmAccount` `contractName` `methodName` `[arguments]` `--abi` `--accountId` - options: `default` (`--gas` and `--deposit` coming soon…) **Example:** ```bash near evm-call evm 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521 adopt '["6"]' --abi /path/to/contract/abi/Adoption.json --accountId test.near ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call inside evm EVM: 0x89dfB1Cd61F05ad3971EC1f83056Fd9793c2D521.adopt() with args [ '6' ] </p> </details> --- ### `near evm-dev-init` > Used for running EVM tests — creates a given number of test accounts on the desired network using a master NEAR account - arguments: `accountId` - options: `numAccounts` ```bash NEAR_ENV=betanet near evm-dev-init you.betanet 3 ``` The above will create 3 subaccounts of `you.betanet`. This is useful for tests that require multiple accounts, for instance, sending fungible tokens back and forth. If the `3` value were to be omitted, it would use the default of 5. --- ## Transactions ### `near tx-status` > Queries transaction status by hash and accountId. - arguments: `txHash` `--accountId` - options: `default` **Example:** ```bash near tx-status FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK --accountId guest-book.testnet ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json Transaction guest-book.testnet:FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK { status: { SuccessValue: '' }, transaction: { signer_id: 'example-acct.testnet', public_key: 'ed25519:AXZZKnp6ZcWXyRNdy8FztYrniKf1qt6YZw6mCCReXrDB', nonce: 20, receiver_id: 'guest-book.testnet', actions: [ { FunctionCall: { method_name: 'addMessage', args: 'eyJ0ZXh0IjoiQWxvaGEifQ==', gas: 300000000000000, deposit: '0' } }, [length]: 1 ], signature: 'ed25519:5S6nZXPU72nzgAsTQLmAFfdVSykdKHWhtPMb5U7duacfPdUjrj8ipJxuRiWkZ4yDodvDNt92wcHLJxGLsyNEsZNB', hash: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK' }, transaction_outcome: { proof: [ [length]: 0 ], block_hash: '6nsjvzt6C52SSuJ8UvfaXTsdrUwcx8JtHfnUj8XjdKy1', id: 'FY8hBam2iyQfdHkdR1dp6w5XEPJzJSosX1wUeVPyUvVK', outcome: { logs: [ [length]: 0 ], receipt_ids: [ '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', [length]: 1 ], gas_burnt: 2427979134284, tokens_burnt: '242797913428400000000', executor_id: 'example-acct.testnet', status: { SuccessReceiptId: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU' } } }, receipts_outcome: [ { proof: [ [length]: 0 ], block_hash: 'At6QMrBuFQYgEPAh6fuRBmrTAe9hXTY1NzAB5VxTH1J2', id: '7n6wjMgpoBTp22ScLHxeMLzcCvN8Vf5FUuC9PMmCX6yU', outcome: { logs: [ [length]: 0 ], receipt_ids: [ 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', [length]: 1 ], gas_burnt: 3559403233496, tokens_burnt: '355940323349600000000', executor_id: 'guest-book.testnet', status: { SuccessValue: '' } } }, { proof: [ [length]: 0 ], block_hash: 'J7KjpMPzAqE7iX82FAQT3qERDs6UR1EAqBLPJXBzoLCk', id: 'FUttfoM2odAhKNQrJ8F4tiBpQJPYu66NzFbxRKii294e', outcome: { logs: [ [length]: 0 ], receipt_ids: [ [length]: 0 ], gas_burnt: 0, tokens_burnt: '0', executor_id: 'example-acct.testnet', status: { SuccessValue: '' } } }, [length]: 2 ] } ``` </p> </details> --- ## Validators ### `near validators current` > Displays details of current validators. > > - amount staked > - number of seats > - percentage of uptime > - expected block production > - blocks actually produced - arguments: `current` - options: `default` **Example:** ```bash near validators current ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near validators current ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Validators (total: 49, seat price: 1,976,588): .--------------------------------------------------------------------------------------------------------------------. | Validator Id | Stake | Seats | % Online | Blocks produced | Blocks expected | |----------------------------------------------|------------|---------|----------|-----------------|-----------------| | cryptium.poolv1.near | 13,945,727 | 7 | 100% | 1143 | 1143 | | astro-stakers.poolv1.near | 11,660,189 | 5 | 100% | 817 | 817 | | blockdaemon.poolv1.near | 11,542,867 | 5 | 76.74% | 627 | 817 | | zavodil.poolv1.near | 11,183,187 | 5 | 100% | 818 | 818 | | bisontrails.poolv1.near | 10,291,696 | 5 | 99.38% | 810 | 815 | | dokiacapital.poolv1.near | 7,906,352 | 3 | 99.54% | 650 | 653 | | chorusone.poolv1.near | 7,480,508 | 3 | 100% | 490 | 490 | | figment.poolv1.near | 6,931,070 | 3 | 100% | 489 | 489 | | stardust.poolv1.near | 6,401,678 | 3 | 100% | 491 | 491 | | anonymous.poolv1.near | 6,291,821 | 3 | 97.55% | 479 | 491 | | d1.poolv1.near | 6,265,109 | 3 | 100% | 491 | 491 | | near8888.poolv1.near | 6,202,968 | 3 | 99.38% | 486 | 489 | | rekt.poolv1.near | 5,950,212 | 3 | 100% | 490 | 490 | | epic.poolv1.near | 5,639,256 | 2 | 100% | 326 | 326 | | fresh.poolv1.near | 5,460,410 | 2 | 100% | 327 | 327 | | buildlinks.poolv1.near | 4,838,398 | 2 | 99.38% | 325 | 327 | | jubi.poolv1.near | 4,805,921 | 2 | 100% | 326 | 326 | | openshards.poolv1.near | 4,644,553 | 2 | 100% | 326 | 326 | | jazza.poolv1.near | 4,563,432 | 2 | 100% | 327 | 327 | | northernlights.poolv1.near | 4,467,978 | 2 | 99.39% | 326 | 328 | | inotel.poolv1.near | 4,427,152 | 2 | 100% | 327 | 327 | | baziliknear.poolv1.near | 4,261,142 | 2 | 100% | 328 | 328 | | stakesabai.poolv1.near | 4,242,618 | 2 | 100% | 326 | 326 | | everstake.poolv1.near | 4,234,552 | 2 | 100% | 327 | 327 | | stakin.poolv1.near | 4,071,704 | 2 | 100% | 327 | 327 | | certusone.poolv1.near | 3,734,505 | 1 | 100% | 164 | 164 | | lux.poolv1.near | 3,705,394 | 1 | 100% | 163 | 163 | | staked.poolv1.near | 3,683,365 | 1 | 100% | 164 | 164 | | lunanova.poolv1.near | 3,597,231 | 1 | 100% | 163 | 163 | | appload.poolv1.near | 3,133,163 | 1 | 100% | 163 | 163 | | smart-stake.poolv1.near | 3,095,711 | 1 | 100% | 164 | 164 | | artemis.poolv1.near | 3,009,462 | 1 | 99.39% | 163 | 164 | | moonlet.poolv1.near | 2,790,296 | 1 | 100% | 163 | 163 | | nearfans.poolv1.near | 2,771,137 | 1 | 100% | 163 | 163 | | nodeasy.poolv1.near | 2,692,745 | 1 | 99.39% | 163 | 164 | | erm.poolv1.near | 2,653,524 | 1 | 100% | 164 | 164 | | zkv_staketosupportprivacy.poolv1.near | 2,548,343 | 1 | 99.39% | 163 | 164 | | dsrvlabs.poolv1.near | 2,542,925 | 1 | 100% | 164 | 164 | | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 | 1 | 100% | 163 | 163 | | electric.poolv1.near | 2,400,532 | 1 | 99.39% | 163 | 164 | | sparkpool.poolv1.near | 2,378,191 | 1 | 100% | 163 | 163 | | hashquark.poolv1.near | 2,376,424 | 1 | 100% | 164 | 164 | | masternode24.poolv1.near | 2,355,634 | 1 | 100% | 164 | 164 | | sharpdarts.poolv1.near | 2,332,398 | 1 | 99.38% | 162 | 163 | | fish.poolv1.near | 2,315,249 | 1 | 100% | 163 | 163 | | ashert.poolv1.near | 2,103,327 | 1 | 97.56% | 160 | 164 | | 01node.poolv1.near | 2,058,200 | 1 | 100% | 163 | 163 | | finoa.poolv1.near | 2,012,304 | 1 | 100% | 163 | 163 | | majlovesreg.poolv1.near | 2,005,032 | 1 | 100% | 164 | 164 | '--------------------------------------------------------------------------------------------------------------------' ``` </p> </details> --- ### `near validators next` > Displays details for the next round of validators. > > - total number of seats available > - seat price > - amount staked > - number of seats assigned per validator - arguments: `next` - options: `default` **Example:** ```bash near validators next ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near validators next ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Next validators (total: 49, seat price: 1,983,932): .----------------------------------------------------------------------------------------------. | Status | Validator | Stake | Seats | |----------|----------------------------------------------|--------------------------|---------| | Rewarded | cryptium.poolv1.near | 13,945,727 -> 14,048,816 | 7 | | Rewarded | astro-stakers.poolv1.near | 11,660,189 -> 11,704,904 | 5 | | Rewarded | blockdaemon.poolv1.near | 11,542,867 -> 11,545,942 | 5 | | Rewarded | zavodil.poolv1.near | 11,183,187 -> 11,204,123 | 5 | | Rewarded | bisontrails.poolv1.near | 10,291,696 -> 10,297,923 | 5 | | Rewarded | dokiacapital.poolv1.near | 7,906,352 -> 8,097,275 | 4 | | Rewarded | chorusone.poolv1.near | 7,480,508 -> 7,500,576 | 3 | | Rewarded | figment.poolv1.near | 6,931,070 -> 6,932,916 | 3 | | Rewarded | stardust.poolv1.near | 6,401,678 -> 6,449,363 | 3 | | Rewarded | anonymous.poolv1.near | 6,291,821 -> 6,293,497 | 3 | | Rewarded | d1.poolv1.near | 6,265,109 -> 6,266,777 | 3 | | Rewarded | near8888.poolv1.near | 6,202,968 -> 6,204,620 | 3 | | Rewarded | rekt.poolv1.near | 5,950,212 -> 5,951,797 | 2 | | Rewarded | epic.poolv1.near | 5,639,256 -> 5,640,758 | 2 | | Rewarded | fresh.poolv1.near | 5,460,410 -> 5,461,811 | 2 | | Rewarded | buildlinks.poolv1.near | 4,838,398 -> 4,839,686 | 2 | | Rewarded | jubi.poolv1.near | 4,805,921 -> 4,807,201 | 2 | | Rewarded | openshards.poolv1.near | 4,644,553 -> 4,776,692 | 2 | | Rewarded | jazza.poolv1.near | 4,563,432 -> 4,564,648 | 2 | | Rewarded | northernlights.poolv1.near | 4,467,978 -> 4,469,168 | 2 | | Rewarded | inotel.poolv1.near | 4,427,152 -> 4,428,331 | 2 | | Rewarded | baziliknear.poolv1.near | 4,261,142 -> 4,290,338 | 2 | | Rewarded | stakesabai.poolv1.near | 4,242,618 -> 4,243,748 | 2 | | Rewarded | everstake.poolv1.near | 4,234,552 -> 4,235,679 | 2 | | Rewarded | stakin.poolv1.near | 4,071,704 -> 4,072,773 | 2 | | Rewarded | certusone.poolv1.near | 3,734,505 -> 3,735,500 | 1 | | Rewarded | lux.poolv1.near | 3,705,394 -> 3,716,381 | 1 | | Rewarded | staked.poolv1.near | 3,683,365 -> 3,684,346 | 1 | | Rewarded | lunanova.poolv1.near | 3,597,231 -> 3,597,836 | 1 | | Rewarded | appload.poolv1.near | 3,133,163 -> 3,152,302 | 1 | | Rewarded | smart-stake.poolv1.near | 3,095,711 -> 3,096,509 | 1 | | Rewarded | artemis.poolv1.near | 3,009,462 -> 3,010,265 | 1 | | Rewarded | moonlet.poolv1.near | 2,790,296 -> 2,948,565 | 1 | | Rewarded | nearfans.poolv1.near | 2,771,137 -> 2,771,875 | 1 | | Rewarded | nodeasy.poolv1.near | 2,692,745 -> 2,693,463 | 1 | | Rewarded | erm.poolv1.near | 2,653,524 -> 2,654,231 | 1 | | Rewarded | dsrvlabs.poolv1.near | 2,542,925 -> 2,571,865 | 1 | | Rewarded | zkv_staketosupportprivacy.poolv1.near | 2,548,343 -> 2,549,022 | 1 | | Rewarded | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 -> 2,493,787 | 1 | | Rewarded | masternode24.poolv1.near | 2,355,634 -> 2,456,226 | 1 | | Rewarded | fish.poolv1.near | 2,315,249 -> 2,415,831 | 1 | | Rewarded | electric.poolv1.near | 2,400,532 -> 2,401,172 | 1 | | Rewarded | sparkpool.poolv1.near | 2,378,191 -> 2,378,824 | 1 | | Rewarded | hashquark.poolv1.near | 2,376,424 -> 2,377,057 | 1 | | Rewarded | sharpdarts.poolv1.near | 2,332,398 -> 2,332,948 | 1 | | Rewarded | ashert.poolv1.near | 2,103,327 -> 2,103,887 | 1 | | Rewarded | 01node.poolv1.near | 2,058,200 -> 2,058,760 | 1 | | Rewarded | finoa.poolv1.near | 2,012,304 -> 2,015,808 | 1 | | Rewarded | majlovesreg.poolv1.near | 2,005,032 -> 2,005,566 | 1 | '----------------------------------------------------------------------------------------------' ``` </p> </details> --- ### `near proposals` > Displays validator proposals for [epoch](http://docs.near.org/docs/concepts/epoch) after next. > > - expected seat price > - status of proposals > - previous amount staked and new amount that _will_ be staked > - amount of seats assigned per validator - arguments: `none` - options: `default` **Example:** ```bash near proposals ``` **Example for `mainnet`:** ```bash NEAR_ENV=mainnet near proposals ``` <details> <summary><strong>Example Response</strong></summary> <p> ```bash Proposals for the epoch after next (new: 51, passing: 49, expected seat price = 1,983,932) .--------------------------------------------------------------------------------------------------------. | Status | Validator | Stake => New Stake | Seats | |--------------------|----------------------------------------------|--------------------------|---------| | Proposal(Accepted) | cryptium.poolv1.near | 13,945,727 => 14,041,766 | 7 | | Proposal(Accepted) | astro-stakers.poolv1.near | 11,660,189 => 11,705,673 | 5 | | Proposal(Accepted) | blockdaemon.poolv1.near | 11,542,867 => 11,545,942 | 5 | | Proposal(Accepted) | zavodil.poolv1.near | 11,183,187 => 11,207,805 | 5 | | Proposal(Accepted) | bisontrails.poolv1.near | 10,291,696 => 10,300,978 | 5 | | Proposal(Accepted) | dokiacapital.poolv1.near | 7,906,352 => 8,097,275 | 4 | | Proposal(Accepted) | chorusone.poolv1.near | 7,480,508 => 7,568,268 | 3 | | Proposal(Accepted) | figment.poolv1.near | 6,931,070 => 6,932,916 | 3 | | Proposal(Accepted) | stardust.poolv1.near | 6,401,678 => 6,449,363 | 3 | | Proposal(Accepted) | anonymous.poolv1.near | 6,291,821 => 6,293,497 | 3 | | Proposal(Accepted) | d1.poolv1.near | 6,265,109 => 6,266,777 | 3 | | Proposal(Accepted) | near8888.poolv1.near | 6,202,968 => 6,204,620 | 3 | | Proposal(Accepted) | rekt.poolv1.near | 5,950,212 => 5,951,797 | 2 | | Proposal(Accepted) | epic.poolv1.near | 5,639,256 => 5,640,758 | 2 | | Proposal(Accepted) | fresh.poolv1.near | 5,460,410 => 5,461,811 | 2 | | Proposal(Accepted) | buildlinks.poolv1.near | 4,838,398 => 4,839,686 | 2 | | Proposal(Accepted) | jubi.poolv1.near | 4,805,921 => 4,807,201 | 2 | | Proposal(Accepted) | openshards.poolv1.near | 4,644,553 => 4,776,692 | 2 | | Proposal(Accepted) | jazza.poolv1.near | 4,563,432 => 4,564,648 | 2 | | Proposal(Accepted) | northernlights.poolv1.near | 4,467,978 => 4,469,168 | 2 | | Proposal(Accepted) | inotel.poolv1.near | 4,427,152 => 4,428,331 | 2 | | Proposal(Accepted) | baziliknear.poolv1.near | 4,261,142 => 4,290,891 | 2 | | Proposal(Accepted) | stakesabai.poolv1.near | 4,242,618 => 4,243,748 | 2 | | Proposal(Accepted) | everstake.poolv1.near | 4,234,552 => 4,235,679 | 2 | | Proposal(Accepted) | stakin.poolv1.near | 4,071,704 => 4,072,773 | 2 | | Proposal(Accepted) | certusone.poolv1.near | 3,734,505 => 3,735,500 | 1 | | Proposal(Accepted) | lux.poolv1.near | 3,705,394 => 3,716,381 | 1 | | Proposal(Accepted) | staked.poolv1.near | 3,683,365 => 3,684,346 | 1 | | Proposal(Accepted) | lunanova.poolv1.near | 3,597,231 => 3,597,836 | 1 | | Proposal(Accepted) | appload.poolv1.near | 3,133,163 => 3,152,302 | 1 | | Proposal(Accepted) | smart-stake.poolv1.near | 3,095,711 => 3,096,509 | 1 | | Proposal(Accepted) | artemis.poolv1.near | 3,009,462 => 3,010,265 | 1 | | Proposal(Accepted) | moonlet.poolv1.near | 2,790,296 => 2,948,565 | 1 | | Proposal(Accepted) | nearfans.poolv1.near | 2,771,137 => 2,771,875 | 1 | | Proposal(Accepted) | nodeasy.poolv1.near | 2,692,745 => 2,693,463 | 1 | | Proposal(Accepted) | erm.poolv1.near | 2,653,524 => 2,654,231 | 1 | | Proposal(Accepted) | dsrvlabs.poolv1.near | 2,542,925 => 2,571,865 | 1 | | Proposal(Accepted) | zkv_staketosupportprivacy.poolv1.near | 2,548,343 => 2,549,022 | 1 | | Proposal(Accepted) | 08investinwomen_runbybisontrails.poolv1.near | 2,493,123 => 2,493,787 | 1 | | Proposal(Accepted) | masternode24.poolv1.near | 2,355,634 => 2,456,226 | 1 | | Proposal(Accepted) | fish.poolv1.near | 2,315,249 => 2,415,831 | 1 | | Proposal(Accepted) | electric.poolv1.near | 2,400,532 => 2,401,172 | 1 | | Proposal(Accepted) | sparkpool.poolv1.near | 2,378,191 => 2,378,824 | 1 | | Proposal(Accepted) | hashquark.poolv1.near | 2,376,424 => 2,377,057 | 1 | | Proposal(Accepted) | sharpdarts.poolv1.near | 2,332,398 => 2,332,948 | 1 | | Proposal(Accepted) | ashert.poolv1.near | 2,103,327 => 2,103,887 | 1 | | Proposal(Accepted) | 01node.poolv1.near | 2,058,200 => 2,059,314 | 1 | | Proposal(Accepted) | finoa.poolv1.near | 2,012,304 => 2,015,808 | 1 | | Proposal(Accepted) | majlovesreg.poolv1.near | 2,005,032 => 2,005,566 | 1 | | Proposal(Declined) | huobipool.poolv1.near | 1,666,976 | 0 | | Proposal(Declined) | hb436_pool.poolv1.near | 500,030 | 0 | '--------------------------------------------------------------------------------------------------------' ``` </p> </details> --- ## JS Contracts Enclave ### `near js` You can use `near js <command> <args>` to be able to interact with JS enclaved contracts. Run `near js --help` for instructions. An optional `--jsvm <accountId>` argument can be supplied to the following `js` subcommands to point to a different JSVM enclave contract. The default is set to `jsvm.testnet` and `jsvm.near` respectively for testnet and mainnet. Note that anything changing state in the enclave will require a deposit to maintain storage of either the contract bytes or the state of the contract itself. ### `near js deploy` > Deploys a smart contract to a given accountId on the JSVM enclave. - arguments: `accountId`, `base64File`, `deposit` - options: `jsvm` **Note:** You will need a full access key for the account you are deploying the contract to. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) **Example:** ```bash near deploy --accountId example-contract.testnet --base64File out/example.base64 --deposit 0.1 ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: example-contract.testnet, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/example.base64, JSVM: jsvm.testnet Transaction Id 4Nxsszgh2LaXPZph37peZKDqPZeJEErPih6n4jWcGDEB To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/4Nxsszgh2LaXPZph37peZKDqPZeJEErPih6n4jWcGDEB Done deploying to example-contract.testnet </p> </details> ### `near js dev-deploy` > Creates a development account and deploys a smart contract to the enclave associated to the dev-account. No access keys needed. **_(`testnet` only)_** - arguments: `base64File` `deposit` - options: `jsvm` **Example:** ```bash near js dev-deploy --base64File out/example.base64 --deposit 0.1 ``` <details> <summary><strong>Example Response</strong></summary> <p> Starting deployment. Account id: dev-1653005231830-15694723179173, node: https://rpc.testnet.near.org, helper: https://helper.testnet.near.org, file: out/example.base64, JSVM: jsvm.testnet Transaction Id FTVd4TKzy9mrmWvok6qHaoX68cVZnUJp2VqUgH6Y446n To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FTVd4TKzy9mrmWvok6qHaoX68cVZnUJp2VqUgH6Y446n Done deploying to dev-1653005231830-15694723179173 </p> </details> ### `near js call` > makes a contract call which can modify _or_ view state into the JSVM enclase **Note:** Contract calls require a transaction fee (gas) so you will need an access key for the `--accountId` that will be charged. ([`near login`](http://docs.near.org/docs/tools/near-cli#near-login)) - arguments: `contractName` `methodName` `{ args }` `--accountId` `--deposit` - options: `--gas` `--jsvm` **Example:** ```bash near js call dev-1653005231830-15694723179173 set_status '["hello world"]' --deposit 0.1 --account-id dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> Scheduling a call in JSVM[jsvm.testnet]: dev-1653005231830-15694723179173.set_status(["hello world"]) with attached 0.1 NEAR Receipts: 5QUuNwSYrDcEPKuSnU7fKN7YCGfXmdmZR9m3zUSTek7P, 3YU4eFhqBruc4z8KKLZr1U1oY31A6Bfks45GLA2rq5GS Log [jsvm.testnet]: dev-1653005231830-15694723179173 set_status with message hello world Transaction Id sP8s9REgK9YcZzkudyccg8R968zYWDVGCNv4wxeZsUe To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/sP8s9REgK9YcZzkudyccg8R968zYWDVGCNv4wxeZsUe '' </p> </details> ### `near js view` > Makes a contract call which can **only** view state. _(Call is free of charge and does not require deposit)_ - arguments: `contractName` `method_name` `{ args }` - options: `jsvm` **Example:** ```bash near js view dev-1653005231830-15694723179173 get_status '["dev-1653005231830-15694723179173"]' --accountId dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> View call in JSVM[jsvm.testnet]: dev-1653005231830-15694723179173.get_status(["dev-1653005231830-15694723179173"]) Log [jsvm.testnet]: get_status for account_id dev-1653005231830-15694723179173 'hello world' </p> </details> ### `near js remove` > Removes the contract on the JS enclase and refunds all the deposit to the actual account. - arguments: `accountId` - options: `jsvm` ```bash near js remove --accountId dev-1653005231830-15694723179173 ``` <details> <summary><strong>Example Response</strong></summary> <p> Removing contract from enclave. Account id: dev-1653005231830-15694723179173, JSVM: jsvm.testnet Transaction Id FGSfvoWmhS1fWb6ckpPMYvc7seNaGQ5MU7iSrY43ZWiG To see the transaction in the transaction explorer, please open this url in your browser https://explorer.testnet.near.org/transactions/FGSfvoWmhS1fWb6ckpPMYvc7seNaGQ5MU7iSrY43ZWiG </p> </details> ## REPL ### `near repl` > Launches NEAR [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) _(an interactive JavaScript programming invironment)_ connected to NEAR. - arguments: `none` - options: `--accountId`, `--script` To launch, run: ```bash near repl ``` - You will then be shown a prompt `>` and can begin interacting with NEAR. - Try typing the following into your prompt that converts NEAR (Ⓝ) into yoctoNEAR (10^-24): ```bash nearAPI.utils.format.parseNearAmount('1000') ``` > You can also use an `--accountId` with `near repl`. The `script` argument allows you to pass the path to a javascript/typescript file that exports a `main` function taking a [`Context`](./context/index.d.ts) as an argument. Anything passed after `--` is passed to the script as the `argv` argument. Note: you will need to add `near-cli` as a dependency in order to import the types. e.g. ```ts import { Context } from "near-cli/context"; ``` **Example:** ```bash near repl --accountId example-acct.testnet ``` - Then try console logging `account` after the `>` prompt. ```bash console.log(account) ``` Or in a JS files ```js module.exports.main = async function main({account, near, nearAPI, argv}) { console.log(account); } ``` <details> <summary><strong>Example Response</strong></summary> <p> ```json Account { accessKeyByPublicKeyCache: {}, connection: Connection { networkId: 'default', provider: JsonRpcProvider { connection: [Object] }, signer: InMemorySigner { keyStore: [MergeKeyStore] } }, accountId: 'example-acct.testnet', _ready: Promise { undefined }, _state: { amount: '98786165075093615800000000', locked: '0', code_hash: '11111111111111111111111111111111', storage_usage: 741, storage_paid_at: 0, block_height: 21661252, block_hash: 'HbAj25dTzP3ssYjNRHov9BQ72UxpHGVqZK1mZwGdGNbo' } } ``` </p> </details> > You can also get a private key's public key. - First, declare a `privateKey` variable: ```js const myPrivateKey = "3fKM9Rr7LHyzhhzmmedXLvc59rayfh1oUYS3VfUcxwpAFQZtdx1G9aTY6i8hG9mQtYoycTEFTBtatgNKHRtYamrS"; ``` - Then run: ```js nearAPI.KeyPair.fromString(myPrivateKey).publicKey.toString(); ``` With NEAR REPL you have complete access to [`near-api-js`](https://github.com/near/near-api-js) to help you develop on the NEAR platform. --- ## Options | Option | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `--help` | Show help [boolean] | | `--version` | Show version number [boolean] | | `--nodeUrl, --node_url` | NEAR node URL [string] [default: "https://rpc.testnet.near.org"] | | `--networkId, --network_id`| NEAR network ID, allows using different keys based on network [string] [default: "testnet"] | | `--helperUrl` | NEAR contract helper URL [string] | | `--keyPath` | Path to master account key [string] | | `--accountId, --account_id`| Unique identifier for the account [string] | | `--useLedgerKey` | Use Ledger for signing with given HD key path [string] [default: "44'/397'/0'/0'/1'"] | | `--seedPhrase` | Seed phrase mnemonic [string] | | `--seedPath` | HD path derivation [string] [default: "m/44'/397'/0'"] | | `--walletUrl` | Website for NEAR Wallet [string] | | `--contractName` | Account name of contract [string] | | `--masterAccount` | Master account used when creating new accounts [string] | | `--helperAccount` | Expected top-level account for a network [string] | | `-v, --verbose` | Prints out verbose output [boolean] [default: false] | |`-f, --force` | Forcefully execute the desired action even if it is unsafe to do so [boolean] [default: false]| > Got a question? <a href="https://stackoverflow.com/questions/tagged/nearprotocol"> <h8>Ask it on StackOverflow!</h8></a> ## License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # magic-string <a href="https://travis-ci.org/Rich-Harris/magic-string"> <img src="http://img.shields.io/travis/Rich-Harris/magic-string.svg" alt="build status"> </a> <a href="https://npmjs.org/package/magic-string"> <img src="https://img.shields.io/npm/v/magic-string.svg" alt="npm version"> </a> <a href="https://github.com/Rich-Harris/magic-string/blob/master/LICENSE.md"> <img src="https://img.shields.io/npm/l/magic-string.svg" alt="license"> </a> Suppose you have some source code. You want to make some light modifications to it - replacing a few characters here and there, wrapping it with a header and footer, etc - and ideally you'd like to generate a source map at the end of it. You've thought about using something like [recast](https://github.com/benjamn/recast) (which allows you to generate an AST from some JavaScript, manipulate it, and reprint it with a sourcemap without losing your comments and formatting), but it seems like overkill for your needs (or maybe the source code isn't JavaScript). Your requirements are, frankly, rather niche. But they're requirements that I also have, and for which I made magic-string. It's a small, fast utility for manipulating strings and generating sourcemaps. ## Installation magic-string works in both node.js and browser environments. For node, install with npm: ```bash npm i magic-string ``` To use in browser, grab the [magic-string.umd.js](https://unpkg.com/magic-string/dist/magic-string.umd.js) file and add it to your page: ```html <script src='magic-string.umd.js'></script> ``` (It also works with various module systems, if you prefer that sort of thing - it has a dependency on [vlq](https://github.com/Rich-Harris/vlq).) ## Usage These examples assume you're in node.js, or something similar: ```js import MagicString from 'magic-string'; import fs from 'fs' const s = new MagicString('problems = 99'); s.overwrite(0, 8, 'answer'); s.toString(); // 'answer = 99' s.overwrite(11, 13, '42'); // character indices always refer to the original string s.toString(); // 'answer = 42' s.prepend('var ').append(';'); // most methods are chainable s.toString(); // 'var answer = 42;' const map = s.generateMap({ source: 'source.js', file: 'converted.js.map', includeContent: true }); // generates a v3 sourcemap fs.writeFileSync('converted.js', s.toString()); fs.writeFileSync('converted.js.map', map.toString()); ``` You can pass an options argument: ```js const s = new MagicString(someCode, { // both these options will be used if you later // call `bundle.addSource( s )` - see below filename: 'foo.js', indentExclusionRanges: [/*...*/] }); ``` ## Methods ### s.addSourcemapLocation( index ) Adds the specified character index (with respect to the original string) to sourcemap mappings, if `hires` is `false` (see below). ### s.append( content ) Appends the specified content to the end of the string. Returns `this`. ### s.appendLeft( index, content ) Appends the specified `content` at the `index` in the original string. If a range *ending* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependLeft(...)`. ### s.appendRight( index, content ) Appends the specified `content` at the `index` in the original string. If a range *starting* with `index` is subsequently moved, the insert will be moved with it. Returns `this`. See also `s.prependRight(...)`. ### s.clone() Does what you'd expect. ### s.generateDecodedMap( options ) Generates a sourcemap object with raw mappings in array form, rather than encoded as a string. See `generateMap` documentation below for options details. Useful if you need to manipulate the sourcemap further, but most of the time you will use `generateMap` instead. ### s.generateMap( options ) Generates a [version 3 sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). All options are, well, optional: * `file` - the filename where you plan to write the sourcemap * `source` - the filename of the file containing the original source * `includeContent` - whether to include the original content in the map's `sourcesContent` array * `hires` - whether the mapping should be high-resolution. Hi-res mappings map every single character, meaning (for example) your devtools will always be able to pinpoint the exact location of function calls and so on. With lo-res mappings, devtools may only be able to identify the correct line - but they're quicker to generate and less bulky. If sourcemap locations have been specified with `s.addSourceMapLocation()`, they will be used here. The returned sourcemap has two (non-enumerable) methods attached for convenience: * `toString` - returns the equivalent of `JSON.stringify(map)` * `toUrl` - returns a DataURI containing the sourcemap. Useful for doing this sort of thing: ```js code += '\n//# sourceMappingURL=' + map.toUrl(); ``` ### s.indent( prefix[, options] ) Prefixes each line of the string with `prefix`. If `prefix` is not supplied, the indentation will be guessed from the original content, falling back to a single tab character. Returns `this`. The `options` argument can have an `exclude` property, which is an array of `[start, end]` character ranges. These ranges will be excluded from the indentation - useful for (e.g.) multiline strings. ### s.insertLeft( index, content ) **DEPRECATED** since 0.17 – use `s.appendLeft(...)` instead ### s.insertRight( index, content ) **DEPRECATED** since 0.17 – use `s.prependRight(...)` instead ### s.locate( index ) **DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) ### s.locateOrigin( index ) **DEPRECATED** since 0.10 – see [#30](https://github.com/Rich-Harris/magic-string/pull/30) ### s.move( start, end, newIndex ) Moves the characters from `start` and `end` to `index`. Returns `this`. ### s.overwrite( start, end, content[, options] ) Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. Returns `this`. The fourth argument is optional. It can have a `storeName` property — if `true`, the original name will be stored for later inclusion in a sourcemap's `names` array — and a `contentOnly` property which determines whether only the content is overwritten, or anything that was appended/prepended to the range as well. ### s.prepend( content ) Prepends the string with the specified content. Returns `this`. ### s.prependLeft ( index, content ) Same as `s.appendLeft(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` ### s.prependRight ( index, content ) Same as `s.appendRight(...)`, except that the inserted content will go *before* any previous appends or prepends at `index` ### s.remove( start, end ) Removes the characters from `start` to `end` (of the original string, **not** the generated string). Removing the same content twice, or making removals that partially overlap, will cause an error. Returns `this`. ### s.slice( start, end ) Returns the content of the generated string that corresponds to the slice between `start` and `end` of the original string. Throws error if the indices are for characters that were already removed. ### s.snip( start, end ) Returns a clone of `s`, with all content before the `start` and `end` characters of the original string removed. ### s.toString() Returns the generated string. ### s.trim([ charType ]) Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start and end. Returns `this`. ### s.trimStart([ charType ]) Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the start. Returns `this`. ### s.trimEnd([ charType ]) Trims content matching `charType` (defaults to `\s`, i.e. whitespace) from the end. Returns `this`. ### s.trimLines() Removes empty lines from the start and end. Returns `this`. ### s.isEmpty() Returns true if the resulting source is empty (disregarding white space). ## Bundling To concatenate several sources, use `MagicString.Bundle`: ```js const bundle = new MagicString.Bundle(); bundle.addSource({ filename: 'foo.js', content: new MagicString('var answer = 42;') }); bundle.addSource({ filename: 'bar.js', content: new MagicString('console.log( answer )') }); // Advanced: a source can include an `indentExclusionRanges` property // alongside `filename` and `content`. This will be passed to `s.indent()` // - see documentation above bundle.indent() // optionally, pass an indent string, otherwise it will be guessed .prepend('(function () {\n') .append('}());'); bundle.toString(); // (function () { // var answer = 42; // console.log( answer ); // }()); // options are as per `s.generateMap()` above const map = bundle.generateMap({ file: 'bundle.js', includeContent: true, hires: true }); ``` As an alternative syntax, if you a) don't have `filename` or `indentExclusionRanges` options, or b) passed those in when you used `new MagicString(...)`, you can simply pass the `MagicString` instance itself: ```js const bundle = new MagicString.Bundle(); const source = new MagicString(someCode, { filename: 'foo.js' }); bundle.addSource(source); ``` ## License MIT # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` are-we-there-yet ---------------- Track complex hiearchies of asynchronous task completion statuses. This is intended to give you a way of recording and reporting the progress of the big recursive fan-out and gather type workflows that are so common in async. What you do with this completion data is up to you, but the most common use case is to feed it to one of the many progress bar modules. Most progress bar modules include a rudamentary version of this, but my needs were more complex. Usage ===== ```javascript var TrackerGroup = require("are-we-there-yet").TrackerGroup var top = new TrackerGroup("program") var single = top.newItem("one thing", 100) single.completeWork(20) console.log(top.completed()) // 0.2 fs.stat("file", function(er, stat) { if (er) throw er var stream = top.newStream("file", stat.size) console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete // and 50% * 20% == 10% fs.createReadStream("file").pipe(stream).on("data", function (chunk) { // do stuff with chunk }) top.on("change", function (name) { // called each time a chunk is read from "file" // top.completed() will start at 0.1 and fill up to 0.6 as the file is read }) }) ``` Shared Methods ============== * var completed = tracker.completed() Implemented in: `Tracker`, `TrackerGroup`, `TrackerStream` Returns the ratio of completed work to work to be done. Range of 0 to 1. * tracker.finish() Implemented in: `Tracker`, `TrackerGroup` Marks the tracker as completed. With a TrackerGroup this marks all of its components as completed. Marks all of the components of this tracker as finished, which in turn means that `tracker.completed()` for this will now be 1. This will result in one or more `change` events being emitted. Events ====== All tracker objects emit `change` events with the following arguments: ``` function (name, completed, tracker) ``` `name` is the name of the tracker that originally emitted the event, or if it didn't have one, the first containing tracker group that had one. `completed` is the percent complete (as returned by `tracker.completed()` method). `tracker` is the tracker object that you are listening for events on. TrackerGroup ============ * var tracker = new TrackerGroup(**name**) * **name** *(optional)* - The name of this tracker group, used in change notifications if the component updating didn't have a name. Defaults to undefined. Creates a new empty tracker aggregation group. These are trackers whose completion status is determined by the completion status of other trackers. * tracker.addUnit(**otherTracker**, **weight**) * **otherTracker** - Any of the other are-we-there-yet tracker objects * **weight** *(optional)* - The weight to give the tracker, defaults to 1. Adds the **otherTracker** to this aggregation group. The weight determines how long you expect this tracker to take to complete in proportion to other units. So for instance, if you add one tracker with a weight of 1 and another with a weight of 2, you're saying the second will take twice as long to complete as the first. As such, the first will account for 33% of the completion of this tracker and the second will account for the other 67%. Returns **otherTracker**. * var subGroup = tracker.newGroup(**name**, **weight**) The above is exactly equivalent to: ```javascript var subGroup = tracker.addUnit(new TrackerGroup(name), weight) ``` * var subItem = tracker.newItem(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subItem = tracker.addUnit(new Tracker(name, todo), weight) ``` * var subStream = tracker.newStream(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subStream = tracker.addUnit(new TrackerStream(name, todo), weight) ``` * console.log( tracker.debug() ) Returns a tree showing the completion of this tracker group and all of its children, including recursively entering all of the children. Tracker ======= * var tracker = new Tracker(**name**, **todo**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **todo** *(optional)* The amount of work todo (a number). Defaults to 0. Ordinarily these are constructed as a part of a tracker group (via `newItem`). * var completed = tracker.completed() Returns the ratio of completed work to work to be done. Range of 0 to 1. If total work to be done is 0 then it will return 0. * tracker.addWork(**todo**) * **todo** A number to add to the amount of work to be done. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. * tracker.completeWork(**completed**) * **completed** A number to add to the work complete Increase the amount of work complete, thus increasing the completion percentage. Will never increase the work completed past the amount of work todo. That is, percentages > 100% are not allowed. Triggers a `change` event. * tracker.finish() Marks this tracker as finished, tracker.completed() will now be 1. Triggers a `change` event. TrackerStream ============= * var tracker = new TrackerStream(**name**, **size**, **options**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **size** *(optional)* The number of bytes being sent through this stream. * **options** *(optional)* A hash of stream options The tracker stream object is a pass through stream that updates an internal tracker object each time a block passes through. It's intended to track downloads, file extraction and other related activities. You use it by piping your data source into it and then using it as your data source. If your data has a length attribute then that's used as the amount of work completed when the chunk is passed through. If it does not (eg, object streams) then each chunk counts as completing 1 unit of work, so your size should be the total number of objects being streamed. * tracker.addWork(**todo**) * **todo** Increase the expected overall size by **todo** bytes. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind # Borsh JS [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![Travis status](https://travis-ci.com/near/borsh.svg?branch=master)](https://travis-ci.com/near/borsh-js) [![NPM version](https://img.shields.io/npm/v/borsh.svg?style=flat-square)](https://npmjs.com/borsh) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/borsh.svg?style=flat-square)](https://npmjs.com/borsh) **Borsh JS** is an implementation of the [Borsh] binary serialization format for JavaScript and TypeScript projects. Borsh stands for _Binary Object Representation Serializer for Hashing_. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification. ## Examples ### Serializing an object ```javascript const value = new Test({ x: 255, y: 20, z: '123', q: [1, 2, 3] }); const schema = new Map([[Test, { kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]); const buffer = borsh.serialize(schema, value); ``` ### Deserializing an object ```javascript const newValue = borsh.deserialize(schema, Test, buffer); ``` ## Type Mappings | Borsh | TypeScript | |-----------------------|----------------| | `u8` integer | `number` | | `u16` integer | `number` | | `u32` integer | `number` | | `u64` integer | `BN` | | `u128` integer | `BN` | | `u256` integer | `BN` | | `u512` integer | `BN` | | `f32` float | N/A | | `f64` float | N/A | | fixed-size byte array | `Uint8Array` | | UTF-8 string | `string` | | option | `null` or type | | map | N/A | | set | N/A | | structs | `any` | ## Contributing Install dependencies: ```bash yarn install ``` Continuously build with: ```bash yarn dev ``` Run tests: ```bash yarn test ``` Run linter ```bash yarn lint ``` ## Publish Prepare `dist` version by running: ```bash yarn build ``` When publishing to npm use [np](https://github.com/sindresorhus/np). # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT.txt) and [LICENSE-APACHE](LICENSE-APACHE) for details. [Borsh]: https://borsh.io <!-- BEFORE EDITING THIS README Our README.md is auto-generated by combining pages in website/docs and website/readme-sources If you are sending a pull request to improve documentation, submit your changes in the source markdown files and we will generate the README from there. You can build the readme with this command: cd website && yarn build-readme --> # [![TypeScript Node](logo.svg?sanitize=true)](https://typestrong.org/ts-node) [![NPM version](https://img.shields.io/npm/v/ts-node.svg?style=flat)](https://npmjs.org/package/ts-node) [![NPM downloads](https://img.shields.io/npm/dm/ts-node.svg?style=flat)](https://npmjs.org/package/ts-node) [![Build status](https://img.shields.io/github/workflow/status/TypeStrong/ts-node/Continuous%20Integration)](https://github.com/TypeStrong/ts-node/actions?query=workflow%3A%22Continuous+Integration%22) [![Test coverage](https://codecov.io/gh/TypeStrong/ts-node/branch/main/graph/badge.svg)](https://codecov.io/gh/TypeStrong/ts-node) > TypeScript execution and REPL for node.js, with source map and native ESM support. The latest documentation can also be found on our website: <https://typestrong.org/ts-node> # Table of Contents * [Overview](#overview) * [Features](#features) * [Installation](#installation) * [Usage](#usage) * [Command Line](#command-line) * [Shebang](#shebang) * [node flags and other tools](#node-flags-and-other-tools) * [Programmatic](#programmatic) * [Configuration](#configuration) * [CLI flags](#cli-flags) * [Via tsconfig.json (recommended)](#via-tsconfigjson-recommended) * [@tsconfig/bases](#tsconfigbases) * [Default config](#default-config) * [`node` flags](#node-flags) * [Options](#options) * [CLI Options](#cli-options) * [help](#help) * [version](#version) * [eval](#eval) * [print](#print) * [interactive](#interactive) * [esm](#esm) * [TSConfig Options](#tsconfig-options) * [project](#project) * [skipProject](#skipproject) * [cwdMode](#cwdmode) * [compilerOptions](#compileroptions) * [showConfig](#showconfig) * [Typechecking](#typechecking) * [transpileOnly](#transpileonly) * [typeCheck](#typecheck) * [compilerHost](#compilerhost) * [files](#files) * [ignoreDiagnostics](#ignorediagnostics) * [Transpilation Options](#transpilation-options) * [ignore](#ignore) * [skipIgnore](#skipignore) * [compiler](#compiler) * [swc](#swc) * [transpiler](#transpiler) * [preferTsExts](#prefertsexts) * [Diagnostic Options](#diagnostic-options) * [logError](#logerror) * [pretty](#pretty) * [TS_NODE_DEBUG](#ts_node_debug) * [Advanced Options](#advanced-options) * [require](#require) * [cwd](#cwd) * [emit](#emit) * [scope](#scope) * [scopeDir](#scopedir) * [moduleTypes](#moduletypes) * [TS_NODE_HISTORY](#ts_node_history) * [noExperimentalReplAwait](#noexperimentalreplawait) * [experimentalResolver](#experimentalresolver) * [experimentalSpecifierResolution](#experimentalspecifierresolution) * [API Options](#api-options) * [SWC](#swc-1) * [CommonJS vs native ECMAScript modules](#commonjs-vs-native-ecmascript-modules) * [CommonJS](#commonjs) * [Native ECMAScript modules](#native-ecmascript-modules) * [Troubleshooting](#troubleshooting) * [Configuration](#configuration-1) * [Common errors](#common-errors) * [`TSError`](#tserror) * [`SyntaxError`](#syntaxerror) * [Unsupported JavaScript syntax](#unsupported-javascript-syntax) * [`ERR_REQUIRE_ESM`](#err_require_esm) * [`ERR_UNKNOWN_FILE_EXTENSION`](#err_unknown_file_extension) * [Missing Types](#missing-types) * [npx, yarn dlx, and node_modules](#npx-yarn-dlx-and-node_modules) * [Performance](#performance) * [Skip typechecking](#skip-typechecking) * [With typechecking](#with-typechecking) * [Advanced](#advanced) * [How it works](#how-it-works) * [Ignored files](#ignored-files) * [File extensions](#file-extensions) * [Skipping `node_modules`](#skipping-node_modules) * [Skipping pre-compiled TypeScript](#skipping-pre-compiled-typescript) * [Scope by directory](#scope-by-directory) * [Ignore by regexp](#ignore-by-regexp) * [paths and baseUrl ](#paths-and-baseurl) * [Why is this not built-in to ts-node?](#why-is-this-not-built-in-to-ts-node) * [Third-party compilers](#third-party-compilers) * [Transpilers](#transpilers) * [Third-party plugins](#third-party-plugins) * [Write your own plugin](#write-your-own-plugin) * [Module type overrides](#module-type-overrides) * [Caveats](#caveats) * [API](#api) * [Recipes](#recipes) * [Watching and restarting](#watching-and-restarting) * [AVA](#ava) * [CommonJS](#commonjs-1) * [Native ECMAScript modules](#native-ecmascript-modules-1) * [Gulp](#gulp) * [IntelliJ and Webstorm](#intellij-and-webstorm) * [Mocha](#mocha) * [Mocha 7 and newer](#mocha-7-and-newer) * [Mocha <=6](#mocha-6) * [Tape](#tape) * [Visual Studio Code](#visual-studio-code) * [Other](#other) * [License](#license) # Overview ts-node is a TypeScript execution engine and REPL for Node.js. It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling. This is accomplished by hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.js tools and libraries. ## Features * Automatic sourcemaps in stack traces * Automatic `tsconfig.json` parsing * Automatic defaults to match your node version * Typechecking (optional) * REPL * Write standalone scripts * Native ESM loader * Use third-party transpilers * Use custom transformers * Integrate with test runners, debuggers, and CLI tools * Compatible with pre-compilation for production ![TypeScript REPL](website/static/img/screenshot.png) # Installation ```shell # Locally in your project. npm install -D typescript npm install -D ts-node # Or globally with TypeScript. npm install -g typescript npm install -g ts-node # Depending on configuration, you may also need these npm install -D tslib @types/node ``` **Tip:** Installing modules locally allows you to control and share the versions through `package.json`. ts-node will always resolve the compiler from `cwd` before checking relative to its own installation. # Usage ## Command Line ```shell # Execute a script as `node` + `tsc`. ts-node script.ts # Starts a TypeScript REPL. ts-node # Execute code with TypeScript. ts-node -e 'console.log("Hello, world!")' # Execute, and print, code with TypeScript. ts-node -p -e '"Hello, world!"' # Pipe scripts to execute with TypeScript. echo 'console.log("Hello, world!")' | ts-node # Equivalent to ts-node --transpileOnly ts-node-transpile-only script.ts # Equivalent to ts-node --cwdMode ts-node-cwd script.ts # Equivalent to ts-node --esm ts-node-esm script.ts ``` ## Shebang To write scripts with maximum portability, [specify options in your `tsconfig.json`](#via-tsconfigjson-recommended) and omit them from the shebang. ```typescript twoslash #!/usr/bin/env ts-node // ts-node options are read from tsconfig.json console.log("Hello, world!") ``` Including options within the shebang requires the [`env -S` flag](https://manpages.debian.org/bullseye/coreutils/env.1.en.html#S), which is available on recent versions of `env`. ([compatibility](https://github.com/TypeStrong/ts-node/pull/1448#issuecomment-913895766)) ```typescript twoslash #!/usr/bin/env -S ts-node --files // This shebang works on Mac and Linux with newer versions of env // Technically, Mac allows omitting `-S`, but Linux requires it ``` To test your version of `env` for compatibility with `-S`: ```shell # Note that these unusual quotes are necessary /usr/bin/env --debug '-S echo foo bar' ``` ## node flags and other tools You can register ts-node without using our CLI: `node -r ts-node/register` and `node --loader ts-node/esm` In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads. This can be combined with other node flags. ```shell NODE_OPTIONS="-r ts-node/register --no-warnings" node ./index.ts ``` Or, if you require native ESM support: ```shell NODE_OPTIONS="--loader ts-node/esm" ``` This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code. If you are invoking node directly, you can avoid the environment variable and pass those flags to node. ```shell node --loader ts-node/esm --inspect ./index.ts ``` ## Programmatic You can require ts-node and register the loader for future requires by using `require('ts-node').register({ /* options */ })`. Check out our [API](#api) for more features. # Configuration ts-node supports a variety of options which can be specified via `tsconfig.json`, as CLI flags, as environment variables, or programmatically. For a complete list, see [Options](#options). ## CLI flags ts-node CLI flags must come *before* the entrypoint script. For example: ```shell $ ts-node --project tsconfig-dev.json say-hello.ts Ronald Hello, Ronald! ``` ## Via tsconfig.json (recommended) ts-node automatically finds and loads `tsconfig.json`. Most ts-node options can be specified in a `"ts-node"` object using their programmatic, camelCase names. We recommend this because it works even when you cannot pass CLI flags, such as `node --require ts-node/register` and when using shebangs. Use `--skipProject` to skip loading the `tsconfig.json`. Use `--project` to explicitly specify the path to a `tsconfig.json`. When searching, it is resolved using [the same search behavior as `tsc`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). By default, this search is performed relative to the entrypoint script. In `--cwdMode` or if no entrypoint is specified -- for example when using the REPL -- the search is performed relative to `--cwd` / `process.cwd()`. You can use this sample configuration as a starting point: ```jsonc title="tsconfig.json" { // This is an alias to @tsconfig/node16: https://github.com/tsconfig/bases "extends": "ts-node/node16/tsconfig.json", // Most ts-node options can be specified here using their programmatic names. "ts-node": { // It is faster to skip typechecking. // Remove if you want ts-node to do typechecking. "transpileOnly": true, "files": true, "compilerOptions": { // compilerOptions specified here will override those declared below, // but *only* in ts-node. Useful if you want ts-node and tsc to use // different options with a single tsconfig.json. } }, "compilerOptions": { // typescript options here } } ``` Our bundled [JSON schema](https://unpkg.com/browse/ts-node@latest/tsconfig.schema.json) lists all compatible options. ### @tsconfig/bases [@tsconfig/bases](https://github.com/tsconfig/bases) maintains recommended configurations for several node versions. As a convenience, these are bundled with ts-node. ```jsonc title="tsconfig.json" { "extends": "ts-node/node16/tsconfig.json", // Or install directly with `npm i -D @tsconfig/node16` "extends": "@tsconfig/node16/tsconfig.json", } ``` ### Default config If no `tsconfig.json` is loaded from disk, ts-node will use the newest recommended defaults from [@tsconfig/bases](https://github.com/tsconfig/bases/) compatible with your `node` and `typescript` versions. With the latest `node` and `typescript`, this is [`@tsconfig/node16`](https://github.com/tsconfig/bases/blob/master/bases/node16.json). Older versions of `typescript` are incompatible with `@tsconfig/node16`. In those cases we will use an older default configuration. When in doubt, `ts-node --showConfig` will log the configuration being used, and `ts-node -vv` will log `node` and `typescript` versions. ## `node` flags [`node` flags](https://nodejs.org/api/cli.html) must be passed directly to `node`; they cannot be passed to the ts-node binary nor can they be specified in `tsconfig.json` We recommend using the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) environment variable to pass options to `node`. ```shell NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts ``` Alternatively, you can invoke `node` directly and install ts-node via `--require`/`-r` ```shell node --trace-deprecation --abort-on-uncaught-exception -r ts-node/register ./index.ts ``` # Options All command-line flags support both `--camelCase` and `--hyphen-case`. Most options can be declared in your tsconfig.json: [Configuration via tsconfig.json](#via-tsconfigjson-recommended) `ts-node` supports `--print` (`-p`), `--eval` (`-e`), `--require` (`-r`) and `--interactive` (`-i`) similar to the [node.js CLI](https://nodejs.org/api/cli.html). `ts-node` supports `--project` and `--showConfig` similar to the [tsc CLI](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options). *Environment variables, where available, are in `ALL_CAPS`* ## CLI Options ### help ```shell ts-node --help ``` Prints the help text ### version ```shell ts-node -v ts-node -vvv ``` Prints the version. `-vv` includes node and typescript compiler versions. `-vvv` includes absolute paths to ts-node and typescript installations. ### eval ```shell ts-node -e <typescript code> # Example ts-node -e 'console.log("Hello world!")' ``` Evaluate code ### print ```shell ts-node -p -e <typescript code> # Example ts-node -p -e '"Hello world!"' ``` Print result of `--eval` ### interactive ```shell ts-node -i ``` Opens the REPL even if stdin does not appear to be a terminal ### esm ```shell ts-node --esm ts-node-esm ``` Bootstrap with the ESM loader, enabling full ESM support ## TSConfig Options ### project ```shell ts-node -P <path/to/tsconfig> ts-node --project <path/to/tsconfig> ``` Path to tsconfig file. *Note the uppercase `-P`. This is different from `tsc`'s `-p/--project` option.* *Environment:* `TS_NODE_PROJECT` ### skipProject ```shell ts-node --skipProject ``` Skip project config resolution and loading *Default:* `false` <br/> *Environment:* `TS_NODE_SKIP_PROJECT` ### cwdMode ```shell ts-node -c ts-node --cwdMode ts-node-cwd ``` Resolve config relative to the current directory instead of the directory of the entrypoint script ### compilerOptions ```shell ts-node -O <json compilerOptions> ts-node --compilerOptions <json compilerOptions> ``` JSON object to merge with compiler options *Environment:* `TS_NODE_COMPILER_OPTIONS` ### showConfig ```shell ts-node --showConfig ``` Print resolved `tsconfig.json`, including `ts-node` options, and exit ## Typechecking ### transpileOnly ```shell ts-node -T ts-node --transpileOnly ``` Use TypeScript's faster `transpileModule` *Default:* `false`<br/> *Environment:* `TS_NODE_TRANSPILE_ONLY` ### typeCheck ```shell ts-node --typeCheck ``` Opposite of `--transpileOnly` *Default:* `true`<br/> *Environment:* `TS_NODE_TYPE_CHECK` ### compilerHost ```shell ts-node -H ts-node --compilerHost ``` Use TypeScript's compiler host API *Default:* `false` <br/> *Environment:* `TS_NODE_COMPILER_HOST` ### files ```shell ts-node --files ``` Load `files`, `include` and `exclude` from `tsconfig.json` on startup. This may avoid certain typechecking failures. See [Missing types](#missing-types) for details. *Default:* `false` <br/> *Environment:* `TS_NODE_FILES` ### ignoreDiagnostics ```shell ts-node -D <code,code> ts-node --ignoreDiagnostics <code,code> ``` Ignore TypeScript warnings by diagnostic code *Environment:* `TS_NODE_IGNORE_DIAGNOSTICS` ## Transpilation Options ### ignore ```shell ts-node -I <regexp matching ignored files> ts-node --ignore <regexp matching ignored files> ``` Override the path patterns to skip compilation *Default:* `/node_modules/` <br/> *Environment:* `TS_NODE_IGNORE` ### skipIgnore ```shell ts-node --skipIgnore ``` Skip ignore checks *Default:* `false` <br/> *Environment:* `TS_NODE_SKIP_IGNORE` ### compiler ```shell ts-node -C <name> ts-node --compiler <name> ``` Specify a custom TypeScript compiler *Default:* `typescript` <br/> *Environment:* `TS_NODE_COMPILER` ### swc ```shell ts-node --swc ``` Transpile with [swc](#swc). Implies `--transpileOnly` *Default:* `false` ### transpiler ```shell ts-node --transpiler <name> # Example ts-node --transpiler ts-node/transpilers/swc ``` Use a third-party, non-typechecking transpiler ### preferTsExts ```shell ts-node --preferTsExts ``` Re-order file extensions so that TypeScript imports are preferred *Default:* `false` <br/> *Environment:* `TS_NODE_PREFER_TS_EXTS` ## Diagnostic Options ### logError ```shell ts-node --logError ``` Logs TypeScript errors to stderr instead of throwing exceptions *Default:* `false` <br/> *Environment:* `TS_NODE_LOG_ERROR` ### pretty ```shell ts-node --pretty ``` Use pretty diagnostic formatter *Default:* `false` <br/> *Environment:* `TS_NODE_PRETTY` ### TS_NODE_DEBUG ```shell TS_NODE_DEBUG=true ts-node ``` Enable debug logging ## Advanced Options ### require ```shell ts-node -r <module name or path> ts-node --require <module name or path> ``` Require a node module before execution ### cwd ```shell ts-node --cwd <path/to/directory> ``` Behave as if invoked in this working directory *Default:* `process.cwd()`<br/> *Environment:* `TS_NODE_CWD` ### emit ```shell ts-node --emit ``` Emit output files into `.ts-node` directory. Requires `--compilerHost` *Default:* `false` <br/> *Environment:* `TS_NODE_EMIT` ### scope ```shell ts-node --scope ``` Scope compiler to files within `scopeDir`. Anything outside this directory is ignored. *Default:* `false` <br/> *Environment:* `TS_NODE_SCOPE` ### scopeDir ```shell ts-node --scopeDir <path/to/directory> ``` Directory within which compiler is limited when `scope` is enabled. *Default:* First of: `tsconfig.json` "rootDir" if specified, directory containing `tsconfig.json`, or cwd if no `tsconfig.json` is loaded.<br/> *Environment:* `TS_NODE_SCOPE_DIR` ### moduleTypes Override the module type of certain files, ignoring the `package.json` `"type"` field. See [Module type overrides](#module-type-overrides) for details. *Default:* obeys `package.json` `"type"` and `tsconfig.json` `"module"` <br/> *Can only be specified via `tsconfig.json` or API.* ### TS_NODE_HISTORY ```shell TS_NODE_HISTORY=<path/to/history/file> ts-node ``` Path to history file for REPL *Default:* `~/.ts_node_repl_history` ### noExperimentalReplAwait ```shell ts-node --noExperimentalReplAwait ``` Disable top-level await in REPL. Equivalent to node's [`--no-experimental-repl-await`](https://nodejs.org/api/cli.html#cli_no_experimental_repl_await) *Default:* Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.<br/> *Environment:* `TS_NODE_EXPERIMENTAL_REPL_AWAIT` set `false` to disable ### experimentalResolver Enable experimental hooks that re-map imports and require calls to support: * remapping extensions, e.g. so that `import "./foo.js"` will execute `foo.ts`. Currently the following extensions will be mapped: * `.js` to `.ts`, `.tsx`, or `.jsx` * `.cjs` to `.cts` * `.mjs` to `.mts` * `.jsx` to `.tsx` * including file extensions in CommonJS, for consistency with ESM where this is often mandatory In the future, this hook will also support: * `baseUrl`, `paths` * `rootDirs` * `outDir` to `rootDir` mappings for composite projects and monorepos For details, see [#1514](https://github.com/TypeStrong/ts-node/issues/1514). *Default:* `false`, but will likely be enabled by default in a future version<br/> *Can only be specified via `tsconfig.json` or API.* ### experimentalSpecifierResolution ```shell ts-node --experimentalSpecifierResolution node ``` Like node's [`--experimental-specifier-resolution`](https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#customizing-esm-specifier-resolution-algorithm), but can also be set in your `tsconfig.json` for convenience. Requires [`esm`](#esm) to be enabled. *Default:* `explicit`<br/> ## API Options The API includes [additional options](https://typestrong.org/ts-node/api/interfaces/RegisterOptions.html) not shown here. # SWC SWC support is built-in via the `--swc` flag or `"swc": true` tsconfig option. [SWC](https://swc.rs) is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster than vanilla `transpileOnly`. To use it, first install `@swc/core` or `@swc/wasm`. If using `importHelpers`, also install `@swc/helpers`. If `target` is less than "es2015" and using `async`/`await` or generator functions, also install `regenerator-runtime`. ```shell npm i -D @swc/core @swc/helpers regenerator-runtime ``` Then add the following to your `tsconfig.json`. ```jsonc title="tsconfig.json" { "ts-node": { "swc": true } } ``` > SWC uses `@swc/helpers` instead of `tslib`. If you have enabled `importHelpers`, you must also install `@swc/helpers`. # CommonJS vs native ECMAScript modules TypeScript is almost always written using modern `import` syntax, but it is also transformed before being executed by the underlying runtime. You can choose to either transform to CommonJS or to preserve the native `import` syntax, using node's native ESM support. Configuration is different for each. Here is a brief comparison of the two. | CommonJS | Native ECMAScript modules | |---|---| | Write native `import` syntax | Write native `import` syntax | | Transforms `import` into `require()` | Does not transform `import` | | Node executes scripts using the classic [CommonJS loader](https://nodejs.org/dist/latest-v16.x/docs/api/modules.html) | Node executes scripts using the new [ESM loader](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html) | | Use any of:<br/>`ts-node`<br/>`node -r ts-node/register`<br/>`NODE_OPTIONS="ts-node/register" node`<br/>`require('ts-node').register({/* options */})` | Use any of:<br/>`ts-node --esm`<br/>`ts-node-esm`<br/>Set `"esm": true` in `tsconfig.json`<br />`node --loader ts-node/esm`<br/>`NODE_OPTIONS="--loader ts-node/esm" node` | ## CommonJS Transforming to CommonJS is typically simpler and more widely supported because it is older. You must remove [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) from `package.json` and set [`"module": "CommonJS"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`. ```jsonc title="package.json" { // This can be omitted; commonjs is the default "type": "commonjs" } ``` ```jsonc title="tsconfig.json" { "compilerOptions": { "module": "CommonJS" } } ``` If you must keep `"module": "ESNext"` for `tsc`, webpack, or another build tool, you can set an override for ts-node. ```jsonc title="tsconfig.json" { "compilerOptions": { "module": "ESNext" }, "ts-node": { "compilerOptions": { "module": "CommonJS" } } } ``` ## Native ECMAScript modules [Node's ESM loader hooks](https://nodejs.org/api/esm.html#esm_experimental_loaders) are [**experimental**](https://nodejs.org/api/documentation.html#documentation_stability_index) and subject to change. ts-node's ESM support is as stable as possible, but it relies on APIs which node can *and will* break in new versions of node. Thus it is not recommended for production. For complete usage, limitations, and to provide feedback, see [#1007](https://github.com/TypeStrong/ts-node/issues/1007). You must set [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) in `package.json` and [`"module": "ESNext"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`. ```jsonc title="package.json" { "type": "module" } ``` ```jsonc title="tsconfig.json" { "compilerOptions": { "module": "ESNext" // or ES2015, ES2020 }, "ts-node": { // Tell ts-node CLI to install the --loader automatically, explained below "esm": true } } ``` You must also ensure node is passed `--loader`. The ts-node CLI will do this automatically with our `esm` option. > Note: `--esm` must spawn a child process to pass it `--loader`. This may change if node adds the ability to install loader hooks > into the current process. ```shell # pass the flag ts-node --esm # Use the convenience binary ts-node-esm # or add `"esm": true` to your tsconfig.json to make it automatic ts-node ``` If you are not using our CLI, pass the loader flag to node. ```shell node --loader ts-node/esm ./index.ts # Or via environment variable NODE_OPTIONS="--loader ts-node/esm" node ./index.ts ``` # Troubleshooting ## Configuration ts-node uses sensible default configurations to reduce boilerplate while still respecting `tsconfig.json` if you have one. If you are unsure which configuration is used, you can log it with `ts-node --showConfig`. This is similar to `tsc --showConfig` but includes `"ts-node"` options as well. ts-node also respects your locally-installed `typescript` version, but global installations fallback to the globally-installed `typescript`. If you are unsure which versions are used, `ts-node -vv` will log them. ```shell $ ts-node -vv ts-node v10.0.0 node v16.1.0 compiler v4.2.2 $ ts-node --showConfig { "compilerOptions": { "target": "es6", "lib": [ "es6", "dom" ], "rootDir": "./src", "outDir": "./.ts-node", "module": "commonjs", "moduleResolution": "node", "strict": true, "declaration": false, "sourceMap": true, "inlineSources": true, "types": [ "node" ], "stripInternal": true, "incremental": true, "skipLibCheck": true, "importsNotUsedAsValues": "error", "inlineSourceMap": false, "noEmit": false }, "ts-node": { "cwd": "/d/project", "projectSearchDir": "/d/project", "require": [], "project": "/d/project/tsconfig.json" } } ``` ## Common errors It is important to differentiate between errors from ts-node, errors from the TypeScript compiler, and errors from `node`. It is also important to understand when errors are caused by a type error in your code, a bug in your code, or a flaw in your configuration. ### `TSError` Type errors from the compiler are thrown as a `TSError`. These are the same as errors you get from `tsc`. ### `SyntaxError` Any error that is not a `TSError` is from node.js (e.g. `SyntaxError`), and cannot be fixed by TypeScript or ts-node. These are bugs in your code or configuration. #### Unsupported JavaScript syntax Your version of `node` may not support all JavaScript syntax supported by TypeScript. The compiler must transform this syntax via "downleveling," which is controlled by the [tsconfig `"target"` option](https://www.typescriptlang.org/tsconfig#target). Otherwise your code will compile fine, but node will throw a `SyntaxError`. For example, `node` 12 does not understand the `?.` optional chaining operator. If you use `"target": "esnext"`, then the following TypeScript syntax: ```typescript twoslash const bar: string | undefined = foo?.bar; ``` will compile into this JavaScript: ```javascript const a = foo?.bar; ``` When you try to run this code, node 12 will throw a `SyntaxError`. To fix this, you must switch to `"target": "es2019"` or lower so TypeScript transforms `?.` into something `node` can understand. ### `ERR_REQUIRE_ESM` This error is thrown by node when a module is `require()`d, but node believes it should execute as native ESM. This can happen for a few reasons: * You have installed an ESM dependency but your own code compiles to CommonJS. * Solution: configure your project to compile and execute as native ESM. [Docs](#native-ecmascript-modules) * Solution: downgrade the dependency to an older, CommonJS version. * You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS --> * Solution: if supported by the relevant tool, rename your config file to `.cts` * Solution: Configure a module type override. [Docs](#module-type-overrides) * You have a mix of CommonJS and native ESM in your project * Solution: double-check all package.json "type" and tsconfig.json "module" configuration [Docs](#commonjs-vs-native-ecmascript-modules) * Solution: consider simplifying by making your project entirely CommonJS or entirely native ESM ### `ERR_UNKNOWN_FILE_EXTENSION` This error is thrown by node when a module has an unrecognized file extension, or no extension at all, and is being executed as native ESM. This can happen for a few reasons: * You are using a tool which has an extensionless binary, such as `mocha`. * CommonJS supports extensionless files but native ESM does not. * Solution: upgrade to ts-node >=[v10.6.0](https://github.com/TypeStrong/ts-node/releases/tag/v10.6.0), which implements a workaround. * Our ESM loader is not installed. * Solution: Use `ts-node-esm`, `ts-node --esm`, or add `"ts-node": {"esm": true}` to your tsconfig.json. [Docs](#native-ecmascript-modules) * You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS --> * Solution: if supported by the relevant tool, rename your config file to `.cts` * Solution: Configure a module type override. [Docs](#module-type-overrides) ## Missing Types ts-node does *not* eagerly load `files`, `include` or `exclude` by default. This is because a large majority of projects do not use all of the files in a project directory (e.g. `Gulpfile.ts`, runtime vs tests) and parsing every file for types slows startup time. Instead, ts-node starts with the script file (e.g. `ts-node index.ts`) and TypeScript resolves dependencies based on imports and references. Occasionally, this optimization leads to missing types. Fortunately, there are other ways to include them in typechecking. For global definitions, you can use the `typeRoots` compiler option. This requires that your type definitions be structured as type packages (not loose TypeScript definition files). More details on how this works can be found in the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types). Example `tsconfig.json`: ```jsonc { "compilerOptions": { "typeRoots" : ["./node_modules/@types", "./typings"] } } ``` Example project structure: ```text <project_root>/ -- tsconfig.json -- typings/ -- <module_name>/ -- index.d.ts ``` Example module declaration file: ```typescript twoslash declare module '<module_name>' { // module definitions go here } ``` For module definitions, you can use [`paths`](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping): ```jsonc title="tsconfig.json" { "compilerOptions": { "baseUrl": ".", "paths": { "custom-module-type": ["types/custom-module-type"] } } } ``` Another option is [triple-slash directives](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). This may be helpful if you prefer not to change your `compilerOptions` or structure your type definitions for `typeRoots`. Below is an example of a triple-slash directive as a relative path within your project: ```typescript twoslash /// <reference path="./types/lib_greeter" /> import {Greeter} from "lib_greeter" const g = new Greeter(); g.sayHello(); ``` If none of the above work, and you *must* use `files`, `include`, or `exclude`, enable our [`files`](#files) option. ## npx, yarn dlx, and node_modules When executing TypeScript with `npx` or `yarn dlx`, the code resides within a temporary `node_modules` directory. The contents of `node_modules` are ignored by default. If execution fails, enable [`skipIgnore`](#skipignore). <!--See also: [npx and yarn dlx](./recipes/npx-and-yarn-dlx.md)--> # Performance These tricks will make ts-node faster. ## Skip typechecking It is often better to typecheck as part of your tests or linting. You can run `tsc --noEmit` to do this. In these cases, ts-node can skip typechecking, making it much faster. To skip typechecking in ts-node, do one of the following: * Enable [swc](#swc) * This is by far the fastest option * Enable [`transpileOnly`](#transpileonly) to skip typechecking without swc ## With typechecking If you absolutely must typecheck in ts-node: * Avoid dynamic `require()` which may trigger repeated typechecking; prefer `import` * Try with and without `--files`; one may be faster depending on your project * Check `tsc --showConfig`; make sure all executed files are included * Enable [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck) * Set a [`types`](https://www.typescriptlang.org/tsconfig#types) array to avoid loading unnecessary `@types` # Advanced ## How it works ts-node works by registering hooks for `.ts`, `.tsx`, `.js`, and/or `.jsx` extensions. Vanilla `node` loads `.js` by reading code from disk and executing it. Our hook runs in the middle, transforming code from TypeScript to JavaScript and passing the result to `node` for execution. This transformation will respect your `tsconfig.json` as if you had compiled via `tsc`. We also register a few other hooks to apply sourcemaps to stack traces and remap from `.js` imports to `.ts`. ## Ignored files ts-node transforms certain files and ignores others. We refer to this mechanism as "scoping." There are various options to configure scoping, so that ts-node transforms only the files in your project. > **Warning:** > > An ignored file can still be executed by node.js. Ignoring a file means we do not transform it from TypeScript into JavaScript, but it does not prevent execution. > > If a file requires transformation but is ignored, node may either fail to resolve it or attempt to execute it as vanilla JavaScript. This may cause syntax errors or other failures, because node does not understand TypeScript type syntax nor bleeding-edge ECMAScript features. ### File extensions `.js` and `.jsx` are only transformed when [`allowJs`](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options) is enabled. `.tsx` and `.jsx` are only transformed when [`jsx`](https://www.typescriptlang.org/docs/handbook/jsx.html) is enabled. > **Warning:** > > When ts-node is used with `allowJs`, *all* non-ignored JavaScript files are transformed by ts-node. ### Skipping `node_modules` By default, ts-node avoids compiling files in `/node_modules/` for three reasons: 1. Modules should always be published in a format node.js can consume 2. Transpiling the entire dependency tree will make your project slower 3. Differing behaviours between TypeScript and node.js (e.g. ES2015 modules) can result in a project that works until you decide to support a feature natively from node.js If you need to import uncompiled TypeScript in `node_modules`, use [`--skipIgnore`](#skipignore) or [`TS_NODE_SKIP_IGNORE`](#skipignore) to bypass this restriction. ### Skipping pre-compiled TypeScript If a compiled JavaScript file with the same name as a TypeScript file already exists, the TypeScript file will be ignored. ts-node will import the pre-compiled JavaScript. To force ts-node to import the TypeScript source, not the precompiled JavaScript, use [`--preferTsExts`](#prefertsexts). ### Scope by directory Our [`scope`](#scope) and [`scopeDir`](#scopedir) options will limit transformation to files within a directory. ### Ignore by regexp Our [`ignore`](#ignore) option will ignore files matching one or more regular expressions. ## paths and baseUrl&#xA; You can use ts-node together with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths) to load modules according to the `paths` section in `tsconfig.json`. ```jsonc title="tsconfig.json" { "ts-node": { // Do not forget to `npm i -D tsconfig-paths` "require": ["tsconfig-paths/register"] } } ``` ### Why is this not built-in to ts-node? The official TypeScript Handbook explains the intended purpose for `"paths"` in ["Additional module resolution flags"](https://www.typescriptlang.org/docs/handbook/module-resolution.html#additional-module-resolution-flags). > The TypeScript compiler has a set of additional flags to *inform* the compiler of transformations that are expected to happen to the sources to generate the final output. > > It is important to note that the compiler will not perform any of these transformations; it just uses these pieces of information to guide the process of resolving a module import to its definition file. This means `"paths"` are intended to describe mappings that the build tool or runtime *already* performs, not to tell the build tool or runtime how to resolve modules. In other words, they intend us to write our imports in a way `node` already understands. For this reason, ts-node does not modify `node`'s module resolution behavior to implement `"paths"` mappings. ## Third-party compilers Some projects require a patched typescript compiler which adds additional features. For example, [`ttypescript`](https://github.com/cevek/ttypescript/tree/master/packages/ttypescript) and [`ts-patch`](https://github.com/nonara/ts-patch#readme) add the ability to configure custom transformers. These are drop-in replacements for the vanilla `typescript` module and implement the same API. For example, to use `ttypescript` and `ts-transformer-keys`, add this to your `tsconfig.json`: ```jsonc title="tsconfig.json" { "ts-node": { // This can be omitted when using ts-patch "compiler": "ttypescript" }, "compilerOptions": { // plugin configuration is the same for both ts-patch and ttypescript "plugins": [ { "transform": "ts-transformer-keys/transformer" } ] } } ``` ## Transpilers ts-node supports third-party transpilers as plugins. Transpilers such as swc can transform TypeScript into JavaScript much faster than the TypeScript compiler. You will still benefit from ts-node's automatic `tsconfig.json` discovery, sourcemap support, and global ts-node CLI. Plugins automatically derive an appropriate configuration from your existing `tsconfig.json` which simplifies project boilerplate. > **What is the difference between a compiler and a transpiler?** > > For our purposes, a compiler implements TypeScript's API and can perform typechecking. > A third-party transpiler does not. Both transform TypeScript into JavaScript. ### Third-party plugins The `transpiler` option allows using third-party transpiler plugins with ts-node. `transpiler` must be given the name of a module which can be `require()`d. The built-in `swc` plugin is exposed as `ts-node/transpilers/swc`. For example, to use a hypothetical "@cspotcode/fast-ts-compiler", first install it into your project: `npm install @cspotcode/fast-ts-compiler` Then add the following to your tsconfig: ```jsonc title="tsconfig.json" { "ts-node": { "transpileOnly": true, "transpiler": "@cspotcode/fast-ts-compiler" } } ``` ### Write your own plugin To write your own transpiler plugin, check our [API docs](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html). Plugins are `require()`d by ts-node, so they can be a local script or a node module published to npm. The module must export a `create` function described by our [`TranspilerModule`](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html) interface. `create` is invoked by ts-node at startup to create one or more transpiler instances. The instances are used to transform TypeScript into JavaScript. For a working example, check out out our bundled swc plugin: https://github.com/TypeStrong/ts-node/blob/main/src/transpilers/swc.ts ## Module type overrides > Wherever possible, it is recommended to use TypeScript's [`NodeNext` or `Node16` mode](https://www.typescriptlang.org/docs/handbook/esm-node.html) instead of the options described > in this section. Setting `"module": "NodeNext"` and using the `.cts` file extension should work well for most projects. When deciding how a file should be compiled and executed -- as either CommonJS or native ECMAScript module -- ts-node matches `node` and `tsc` behavior. This means TypeScript files are transformed according to your `tsconfig.json` `"module"` option and executed according to node's rules for the `package.json` `"type"` field. Set `"module": "NodeNext"` and everything should work. In rare cases, you may need to override this behavior for some files. For example, some tools read a `name-of-tool.config.ts` and require that file to execute as CommonJS. If you have `package.json` configured with `"type": "module"` and `tsconfig.json` with `"module": "esnext"`, the config is native ECMAScript by default and will raise an error. You will need to force the config and any supporting scripts to execute as CommonJS. In these situations, our `moduleTypes` option can override certain files to be CommonJS or ESM. Similar overriding is possible by using `.mts`, `.cts`, `.cjs` and `.mjs` file extensions. `moduleTypes` achieves the same effect for `.ts` and `.js` files, and *also* overrides your `tsconfig.json` `"module"` config appropriately. The following example tells ts-node to execute a webpack config as CommonJS: ```jsonc title="tsconfig.json" { "ts-node": { "transpileOnly": true, "moduleTypes": { "webpack.config.ts": "cjs", // Globs are also supported with the same behavior as tsconfig "include" "webpack-config-scripts/**/*": "cjs" } }, "compilerOptions": { "module": "es2020", "target": "es2020" } } ``` Each key is a glob pattern with the same syntax as tsconfig's `"include"` array. When multiple patterns match the same file, the last pattern takes precedence. * `cjs` overrides matches files to compile and execute as CommonJS. * `esm` overrides matches files to compile and execute as native ECMAScript modules. * `package` resets either of the above to default behavior, which obeys `package.json` `"type"` and `tsconfig.json` `"module"` options. ### Caveats Files with an overridden module type are transformed with the same limitations as [`isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules). This will only affect rare cases such as using `const enum`s with [`preserveConstEnums`](https://www.typescriptlang.org/tsconfig#preserveConstEnums) disabled. This feature is meant to facilitate scenarios where normal `compilerOptions` and `package.json` configuration is not possible. For example, a `webpack.config.ts` cannot be given its own `package.json` to override `"type"`. Wherever possible you should favor using traditional `package.json` and `tsconfig.json` configurations. ## API ts-node's complete API is documented here: [API Docs](https://typestrong.org/ts-node/api/) Here are a few highlights of what you can accomplish: * [`create()`](https://typestrong.org/ts-node/api/index.html#create) creates ts-node's compiler service without registering any hooks. * [`createRepl()`](https://typestrong.org/ts-node/api/index.html#createRepl) creates an instance of our REPL service, so you can create your own TypeScript-powered REPLs. * [`createEsmHooks()`](https://typestrong.org/ts-node/api/index.html#createEsmHooks) creates our ESM loader hooks, suitable for composing with other loaders or augmenting with additional features. # Recipes ## Watching and restarting ts-node focuses on adding first-class TypeScript support to node. Watching files and code reloads are out of scope for the project. If you want to restart the `ts-node` process on file change, existing node.js tools such as [nodemon](https://github.com/remy/nodemon), [onchange](https://github.com/Qard/onchange) and [node-dev](https://github.com/fgnass/node-dev) work. There's also [`ts-node-dev`](https://github.com/whitecolor/ts-node-dev), a modified version of [`node-dev`](https://github.com/fgnass/node-dev) using `ts-node` for compilation that will restart the process on file change. Note that `ts-node-dev` is incompatible with our native ESM loader. ## AVA Assuming you are configuring AVA via your `package.json`, add one of the following configurations. ### CommonJS Use this configuration if your `package.json` does not have `"type": "module"`. ```jsonc title="package.json" { "ava": { "extensions": [ "ts" ], "require": [ "ts-node/register" ] } } ``` ### Native ECMAScript modules This configuration is necessary if your `package.json` has `"type": "module"`. ```jsonc title="package.json" { "ava": { "extensions": { "ts": "module" }, "nonSemVerExperiments": { "configurableModuleFormat": true }, "nodeArguments": [ "--loader=ts-node/esm" ] } } ``` ## Gulp ts-node support is built-in to gulp. ```sh # Create a `gulpfile.ts` and run `gulp`. gulp ``` See also: https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles#transpilation ## IntelliJ and Webstorm Create a new Node.js configuration and add `-r ts-node/register` to "Node parameters." **Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in IntelliJ, specify under "Environment Variables": `TS_NODE_PROJECT=<tsconfig.json>`. ## Mocha ### Mocha 7 and newer ```shell mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'tests/**/*.{ts,tsx}' [...args] ``` Or specify options via your mocha config file. ```jsonc title=".mocharc.json" { // Specify "require" for CommonJS "require": "ts-node/register", // Specify "loader" for native ESM "loader": "ts-node/esm", "extensions": ["ts", "tsx"], "spec": [ "tests/**/*.spec.*" ], "watch-files": [ "src" ] } ``` See also: https://mochajs.org/#configuring-mocha-nodejs ### Mocha <=6 ```shell mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args] ``` **Note:** `--watch-extensions` is only used in `--watch` mode. ## Tape ```shell ts-node node_modules/tape/bin/tape [...args] ``` ## Visual Studio Code Create a new Node.js debug configuration, add `-r ts-node/register` to node args and move the `program` to the `args` list (so VS Code doesn't look for `outFiles`). ```jsonc title=".vscode/launch.json" { "configurations": [{ "type": "node", "request": "launch", "name": "Launch Program", "runtimeArgs": [ "-r", "ts-node/register" ], "args": [ "${workspaceFolder}/src/index.ts" ] }], } ``` **Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in VS Code, add an "env" key into the launch configuration: `"env": { "TS_NODE_PROJECT": "<tsconfig.json>" }`. ## Other In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads. ```shell NODE_OPTIONS="-r ts-node/register" ``` Or, if you require native ESM support: ```shell NODE_OPTIONS="--loader ts-node/esm" ``` This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code. # License ts-node is licensed under the MIT license. [MIT](https://github.com/TypeStrong/ts-node/blob/main/LICENSE) ts-node includes source code from Node.js which is licensed under the MIT license. [Node.js license information](https://raw.githubusercontent.com/nodejs/node/master/LICENSE) ts-node includes source code from the TypeScript compiler which is licensed under the Apache License 2.0. [TypeScript license information](https://github.com/microsoft/TypeScript/blob/master/LICENSE.txt) NOTE: The default branch has been renamed! master is now named main If you have a local clone, you can update it by running: ```shell git branch -m master main git fetch origin git branch -u origin/main main ``` # **node-addon-api module** This module contains **header-only C++ wrapper classes** which simplify the use of the C based [Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) provided by Node.js when using C++. It provides a C++ object model and exception handling semantics with low overhead. There are three options for implementing addons: Node-API, nan, or direct use of internal V8, libuv and Node.js libraries. Unless there is a need for direct access to functionality which is not exposed by Node-API as outlined in [C/C++ addons](https://nodejs.org/dist/latest/docs/api/addons.html) in Node.js core, use Node-API. Refer to [C/C++ addons with Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html) for more information on Node-API. Node-API is an ABI stable C interface provided by Node.js for building native addons. It is independent from the underlying JavaScript runtime (e.g. V8 or ChakraCore) and is maintained as part of Node.js itself. It is intended to insulate native addons from changes in the underlying JavaScript engine and allow modules compiled for one version to run on later versions of Node.js without recompilation. The `node-addon-api` module, which is not part of Node.js, preserves the benefits of the Node-API as it consists only of inline code that depends only on the stable API provided by Node-API. As such, modules built against one version of Node.js using node-addon-api should run without having to be rebuilt with newer versions of Node.js. It is important to remember that *other* Node.js interfaces such as `libuv` (included in a project via `#include <uv.h>`) are not ABI-stable across Node.js major versions. Thus, an addon must use Node-API and/or `node-addon-api` exclusively and build against a version of Node.js that includes an implementation of Node-API (meaning an active LTS version of Node.js) in order to benefit from ABI stability across Node.js major versions. Node.js provides an [ABI stability guide][] containing a detailed explanation of ABI stability in general, and the Node-API ABI stability guarantee in particular. As new APIs are added to Node-API, node-addon-api must be updated to provide wrappers for those new APIs. For this reason node-addon-api provides methods that allow callers to obtain the underlying Node-API handles so direct calls to Node-API and the use of the objects/methods provided by node-addon-api can be used together. For example, in order to be able to use an API for which the node-addon-api does not yet provide a wrapper. APIs exposed by node-addon-api are generally used to create and manipulate JavaScript values. Concepts and operations generally map to ideas specified in the **ECMA262 Language Specification**. The [Node-API Resource](https://nodejs.github.io/node-addon-examples/) offers an excellent orientation and tips for developers just getting started with Node-API and node-addon-api. - **[Setup](#setup)** - **[API Documentation](#api)** - **[Examples](#examples)** - **[Tests](#tests)** - **[More resource and info about native Addons](#resources)** - **[Badges](#badges)** - **[Code of Conduct](CODE_OF_CONDUCT.md)** - **[Contributors](#contributors)** - **[License](#license)** ## **Current version: 3.2.1** (See [CHANGELOG.md](CHANGELOG.md) for complete Changelog) [![NPM](https://nodei.co/npm/node-addon-api.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-addon-api/) [![NPM](https://nodei.co/npm-dl/node-addon-api.png?months=6&height=1)](https://nodei.co/npm/node-addon-api/) <a name="setup"></a> node-addon-api is based on [Node-API](https://nodejs.org/api/n-api.html) and supports using different Node-API versions. This allows addons built with it to run with Node.js versions which support the targeted Node-API version. **However** the node-addon-api support model is to support only the active LTS Node.js versions. This means that every year there will be a new major which drops support for the Node.js LTS version which has gone out of service. The oldest Node.js version supported by the current version of node-addon-api is Node.js 10.x. ## Setup - [Installation and usage](doc/setup.md) - [node-gyp](doc/node-gyp.md) - [cmake-js](doc/cmake-js.md) - [Conversion tool](doc/conversion-tool.md) - [Checker tool](doc/checker-tool.md) - [Generator](doc/generator.md) - [Prebuild tools](doc/prebuild_tools.md) <a name="api"></a> ### **API Documentation** The following is the documentation for node-addon-api. - [Full Class Hierarchy](doc/hierarchy.md) - [Addon Structure](doc/addon.md) - Data Types: - [Env](doc/env.md) - [CallbackInfo](doc/callbackinfo.md) - [Reference](doc/reference.md) - [Value](doc/value.md) - [Name](doc/name.md) - [Symbol](doc/symbol.md) - [String](doc/string.md) - [Number](doc/number.md) - [Date](doc/date.md) - [BigInt](doc/bigint.md) - [Boolean](doc/boolean.md) - [External](doc/external.md) - [Object](doc/object.md) - [Array](doc/array.md) - [ObjectReference](doc/object_reference.md) - [PropertyDescriptor](doc/property_descriptor.md) - [Function](doc/function.md) - [FunctionReference](doc/function_reference.md) - [ObjectWrap](doc/object_wrap.md) - [ClassPropertyDescriptor](doc/class_property_descriptor.md) - [Buffer](doc/buffer.md) - [ArrayBuffer](doc/array_buffer.md) - [TypedArray](doc/typed_array.md) - [TypedArrayOf](doc/typed_array_of.md) - [DataView](doc/dataview.md) - [Error Handling](doc/error_handling.md) - [Error](doc/error.md) - [TypeError](doc/type_error.md) - [RangeError](doc/range_error.md) - [Object Lifetime Management](doc/object_lifetime_management.md) - [HandleScope](doc/handle_scope.md) - [EscapableHandleScope](doc/escapable_handle_scope.md) - [Memory Management](doc/memory_management.md) - [Async Operations](doc/async_operations.md) - [AsyncWorker](doc/async_worker.md) - [AsyncContext](doc/async_context.md) - [AsyncWorker Variants](doc/async_worker_variants.md) - [Thread-safe Functions](doc/threadsafe.md) - [ThreadSafeFunction](doc/threadsafe_function.md) - [TypedThreadSafeFunction](doc/typed_threadsafe_function.md) - [Promises](doc/promises.md) - [Version management](doc/version_management.md) <a name="examples"></a> ### **Examples** Are you new to **node-addon-api**? Take a look at our **[examples](https://github.com/nodejs/node-addon-examples)** - **[Hello World](https://github.com/nodejs/node-addon-examples/tree/HEAD/1_hello_world/node-addon-api)** - **[Pass arguments to a function](https://github.com/nodejs/node-addon-examples/tree/HEAD/2_function_arguments/node-addon-api)** - **[Callbacks](https://github.com/nodejs/node-addon-examples/tree/HEAD/3_callbacks/node-addon-api)** - **[Object factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/4_object_factory/node-addon-api)** - **[Function factory](https://github.com/nodejs/node-addon-examples/tree/HEAD/5_function_factory/node-addon-api)** - **[Wrapping C++ Object](https://github.com/nodejs/node-addon-examples/tree/HEAD/6_object_wrap/node-addon-api)** - **[Factory of wrapped object](https://github.com/nodejs/node-addon-examples/tree/HEAD/7_factory_wrap/node-addon-api)** - **[Passing wrapped object around](https://github.com/nodejs/node-addon-examples/tree/HEAD/8_passing_wrapped/node-addon-api)** <a name="tests"></a> ### **Tests** To run the **node-addon-api** tests do: ``` npm install npm test ``` To avoid testing the deprecated portions of the API run ``` npm install npm test --disable-deprecated ``` To run the tests targeting a specific version of Node-API run ``` npm install export NAPI_VERSION=X npm test --NAPI_VERSION=X ``` where X is the version of Node-API you want to target. ### **Debug** To run the **node-addon-api** tests with `--debug` option: ``` npm run-script dev ``` If you want faster build, you might use the following option: ``` npm run-script dev:incremental ``` Take a look and get inspired by our **[test suite](https://github.com/nodejs/node-addon-api/tree/HEAD/test)** ### **Benchmarks** You can run the available benchmarks using the following command: ``` npm run-script benchmark ``` See [benchmark/README.md](benchmark/README.md) for more details about running and adding benchmarks. <a name="resources"></a> ### **More resource and info about native Addons** - **[C++ Addons](https://nodejs.org/dist/latest/docs/api/addons.html)** - **[Node-API](https://nodejs.org/dist/latest/docs/api/n-api.html)** - **[Node-API - Next Generation Node API for Native Modules](https://youtu.be/-Oniup60Afs)** - **[How We Migrated Realm JavaScript From NAN to Node-API](https://developer.mongodb.com/article/realm-javascript-nan-to-n-api)** As node-addon-api's core mission is to expose the plain C Node-API as C++ wrappers, tools that facilitate n-api/node-addon-api providing more convenient patterns on developing a Node.js add-ons with n-api/node-addon-api can be published to NPM as standalone packages. It is also recommended to tag such packages with `node-addon-api` to provide more visibility to the community. Quick links to NPM searches: [keywords:node-addon-api](https://www.npmjs.com/search?q=keywords%3Anode-addon-api). <a name="other-bindings"></a> ### **Other bindings** - **[napi-rs](https://napi.rs)** - (`Rust`) <a name="badges"></a> ### **Badges** The use of badges is recommended to indicate the minimum version of Node-API required for the module. This helps to determine which Node.js major versions are supported. Addon maintainers can consult the [Node-API support matrix][] to determine which Node.js versions provide a given Node-API version. The following badges are available: ![Node-API v1 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v1%20Badge.svg) ![Node-API v2 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v2%20Badge.svg) ![Node-API v3 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v3%20Badge.svg) ![Node-API v4 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v4%20Badge.svg) ![Node-API v5 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v5%20Badge.svg) ![Node-API v6 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v6%20Badge.svg) ![Node-API v7 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v7%20Badge.svg) ![Node-API v8 Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20v8%20Badge.svg) ![Node-API Experimental Version Badge](https://github.com/nodejs/abi-stable-node/blob/doc/assets/Node-API%20Experimental%20Version%20Badge.svg) ## **Contributing** We love contributions from the community to **node-addon-api**! See [CONTRIBUTING.md](CONTRIBUTING.md) for more details on our philosophy around extending this module. <a name="contributors"></a> ## Team members ### Active | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Anna Henningsen | [addaleax](https://github.com/addaleax) | | Chengzhong Wu | [legendecas](https://github.com/legendecas) | | Gabriel Schulhof | [gabrielschulhof](https://github.com/gabrielschulhof) | | Jim Schlight | [jschlight](https://github.com/jschlight) | | Michael Dawson | [mhdawson](https://github.com/mhdawson) | | Kevin Eady | [KevinEady](https://github.com/KevinEady) | Nicola Del Gobbo | [NickNaso](https://github.com/NickNaso) | ### Emeritus | Name | GitHub Link | | ------------------- | ----------------------------------------------------- | | Arunesh Chandra | [aruneshchandra](https://github.com/aruneshchandra) | | Benjamin Byholm | [kkoopa](https://github.com/kkoopa) | | Jason Ginchereau | [jasongin](https://github.com/jasongin) | | Hitesh Kanwathirtha | [digitalinfinity](https://github.com/digitalinfinity) | | Sampson Gao | [sampsongao](https://github.com/sampsongao) | | Taylor Woll | [boingoing](https://github.com/boingoing) | <a name="license"></a> Licensed under [MIT](./LICENSE.md) [ABI stability guide]: https://nodejs.org/en/docs/guides/abi-stability/ [Node-API support matrix]: https://nodejs.org/dist/latest/docs/api/n-api.html#n_api_n_api_version_matrix # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # Can I cache this? [![Build Status](https://travis-ci.org/kornelski/http-cache-semantics.svg?branch=master)](https://travis-ci.org/kornelski/http-cache-semantics) `CachePolicy` tells when responses can be reused from a cache, taking into account [HTTP RFC 7234](http://httpwg.org/specs/rfc7234.html) rules for user agents and shared caches. It also implements [RFC 5861](https://tools.ietf.org/html/rfc5861), implementing `stale-if-error` and `stale-while-revalidate`. It's aware of many tricky details such as the `Vary` header, proxy revalidation, and authenticated responses. ## Usage Cacheability of an HTTP response depends on how it was requested, so both `request` and `response` are required to create the policy. ```js const policy = new CachePolicy(request, response, options); if (!policy.storable()) { // throw the response away, it's not usable at all return; } // Cache the data AND the policy object in your cache // (this is pseudocode, roll your own cache (lru-cache package works)) letsPretendThisIsSomeCache.set( request.url, { policy, response }, policy.timeToLive() ); ``` ```js // And later, when you receive a new request: const { policy, response } = letsPretendThisIsSomeCache.get(newRequest.url); // It's not enough that it exists in the cache, it has to match the new request, too: if (policy && policy.satisfiesWithoutRevalidation(newRequest)) { // OK, the previous response can be used to respond to the `newRequest`. // Response headers have to be updated, e.g. to add Age and remove uncacheable headers. response.headers = policy.responseHeaders(); return response; } ``` It may be surprising, but it's not enough for an HTTP response to be [fresh](#yo-fresh) to satisfy a request. It may need to match request headers specified in `Vary`. Even a matching fresh response may still not be usable if the new request restricted cacheability, etc. The key method is `satisfiesWithoutRevalidation(newRequest)`, which checks whether the `newRequest` is compatible with the original request and whether all caching conditions are met. ### Constructor options Request and response must have a `headers` property with all header names in lower case. `url`, `status` and `method` are optional (defaults are any URL, status `200`, and `GET` method). ```js const request = { url: '/', method: 'GET', headers: { accept: '*/*', }, }; const response = { status: 200, headers: { 'cache-control': 'public, max-age=7234', }, }; const options = { shared: true, cacheHeuristic: 0.1, immutableMinTimeToLive: 24 * 3600 * 1000, // 24h ignoreCargoCult: false, }; ``` If `options.shared` is `true` (default), then the response is evaluated from a perspective of a shared cache (i.e. `private` is not cacheable and `s-maxage` is respected). If `options.shared` is `false`, then the response is evaluated from a perspective of a single-user cache (i.e. `private` is cacheable and `s-maxage` is ignored). `shared: true` is recommended for HTTP clients. `options.cacheHeuristic` is a fraction of response's age that is used as a fallback cache duration. The default is 0.1 (10%), e.g. if a file hasn't been modified for 100 days, it'll be cached for 100\*0.1 = 10 days. `options.immutableMinTimeToLive` is a number of milliseconds to assume as the default time to cache responses with `Cache-Control: immutable`. Note that [per RFC](http://httpwg.org/http-extensions/immutable.html) these can become stale, so `max-age` still overrides the default. If `options.ignoreCargoCult` is true, common anti-cache directives will be completely ignored if the non-standard `pre-check` and `post-check` directives are present. These two useless directives are most commonly found in bad StackOverflow answers and PHP's "session limiter" defaults. ### `storable()` Returns `true` if the response can be stored in a cache. If it's `false` then you MUST NOT store either the request or the response. ### `satisfiesWithoutRevalidation(newRequest)` This is the most important method. Use this method to check whether the cached response is still fresh in the context of the new request. If it returns `true`, then the given `request` matches the original response this cache policy has been created with, and the response can be reused without contacting the server. Note that the old response can't be returned without being updated, see `responseHeaders()`. If it returns `false`, then the response may not be matching at all (e.g. it's for a different URL or method), or may require to be refreshed first (see `revalidationHeaders()`). ### `responseHeaders()` Returns updated, filtered set of response headers to return to clients receiving the cached response. This function is necessary, because proxies MUST always remove hop-by-hop headers (such as `TE` and `Connection`) and update response's `Age` to avoid doubling cache time. ```js cachedResponse.headers = cachePolicy.responseHeaders(cachedResponse); ``` ### `timeToLive()` Returns approximate time in _milliseconds_ until the response becomes stale (i.e. not fresh). After that time (when `timeToLive() <= 0`) the response might not be usable without revalidation. However, there are exceptions, e.g. a client can explicitly allow stale responses, so always check with `satisfiesWithoutRevalidation()`. `stale-if-error` and `stale-while-revalidate` extend the time to live of the cache, that can still be used if stale. ### `toObject()`/`fromObject(json)` Chances are you'll want to store the `CachePolicy` object along with the cached response. `obj = policy.toObject()` gives a plain JSON-serializable object. `policy = CachePolicy.fromObject(obj)` creates an instance from it. ### Refreshing stale cache (revalidation) When a cached response has expired, it can be made fresh again by making a request to the origin server. The server may respond with status 304 (Not Modified) without sending the response body again, saving bandwidth. The following methods help perform the update efficiently and correctly. #### `revalidationHeaders(newRequest)` Returns updated, filtered set of request headers to send to the origin server to check if the cached response can be reused. These headers allow the origin server to return status 304 indicating the response is still fresh. All headers unrelated to caching are passed through as-is. Use this method when updating cache from the origin server. ```js updateRequest.headers = cachePolicy.revalidationHeaders(updateRequest); ``` #### `revalidatedPolicy(revalidationRequest, revalidationResponse)` Use this method to update the cache after receiving a new response from the origin server. It returns an object with two keys: - `policy` — A new `CachePolicy` with HTTP headers updated from `revalidationResponse`. You can always replace the old cached `CachePolicy` with the new one. - `modified` — Boolean indicating whether the response body has changed. - If `false`, then a valid 304 Not Modified response has been received, and you can reuse the old cached response body. This is also affected by `stale-if-error`. - If `true`, you should use new response's body (if present), or make another request to the origin server without any conditional headers (i.e. don't use `revalidationHeaders()` this time) to get the new resource. ```js // When serving requests from cache: const { oldPolicy, oldResponse } = letsPretendThisIsSomeCache.get( newRequest.url ); if (!oldPolicy.satisfiesWithoutRevalidation(newRequest)) { // Change the request to ask the origin server if the cached response can be used newRequest.headers = oldPolicy.revalidationHeaders(newRequest); // Send request to the origin server. The server may respond with status 304 const newResponse = await makeRequest(newRequest); // Create updated policy and combined response from the old and new data const { policy, modified } = oldPolicy.revalidatedPolicy( newRequest, newResponse ); const response = modified ? newResponse : oldResponse; // Update the cache with the newer/fresher response letsPretendThisIsSomeCache.set( newRequest.url, { policy, response }, policy.timeToLive() ); // And proceed returning cached response as usual response.headers = policy.responseHeaders(); return response; } ``` # Yo, FRESH ![satisfiesWithoutRevalidation](fresh.jpg) ## Used by - [ImageOptim API](https://imageoptim.com/api), [make-fetch-happen](https://github.com/zkat/make-fetch-happen), [cacheable-request](https://www.npmjs.com/package/cacheable-request) ([got](https://www.npmjs.com/package/got)), [npm/registry-fetch](https://github.com/npm/registry-fetch), [etc.](https://github.com/kornelski/http-cache-semantics/network/dependents) ## Implemented - `Cache-Control` response header with all the quirks. - `Expires` with check for bad clocks. - `Pragma` response header. - `Age` response header. - `Vary` response header. - Default cacheability of statuses and methods. - Requests for stale data. - Filtering of hop-by-hop headers. - Basic revalidation request - `stale-if-error` ## Unimplemented - Merging of range requests, `If-Range` (but correctly supports them as non-cacheable) - Revalidation of multiple representations ### Trusting server `Date` Per the RFC, the cache should take into account the time between server-supplied `Date` and the time it received the response. The RFC-mandated behavior creates two problems: * Servers with incorrectly set timezone may add several hours to cache age (or more, if the clock is completely wrong). * Even reasonably correct clocks may be off by a couple of seconds, breaking `max-age=1` trick (which is useful for reverse proxies on high-traffic servers). Previous versions of this library had an option to ignore the server date if it was "too inaccurate". To support the `max-age=1` trick the library also has to ignore dates that pretty accurate. There's no point of having an option to trust dates that are only a bit inaccurate, so this library won't trust any server dates. `max-age` will be interpreted from the time the response has been received, not from when it has been sent. This will affect only [RFC 1149 networks](https://tools.ietf.org/html/rfc1149). # napi-build-utils [![npm](https://img.shields.io/npm/v/napi-build-utils.svg)](https://www.npmjs.com/package/napi-build-utils) ![Node version](https://img.shields.io/node/v/prebuild.svg) [![Build Status](https://travis-ci.org/inspiredware/napi-build-utils.svg?branch=master)](https://travis-ci.org/inspiredware/napi-build-utils) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) A set of utilities to assist developers of tools that build [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) native add-ons. ## Background This module is targeted to developers creating tools that build N-API native add-ons. It implements a set of functions that aid in determining the N-API version supported by the currently running Node instance and the set of N-API versions against which the N-API native add-on is designed to be built. Other functions determine whether a particular N-API version can be built and can issue console warnings for unsupported N-API versions. Unlike the modules this code is designed to facilitate building, this module is written entirely in JavaScript. ## Quick start ```bash $ npm install napi-build-utils ``` The module exports a set of functions documented [here](./index.md). For example: ```javascript var napiBuildUtils = require('napi-build-utils'); var napiVersion = napiBuildUtils.getNapiVersion(); // N-API version supported by Node, or undefined. ``` ## Declaring supported N-API versions Native modules that are designed to work with [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) must explicitly declare the N-API version(s) against which they are coded to build. This is accomplished by including a `binary.napi_versions` property in the module's `package.json` file. For example: ```json "binary": { "napi_versions": [2,3] } ``` In the absence of a need to compile against a specific N-API version, the value `3` is a good choice as this is the N-API version that was supported when N-API left experimental status. Modules that are built against a specific N-API version will continue to operate indefinitely, even as later versions of N-API are introduced. ## Support If you run into problems or limitations, please file an issue and we'll take a look. Pull requests are also welcome. # signal-exit [![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) [![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) [![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the process to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. # Polyfill for `Object.setPrototypeOf` [![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. ## Usage: ``` $ npm install --save setprototypeof ``` ```javascript var setPrototypeOf = require('setprototypeof') var obj = {} setPrototypeOf(obj, { foo: function () { return 'bar' } }) obj.foo() // bar ``` TypeScript is also supported: ```typescript import setPrototypeOf from 'setprototypeof' ``` # pretty-format Stringify any JavaScript value. - Serialize built-in JavaScript types. - Serialize application-specific data types with built-in or user-defined plugins. ## Installation ```sh $ yarn add pretty-format ``` ## Usage ```js const {format: prettyFormat} = require('pretty-format'); // CommonJS ``` ```js import {format as prettyFormat} from 'pretty-format'; // ES2015 modules ``` ```js const val = {object: {}}; val.circularReference = val; val[Symbol('foo')] = 'foo'; val.map = new Map([['prop', 'value']]); val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); /* Object { "array": Array [ -0, Infinity, NaN, ], "circularReference": [Circular], "map": Map { "prop" => "value", }, "object": Object {}, Symbol(foo): "foo", } */ ``` ## Usage with options ```js function onClick() {} console.log(prettyFormat(onClick)); /* [Function onClick] */ const options = { printFunctionName: false, }; console.log(prettyFormat(onClick, options)); /* [Function] */ ``` <!-- prettier-ignore --> | key | type | default | description | | :-------------------- | :-------- | :--------- | :------------------------------------------------------ | | `callToJSON` | `boolean` | `true` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function`| `undefined`| compare function used when sorting object keys | | `escapeRegex` | `boolean` | `false` | escape special characters in regular expressions | | `escapeString` | `boolean` | `true` | escape special characters in strings | | `highlight` | `boolean` | `false` | highlight syntax with colors in terminal (some plugins) | | `indent` | `number` | `2` | spaces in each level of indentation | | `maxDepth` | `number` | `Infinity` | levels to print in arrays, objects, elements, and so on | | `min` | `boolean` | `false` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | `[]` | plugins to serialize application-specific data types | | `printBasicPrototype` | `boolean` | `false` | print the prototype for plain objects and arrays | | `printFunctionName` | `boolean` | `true` | include or omit the name of a function | | `theme` | `object` | | colors to highlight syntax in terminal | Property values of `theme` are from [ansi-styles colors](https://github.com/chalk/ansi-styles#colors) ```js const DEFAULT_THEME = { comment: 'gray', content: 'reset', prop: 'yellow', tag: 'cyan', value: 'green', }; ``` ## Usage with plugins The `pretty-format` package provides some built-in plugins, including: - `ReactElement` for elements from `react` - `ReactTestComponent` for test objects from `react-test-renderer` ```js // CommonJS const React = require('react'); const renderer = require('react-test-renderer'); const {format: prettyFormat, plugins} = require('pretty-format'); const {ReactElement, ReactTestComponent} = plugins; ``` ```js // ES2015 modules and destructuring assignment import React from 'react'; import renderer from 'react-test-renderer'; import {plugins, format as prettyFormat} from 'pretty-format'; const {ReactElement, ReactTestComponent} = plugins; ``` ```js const onClick = () => {}; const element = React.createElement('button', {onClick}, 'Hello World'); const formatted1 = prettyFormat(element, { plugins: [ReactElement], printFunctionName: false, }); const formatted2 = prettyFormat(renderer.create(element).toJSON(), { plugins: [ReactTestComponent], printFunctionName: false, }); /* <button onClick=[Function] > Hello World </button> */ ``` ## Usage in Jest For snapshot tests, Jest uses `pretty-format` with options that include some of its built-in plugins. For this purpose, plugins are also known as **snapshot serializers**. To serialize application-specific data types, you can add modules to `devDependencies` of a project, and then: In an **individual** test file, you can add a module as follows. It precedes any modules from Jest configuration. ```js import serializer from 'my-serializer-module'; expect.addSnapshotSerializer(serializer); // tests which have `expect(value).toMatchSnapshot()` assertions ``` For **all** test files, you can specify modules in Jest configuration. They precede built-in plugins for React, HTML, and Immutable.js data types. For example, in a `package.json` file: ```json { "jest": { "snapshotSerializers": ["my-serializer-module"] } } ``` ## Writing plugins A plugin is a JavaScript object. If `options` has a `plugins` array: for the first plugin whose `test(val)` method returns a truthy value, then `prettyFormat(val, options)` returns the result from either: - `serialize(val, …)` method of the **improved** interface (available in **version 21** or later) - `print(val, …)` method of the **original** interface (if plugin does not have `serialize` method) ### test Write `test` so it can receive `val` argument of any type. To serialize **objects** which have certain properties, then a guarded expression like `val != null && …` or more concise `val && …` prevents the following errors: - `TypeError: Cannot read property 'whatever' of null` - `TypeError: Cannot read property 'whatever' of undefined` For example, `test` method of built-in `ReactElement` plugin: ```js const elementSymbol = Symbol.for('react.element'); const test = val => val && val.$$typeof === elementSymbol; ``` Pay attention to efficiency in `test` because `pretty-format` calls it often. ### serialize The **improved** interface is available in **version 21** or later. Write `serialize` to return a string, given the arguments: - `val` which “passed the test” - unchanging `config` object: derived from `options` - current `indentation` string: concatenate to `indent` from `config` - current `depth` number: compare to `maxDepth` from `config` - current `refs` array: find circular references in objects - `printer` callback function: serialize children ### config <!-- prettier-ignore --> | key | type | description | | :------------------ | :-------- | :------------------------------------------------------ | | `callToJSON` | `boolean` | call `toJSON` method (if it exists) on objects | | `compareKeys` | `function`| compare function used when sorting object keys | | `colors` | `Object` | escape codes for colors to highlight syntax | | `escapeRegex` | `boolean` | escape special characters in regular expressions | | `escapeString` | `boolean` | escape special characters in strings | | `indent` | `string` | spaces in each level of indentation | | `maxDepth` | `number` | levels to print in arrays, objects, elements, and so on | | `min` | `boolean` | minimize added space: no indentation nor line breaks | | `plugins` | `array` | plugins to serialize application-specific data types | | `printFunctionName` | `boolean` | include or omit the name of a function | | `spacingInner` | `strong` | spacing to separate items in a list | | `spacingOuter` | `strong` | spacing to enclose a list of items | Each property of `colors` in `config` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) Some properties in `config` are derived from `min` in `options`: - `spacingInner` and `spacingOuter` are **newline** if `min` is `false` - `spacingInner` is **space** and `spacingOuter` is **empty string** if `min` is `true` ### Example of serialize and test This plugin is a pattern you can apply to serialize composite data types. Side note: `pretty-format` does not need a plugin to serialize arrays. ```js // We reused more code when we factored out a function for child items // that is independent of depth, name, and enclosing punctuation (see below). const SEPARATOR = ','; function serializeItems(items, config, indentation, depth, refs, printer) { if (items.length === 0) { return ''; } const indentationItems = indentation + config.indent; return ( config.spacingOuter + items .map( item => indentationItems + printer(item, config, indentationItems, depth, refs), // callback ) .join(SEPARATOR + config.spacingInner) + (config.min ? '' : SEPARATOR) + // following the last item config.spacingOuter + indentation ); } const plugin = { test(val) { return Array.isArray(val); }, serialize(array, config, indentation, depth, refs, printer) { const name = array.constructor.name; return ++depth > config.maxDepth ? '[' + name + ']' : (config.min ? '' : name + ' ') + '[' + serializeItems(array, config, indentation, depth, refs, printer) + ']'; }, }; ``` ```js const val = { filter: 'completed', items: [ { text: 'Write test', completed: true, }, { text: 'Write serialize', completed: true, }, ], }; ``` ```js console.log( prettyFormat(val, { plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { indent: 4, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": Array [ Object { "completed": true, "text": "Write test", }, Object { "completed": true, "text": "Write serialize", }, ], } */ ``` ```js console.log( prettyFormat(val, { maxDepth: 1, plugins: [plugin], }), ); /* Object { "filter": "completed", "items": [Array], } */ ``` ```js console.log( prettyFormat(val, { min: true, plugins: [plugin], }), ); /* {"filter": "completed", "items": [{"completed": true, "text": "Write test"}, {"completed": true, "text": "Write serialize"}]} */ ``` ### print The **original** interface is adequate for plugins: - that **do not** depend on options other than `highlight` or `min` - that **do not** depend on `depth` or `refs` in recursive traversal, and - if values either - do **not** require indentation, or - do **not** occur as children of JavaScript data structures (for example, array) Write `print` to return a string, given the arguments: - `val` which “passed the test” - current `printer(valChild)` callback function: serialize children - current `indenter(lines)` callback function: indent lines at the next level - unchanging `config` object: derived from `options` - unchanging `colors` object: derived from `options` The 3 properties of `config` are `min` in `options` and: - `spacing` and `edgeSpacing` are **newline** if `min` is `false` - `spacing` is **space** and `edgeSpacing` is **empty string** if `min` is `true` Each property of `colors` corresponds to a property of `theme` in `options`: - the key is the same (for example, `tag`) - the value in `colors` is a object with `open` and `close` properties whose values are escape codes from [ansi-styles](https://github.com/chalk/ansi-styles) for the color value in `theme` (for example, `'cyan'`) ### Example of print and test This plugin prints functions with the **number of named arguments** excluding rest argument. ```js const plugin = { print(val) { return `[Function ${val.name || 'anonymous'} ${val.length}]`; }, test(val) { return typeof val === 'function'; }, }; ``` ```js const val = { onClick(event) {}, render() {}, }; prettyFormat(val, { plugins: [plugin], }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val); /* Object { "onClick": [Function onClick], "render": [Function render], } */ ``` This plugin **ignores** the `printFunctionName` option. That limitation of the original `print` interface is a reason to use the improved `serialize` interface, described above. ```js prettyFormat(val, { plugins: [pluginOld], printFunctionName: false, }); /* Object { "onClick": [Function onClick 1], "render": [Function render 0], } */ prettyFormat(val, { printFunctionName: false, }); /* Object { "onClick": [Function], "render": [Function], } */ ``` # `react-is` This package allows you to test arbitrary values and see if they're a particular React element type. ## Installation ```sh # Yarn yarn add react-is # NPM npm install react-is ``` ## Usage ### Determining if a Component is Valid ```js import React from "react"; import * as ReactIs from "react-is"; class ClassComponent extends React.Component { render() { return React.createElement("div"); } } const FunctionComponent = () => React.createElement("div"); const ForwardRefComponent = React.forwardRef((props, ref) => React.createElement(Component, { forwardedRef: ref, ...props }) ); const Context = React.createContext(false); ReactIs.isValidElementType("div"); // true ReactIs.isValidElementType(ClassComponent); // true ReactIs.isValidElementType(FunctionComponent); // true ReactIs.isValidElementType(ForwardRefComponent); // true ReactIs.isValidElementType(Context.Provider); // true ReactIs.isValidElementType(Context.Consumer); // true ReactIs.isValidElementType(React.createFactory("div")); // true ``` ### Determining an Element's Type #### Context ```js import React from "react"; import * as ReactIs from 'react-is'; const ThemeContext = React.createContext("blue"); ReactIs.isContextConsumer(<ThemeContext.Consumer />); // true ReactIs.isContextProvider(<ThemeContext.Provider />); // true ReactIs.typeOf(<ThemeContext.Provider />) === ReactIs.ContextProvider; // true ReactIs.typeOf(<ThemeContext.Consumer />) === ReactIs.ContextConsumer; // true ``` #### Element ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isElement(<div />); // true ReactIs.typeOf(<div />) === ReactIs.Element; // true ``` #### Fragment ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isFragment(<></>); // true ReactIs.typeOf(<></>) === ReactIs.Fragment; // true ``` #### Portal ```js import React from "react"; import ReactDOM from "react-dom"; import * as ReactIs from 'react-is'; const div = document.createElement("div"); const portal = ReactDOM.createPortal(<div />, div); ReactIs.isPortal(portal); // true ReactIs.typeOf(portal) === ReactIs.Portal; // true ``` #### StrictMode ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isStrictMode(<React.StrictMode />); // true ReactIs.typeOf(<React.StrictMode />) === ReactIs.StrictMode; // true ``` # is-ci Returns `true` if the current environment is a Continuous Integration server. Please [open an issue](https://github.com/watson/is-ci/issues) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/is-ci.svg)](https://www.npmjs.com/package/is-ci) [![Build status](https://travis-ci.org/watson/is-ci.svg?branch=master)](https://travis-ci.org/watson/is-ci) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install is-ci --save ``` ## Programmatic Usage ```js const isCI = require('is-ci') if (isCI) { console.log('The code is running on a CI server') } ``` ## CLI Usage For CLI usage you need to have the `is-ci` executable in your `PATH`. There's a few ways to do that: - Either install the module globally using `npm install is-ci -g` - Or add the module as a dependency to your app in which case it can be used inside your package.json scripts as is - Or provide the full path to the executable, e.g. `./node_modules/.bin/is-ci` ```bash is-ci && echo "This is a CI server" ``` ## Supported CI tools Refer to [ci-info](https://github.com/watson/ci-info#supported-ci-tools) docs for all supported CI's ## License [MIT](LICENSE) # Borsh JS [![Project license](https://img.shields.io/badge/license-Apache2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) [![Project license](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/licenses/MIT) [![Discord](https://img.shields.io/discord/490367152054992913?label=discord)](https://discord.gg/Vyp7ETM) [![Travis status](https://travis-ci.com/near/borsh.svg?branch=master)](https://travis-ci.com/near/borsh-js) [![NPM version](https://img.shields.io/npm/v/borsh.svg?style=flat-square)](https://npmjs.com/borsh) [![Size on NPM](https://img.shields.io/bundlephobia/minzip/borsh.svg?style=flat-square)](https://npmjs.com/borsh) **Borsh JS** is an implementation of the [Borsh] binary serialization format for JavaScript and TypeScript projects. Borsh stands for _Binary Object Representation Serializer for Hashing_. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification. ## Examples ### Serializing an object ```javascript const value = new Test({ x: 255, y: 20, z: '123', q: [1, 2, 3] }); const schema = new Map([[Test, { kind: 'struct', fields: [['x', 'u8'], ['y', 'u64'], ['z', 'string'], ['q', [3]]] }]]); const buffer = borsh.serialize(schema, value); ``` ### Deserializing an object ```javascript const newValue = borsh.deserialize(schema, Test, buffer); ``` ## Type Mappings | Borsh | TypeScript | |-----------------------|----------------| | `u8` integer | `number` | | `u16` integer | `number` | | `u32` integer | `number` | | `u64` integer | `BN` | | `u128` integer | `BN` | | `u256` integer | `BN` | | `u512` integer | `BN` | | `f32` float | N/A | | `f64` float | N/A | | fixed-size byte array | `Uint8Array` | | UTF-8 string | `string` | | option | `null` or type | | map | N/A | | set | N/A | | structs | `any` | ## Contributing Install dependencies: ```bash yarn install ``` Continuously build with: ```bash yarn dev ``` Run tests: ```bash yarn test ``` Run linter ```bash yarn lint ``` ## Publish Prepare `dist` version by running: ```bash yarn build ``` When publishing to npm use [np](https://github.com/sindresorhus/np). # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE-MIT](LICENSE-MIT.txt) and [LICENSE-APACHE](LICENSE-APACHE) for details. [Borsh]: https://borsh.io # ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg [travis-url]: https://travis-ci.org/feross/ieee754 [npm-image]: https://img.shields.io/npm/v/ieee754.svg [npm-url]: https://npmjs.org/package/ieee754 [downloads-image]: https://img.shields.io/npm/dm/ieee754.svg [downloads-url]: https://npmjs.org/package/ieee754 [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg [saucelabs-url]: https://saucelabs.com/u/ieee754 ### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. ## install ``` npm install ieee754 ``` ## methods `var ieee754 = require('ieee754')` The `ieee754` object has the following functions: ``` ieee754.read = function (buffer, offset, isLE, mLen, nBytes) ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) ``` The arguments mean the following: - buffer = the buffer - offset = offset into the buffer - value = value to set (only for `write`) - isLe = is little endian? - mLen = mantissa length - nBytes = number of bytes ## what is ieee754? The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). ## license BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. # json-parse-better-errors [![npm version](https://img.shields.io/npm/v/json-parse-better-errors.svg)](https://npm.im/json-parse-better-errors) [![license](https://img.shields.io/npm/l/json-parse-better-errors.svg)](https://npm.im/json-parse-better-errors) [![Travis](https://img.shields.io/travis/zkat/json-parse-better-errors.svg)](https://travis-ci.org/zkat/json-parse-better-errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/json-parse-better-errors?svg=true)](https://ci.appveyor.com/project/zkat/json-parse-better-errors) [![Coverage Status](https://coveralls.io/repos/github/zkat/json-parse-better-errors/badge.svg?branch=latest)](https://coveralls.io/github/zkat/json-parse-better-errors?branch=latest) [`json-parse-better-errors`](https://github.com/zkat/json-parse-better-errors) is a Node.js library for getting nicer errors out of `JSON.parse()`, including context and position of the parse errors. ## Install `$ npm install --save json-parse-better-errors` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * [`parse`](#parse) ### Example ```javascript const parseJson = require('json-parse-better-errors') parseJson('"foo"') parseJson('garbage') // more useful error message ``` ### Features * Like JSON.parse, but the errors are better. ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### <a name="parse"></a> `> parse(txt, ?reviver, ?context=20)` Works just like `JSON.parse`, but will include a bit more information when an error happens. semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` You can also just load the module for the function that you care about, if you'd like to minimize your footprint. ```js // load the whole API at once in a single object const semver = require('semver') // or just load the bits you need // all of them listed here, just pick and choose what you want // classes const SemVer = require('semver/classes/semver') const Comparator = require('semver/classes/comparator') const Range = require('semver/classes/range') // functions for working with versions const semverParse = require('semver/functions/parse') const semverValid = require('semver/functions/valid') const semverClean = require('semver/functions/clean') const semverInc = require('semver/functions/inc') const semverDiff = require('semver/functions/diff') const semverMajor = require('semver/functions/major') const semverMinor = require('semver/functions/minor') const semverPatch = require('semver/functions/patch') const semverPrerelease = require('semver/functions/prerelease') const semverCompare = require('semver/functions/compare') const semverRcompare = require('semver/functions/rcompare') const semverCompareLoose = require('semver/functions/compare-loose') const semverCompareBuild = require('semver/functions/compare-build') const semverSort = require('semver/functions/sort') const semverRsort = require('semver/functions/rsort') // low-level comparators between versions const semverGt = require('semver/functions/gt') const semverLt = require('semver/functions/lt') const semverEq = require('semver/functions/eq') const semverNeq = require('semver/functions/neq') const semverGte = require('semver/functions/gte') const semverLte = require('semver/functions/lte') const semverCmp = require('semver/functions/cmp') const semverCoerce = require('semver/functions/coerce') // working with ranges const semverSatisfies = require('semver/functions/satisfies') const semverMaxSatisfying = require('semver/ranges/max-satisfying') const semverMinSatisfying = require('semver/ranges/min-satisfying') const semverToComparators = require('semver/ranges/to-comparators') const semverMinVersion = require('semver/ranges/min-version') const semverValidRange = require('semver/ranges/valid') const semverOutside = require('semver/ranges/outside') const semverGtr = require('semver/ranges/gtr') const semverLtr = require('semver/ranges/ltr') const semverIntersects = require('semver/ranges/intersects') const simplifyRange = require('semver/ranges/simplify') const rangeSubset = require('semver/ranges/subset') ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) --rtl Coerce version strings right to left --ltr Coerce version strings left to right (default) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0-0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless `includePrerelease` is specified, in which case any version at all satisfies) * `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0-0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero element in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0-0` * `^0.2.3` := `>=0.2.3 <0.3.0-0` * `^0.0.3` := `>=0.0.3 <0.0.4-0` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0-0` * `^0.0.x` := `>=0.0.0 <0.1.0-0` * `^0.0` := `>=0.0.0 <0.1.0-0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0-0` * `^0.x` := `>=0.0.0 <1.0.0-0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions are equal. Sorts in ascending order if passed to `Array.sort()`. `v2` is greater. Sorts in ascending order if passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect * `simplifyRange(versions, range)`: Return a "simplified" range that matches the same items in `versions` list as the range specified. Note that it does *not* guarantee that it would match the same versions in all cases, only for the set of versions provided. This is useful when generating ranges by joining together multiple versions with `||` programmatically, to provide the user with something a bit more ergonomic. If the provided range is shorter in string-length than the generated range, then that is returned. * `subset(subRange, superRange)`: Return `true` if the `subRange` range is entirely contained by the `superRange` range. Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version, options)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). If the `options.rtl` flag is set, then `coerce` will return the right-most coercible tuple that does not share an ending index with a longer coercible tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not `4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of any other overlapping SemVer tuple. ### Clean * `clean(version)`: Clean a string to be a valid semver if possible This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges. ex. * `s.clean(' = v 2.1.5foo')`: `null` * `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'` * `s.clean(' = v 2.1.5-foo')`: `null` * `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'` * `s.clean('=v2.1.5')`: `'2.1.5'` * `s.clean(' =v2.1.5')`: `2.1.5` * `s.clean(' 2.1.5 ')`: `'2.1.5'` * `s.clean('~1.0.0')`: `null` ## Exported Modules <!-- TODO: Make sure that all of these items are documented (classes aren't, eg), and then pull the module name into the documentation for that specific thing. --> You may pull in just the part of this semver utility that you need, if you are sensitive to packing and tree-shaking concerns. The main `require('semver')` export uses getter functions to lazily load the parts of the API that are used. The following modules are available: * `require('semver')` * `require('semver/classes')` * `require('semver/classes/comparator')` * `require('semver/classes/range')` * `require('semver/classes/semver')` * `require('semver/functions/clean')` * `require('semver/functions/cmp')` * `require('semver/functions/coerce')` * `require('semver/functions/compare')` * `require('semver/functions/compare-build')` * `require('semver/functions/compare-loose')` * `require('semver/functions/diff')` * `require('semver/functions/eq')` * `require('semver/functions/gt')` * `require('semver/functions/gte')` * `require('semver/functions/inc')` * `require('semver/functions/lt')` * `require('semver/functions/lte')` * `require('semver/functions/major')` * `require('semver/functions/minor')` * `require('semver/functions/neq')` * `require('semver/functions/parse')` * `require('semver/functions/patch')` * `require('semver/functions/prerelease')` * `require('semver/functions/rcompare')` * `require('semver/functions/rsort')` * `require('semver/functions/satisfies')` * `require('semver/functions/sort')` * `require('semver/functions/valid')` * `require('semver/ranges/gtr')` * `require('semver/ranges/intersects')` * `require('semver/ranges/ltr')` * `require('semver/ranges/max-satisfying')` * `require('semver/ranges/min-satisfying')` * `require('semver/ranges/min-version')` * `require('semver/ranges/outside')` * `require('semver/ranges/to-comparators')` * `require('semver/ranges/valid')` # Ozone - Javascript Class Framework [![Build Status](https://travis-ci.org/inf3rno/o3.png?branch=master)](https://travis-ci.org/inf3rno/o3) The Ozone class framework contains enhanced class support to ease the development of object-oriented javascript applications in an ES5 environment. Another alternative to get a better class support to use ES6 classes and compilers like Babel, Traceur or TypeScript until native ES6 support arrives. ## Documentation ### Installation ```bash npm install o3 ``` ```bash bower install o3 ``` #### Environment compatibility The framework succeeded the tests on - node v4.2 and v5.x - chrome 51.0 - firefox 47.0 and 48.0 - internet explorer 11.0 - phantomjs 2.1 by the usage of npm scripts under win7 x64. I wasn't able to test the framework by Opera since the Karma launcher is buggy, so I decided not to support Opera. I used [Yadda](https://github.com/acuminous/yadda) to write BDD tests. I used [Karma](https://github.com/karma-runner/karma) with [Browserify](https://github.com/substack/node-browserify) to test the framework in browsers. On pre-ES5 environments there will be bugs in the Class module due to pre-ES5 enumeration and the lack of some ES5 methods, so pre-ES5 environments are not supported. #### Requirements An ES5 capable environment is required with - `Object.create` - ES5 compatible property enumeration: `Object.defineProperty`, `Object.getOwnPropertyDescriptor`, `Object.prototype.hasOwnProperty`, etc. - `Array.prototype.forEach` #### Usage In this documentation I used the framework as follows: ```js var o3 = require("o3"), Class = o3.Class; ``` ### Inheritance #### Inheriting from native classes (from the Error class in these examples) You can extend native classes by calling the Class() function. ```js var UserError = Class(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` An alternative to call Class.extend() with the Ancestor as the context. The Class() function uses this in the background. ```js var UserError = Class.extend.call(Error, { prototype: { message: "blah", constructor: function UserError() { Error.captureStackTrace(this, this.constructor); } } }); ``` #### Inheriting from custom classes You can use Class.extend() by any other class, not just by native classes. ```js var Ancestor = Class(Object, { prototype: { a: 1, b: 2 } }); var Descendant = Class.extend.call(Ancestor, { prototype: { c: 3 } }); ``` Or you can simply add it as a static method, so you don't have to pass context any time you want to use it. The only drawback, that this static method will be inherited as well. ```js var Ancestor = Class(Object, { extend: Class.extend, prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheriting from the Class class You can inherit the extend() method and other utility methods from the Class class. Probably this is the simplest solution if you need the Class API and you don't need to inherit from special native classes like Error. ```js var Ancestor = Class.extend({ prototype: { a: 1, b: 2 } }); var Descendant = Ancestor.extend({ prototype: { c: 3 } }); ``` #### Inheritance with clone and merge The static extend() method uses the clone() and merge() utility methods to inherit from the ancestor and add properties from the config. ```js var MyClass = Class.clone.call(Object, function MyClass(){ // ... }); Class.merge.call(MyClass, { prototype: { x: 1, y: 2 } }); ``` Or with utility methods. ```js var MyClass = Class.clone(function MyClass() { // ... }).merge({ prototype: { x: 1, y: 2 } }); ``` #### Inheritance with clone and absorb You can fill in missing properties with the usage of absorb. ```js var MyClass = Class(SomeAncestor, {...}); Class.absorb.call(MyClass, Class); MyClass.merge({...}); ``` For example if you don't have Class methods and your class already has an ancestor, then you can use absorb() to add Class methods. #### Abstract classes Using abstract classes with instantiation verification won't be implemented in this lib, however we provide an `abstractMethod`, which you can put to not implemented parts of your abstract class. ```js var AbstractA = Class({ prototype: { doA: function (){ // ... var b = this.getB(); // ... // do something with b // ... }, getB: abstractMethod } }); var AB1 = Class(AbstractA, { prototype: { getB: function (){ return new B1(); } } }); var ab1 = new AB1(); ``` I strongly support the composition over inheritance principle and I think you should use dependency injection instead of abstract classes. ```js var A = Class({ prototype: { init: function (b){ this.b = b; }, doA: function (){ // ... // do something with this.b // ... } } }); var b = new B1(); var ab1 = new A(b); ``` ### Constructors #### Using a custom constructor You can pass your custom constructor as a config option by creating the class. ```js var MyClass = Class(Object, { prototype: { constructor: function () { // ... } } }); ``` #### Using a custom factory to create the constructor Or you can pass a static factory method to create your custom constructor. ```js var MyClass = Class(Object, { factory: function () { return function () { // ... } } }); ``` #### Using an inherited factory to create the constructor By inheritance the constructors of the descendant classes will be automatically created as well. ```js var Ancestor = Class(Object, { factory: function () { return function () { // ... } } }); var Descendant = Class(Ancestor, {}); ``` #### Using the default factory to create the constructor You don't need to pass anything if you need a noop function as constructor. The Class.factory() will create a noop constructor by default. ```js var MyClass = Class(Object, {}); ``` In fact you don't need to pass any arguments to the Class function if you need an empty class inheriting from the Object native class. ```js var MyClass = Class(); ``` The default factory calls the build() and init() methods if they are given. ```js var MyClass = Class({ prototype: { build: function (options) { console.log("build", options); }, init: function (options) { console.log("init", options); } } }); var my = new MyClass({a: 1, b: 2}); // build {a: 1, b: 2} // init {a: 1, b: 2} var my2 = my.clone({c: 3}); // build {c: 3} var MyClass2 = MyClass.extend({}, [{d: 4}]); // build {d: 4} ``` ### Instantiation #### Creating new instance with the new operator Ofc. you can create a new instance in the javascript way. ```js var MyClass = Class(); var my = new MyClass(); ``` #### Creating a new instance with the static newInstance method If you want to pass an array of arguments then you can do it the following way. ```js var MyClass = Class.extend({ prototype: { constructor: function () { for (var i in arguments) console.log(arguments[i]); } } }); var my = MyClass.newInstance.apply(MyClass, ["a", "b", "c"]); // a // b // c ``` #### Creating new instance with clone You can create a new instance by cloning the prototype of the class. ```js var MyClass = Class(); var my = Class.prototype.clone.call(MyClass.prototype); ``` Or you can inherit the utility methods to make this easier. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); ``` Just be aware that by default cloning calls only the `build()` method, so the `init()` method won't be called by the new instance. #### Cloning instances You can clone an existing instance with the clone method. ```js var MyClass = Class.extend(); var my = MyClass.prototype.clone(); var my2 = my.clone(); ``` Be aware that this is prototypal inheritance with Object.create(), so the inherited properties won't be enumerable. The clone() method calls the build() method on the new instance if it is given. #### Using clone in the constructor You can use the same behavior both by cloning and by creating a new instance using the constructor ```js var MyClass = Class.extend({ lastIndex: 0, prototype: { index: undefined, constructor: function MyClass() { return MyClass.prototype.clone(); }, clone: function () { var instance = Class.prototype.clone.call(this); instance.index = ++MyClass.lastIndex; return instance; } } }); var my1 = new MyClass(); var my2 = MyClass.prototype.clone(); var my3 = my1.clone(); var my4 = my2.clone(); ``` Be aware that this way the constructor will drop the instance created with the `new` operator. Be aware that the clone() method is used by inheritance, so creating the prototype of a descendant class will use the clone() method as well. ```js var Descendant = MyClass.clone(function Descendant() { return Descendant.prototype.clone(); }); var my5 = Descendant.prototype; var my6 = new Descendant(); // ... ``` #### Using absorb(), merge() or inheritance to set the defaults values on properties You can use absorb() to set default values after configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(config); this.absorb(theDefaults); } } }); ``` You can use merge() to set default values before configuration. ```js var MyClass = Class.extend({ prototype: { constructor: function (config) { var theDefaults = { // ... }; this.merge(theDefaults); this.merge(config); } } }); ``` You can use inheritance to set default values on class level. ```js var MyClass = Class.extend({ prototype: { aProperty: defaultValue, // ... constructor: function (config) { this.merge(config); } } }); ``` ## License MIT - 2015 Jánszky László Lajos # cacheable-request > Wrap native HTTP requests with RFC compliant cache support [![Build Status](https://travis-ci.org/lukechilds/cacheable-request.svg?branch=master)](https://travis-ci.org/lukechilds/cacheable-request) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/cacheable-request/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/cacheable-request?branch=master) [![npm](https://img.shields.io/npm/dm/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [![npm](https://img.shields.io/npm/v/cacheable-request.svg)](https://www.npmjs.com/package/cacheable-request) [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching for native Node.js HTTP/HTTPS requests. Caching works out of the box in memory or is easily pluggable with a wide range of storage adapters. **Note:** This is a low level wrapper around the core HTTP modules, it's not a high level request library. ## Features - Only stores cacheable responses as defined by RFC 7234 - Fresh cache entries are served directly from cache - Stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers - 304 responses from revalidation requests use cached body - Updates `Age` header on cached responses - Can completely bypass cache on a per request basis - In memory cache by default - Official support for Redis, MongoDB, SQLite, PostgreSQL and MySQL storage adapters - Easily plug in your own or third-party storage adapters - If DB connection fails, cache is automatically bypassed ([disabled by default](#optsautomaticfailover)) - Adds cache support to any existing HTTP code with minimal changes - Uses [http-cache-semantics](https://github.com/pornel/http-cache-semantics) internally for HTTP RFC 7234 compliance ## Install ```shell npm install cacheable-request ``` ## Usage ```js const http = require('http'); const CacheableRequest = require('cacheable-request'); // Then instead of const req = http.request('http://example.com', cb); req.end(); // You can do const cacheableRequest = new CacheableRequest(http.request); const cacheReq = cacheableRequest('http://example.com', cb); cacheReq.on('request', req => req.end()); // Future requests to 'example.com' will be returned from cache if still valid // You pass in any other http.request API compatible method to be wrapped with cache support: const cacheableRequest = new CacheableRequest(https.request); const cacheableRequest = new CacheableRequest(electron.net); ``` ## Storage Adapters `cacheable-request` uses [Keyv](https://github.com/lukechilds/keyv) to support a wide range of storage adapters. For example, to use Redis as a cache backend, you just need to install the official Redis Keyv storage adapter: ``` npm install @keyv/redis ``` And then you can pass `CacheableRequest` your connection string: ```js const cacheableRequest = new CacheableRequest(http.request, 'redis://user:pass@localhost:6379'); ``` [View all official Keyv storage adapters.](https://github.com/lukechilds/keyv#official-storage-adapters) Keyv also supports anything that follows the Map API so it's easy to write your own storage adapter or use a third-party solution. e.g The following are all valid storage adapters ```js const storageAdapter = new Map(); // or const storageAdapter = require('./my-storage-adapter'); // or const QuickLRU = require('quick-lru'); const storageAdapter = new QuickLRU({ maxSize: 1000 }); const cacheableRequest = new CacheableRequest(http.request, storageAdapter); ``` View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters. ## API ### new cacheableRequest(request, [storageAdapter]) Returns the provided request function wrapped with cache support. #### request Type: `function` Request function to wrap with cache support. Should be [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) or a similar API compatible request function. #### storageAdapter Type: `Keyv storage adapter`<br> Default: `new Map()` A [Keyv](https://github.com/lukechilds/keyv) storage adapter instance, or connection string if using with an official Keyv storage adapter. ### Instance #### cacheableRequest(opts, [cb]) Returns an event emitter. ##### opts Type: `object`, `string` - Any of the default request functions options. - Any [`http-cache-semantics`](https://github.com/kornelski/http-cache-semantics#constructor-options) options. - Any of the following: ###### opts.cache Type: `boolean`<br> Default: `true` If the cache should be used. Setting this to false will completely bypass the cache for the current request. ###### opts.strictTtl Type: `boolean`<br> Default: `false` If set to `true` once a cached resource has expired it is deleted and will have to be re-requested. If set to `false` (default), after a cached resource's TTL expires it is kept in the cache and will be revalidated on the next request with `If-None-Match`/`If-Modified-Since` headers. ###### opts.maxTtl Type: `number`<br> Default: `undefined` Limits TTL. The `number` represents milliseconds. ###### opts.automaticFailover Type: `boolean`<br> Default: `false` When set to `true`, if the DB connection fails we will automatically fallback to a network request. DB errors will still be emitted to notify you of the problem even though the request callback may succeed. ###### opts.forceRefresh Type: `boolean`<br> Default: `false` Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a new request and override the cache instead. ##### cb Type: `function` The callback function which will receive the response as an argument. The response can be either a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage) or a [responselike object](https://github.com/lukechilds/responselike). The response will also have a `fromCache` property set with a boolean value. ##### .on('request', request) `request` event to get the request object of the request. **Note:** This event will only fire if an HTTP request is actually made, not when a response is retrieved from cache. However, you should always handle the `request` event to end the request and handle any potential request errors. ##### .on('response', response) `response` event to get the response object from the HTTP request or cache. ##### .on('error', error) `error` event emitted in case of an error with the cache. Errors emitted here will be an instance of `CacheableRequest.RequestError` or `CacheableRequest.CacheError`. You will only ever receive a `RequestError` if the request function throws (normally caused by invalid user input). Normal request errors should be handled inside the `request` event. To properly handle all error scenarios you should use the following pattern: ```js cacheableRequest('example.com', cb) .on('error', err => { if (err instanceof CacheableRequest.CacheError) { handleCacheError(err); // Cache error } else if (err instanceof CacheableRequest.RequestError) { handleRequestError(err); // Request function thrown } }) .on('request', req => { req.on('error', handleRequestError); // Request error emitted req.end(); }); ``` **Note:** Database connection errors are emitted here, however `cacheable-request` will attempt to re-request the resource and bypass the cache on a connection error. Therefore a database connection error doesn't necessarily mean the request won't be fulfilled. ## License MIT © Luke Childs # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # fs-constants Small module that allows you to get the fs constants across Node and the browser. ``` npm install fs-constants ``` Previously you would use `require('constants')` for this in node but that has been deprecated and changed to `require('fs').constants` which does not browserify. This module uses `require('constants')` in the browser and `require('fs').constants` in node to work around this ## Usage ``` js var constants = require('fs-constants') console.log('constants:', constants) ``` ## License MIT # axios // adapters The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received. ## Example ```js var settle = require('./../core/settle'); module.exports = function myAdapter(config) { // At this point: // - config has been merged with defaults // - request transformers have already run // - request interceptors have already run // Make the request using config provided // Upon response settle the Promise return new Promise(function(resolve, reject) { var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // From here: // - response transformers will run // - response interceptors will run }); } ``` # MD5 [![build status](https://secure.travis-ci.org/pvorb/node-md5.png)](http://travis-ci.org/pvorb/node-md5) [![info badge](https://img.shields.io/npm/dt/md5.svg)](http://npm-stat.com/charts.html?package=md5) a JavaScript function for hashing messages with MD5. node-md5 is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial <a href="https://tracking.gitads.io/?repo=node-md5"><img src="https://images.gitads.io/node-md5" alt="GitAds"/></a> ## Installation You can use this package on the server side as well as the client side. ### [Node.js](http://nodejs.org/): ~~~ npm install md5 ~~~ ## API ~~~ javascript md5(message) ~~~ * `message` -- `String`, `Buffer`, `Array` or `Uint8Array` * returns `String` ## Usage ~~~ javascript var md5 = require('md5'); console.log(md5('message')); ~~~ This will print the following ~~~ 78e731027d8fd50ed642340b7c9a63b3 ~~~ It supports buffers, too ~~~ javascript var fs = require('fs'); var md5 = require('md5'); fs.readFile('example.txt', function(err, buf) { console.log(md5(buf)); }); ~~~ ## Versions Before version 2.0.0 there were two packages called md5 on npm, one lowercase, one uppercase (the one you're looking at). As of version 2.0.0, all new versions of this module will go to lowercase [md5](https://www.npmjs.com/package/md5) on npm. To use the correct version, users of this module will have to change their code from `require('MD5')` to `require('md5')` if they want to use versions >= 2.0.0. ## Bugs and Issues If you encounter any bugs or issues, feel free to open an issue at [github](https://github.com/pvorb/node-md5/issues). ## Credits This package is based on the work of Jeff Mott, who did a pure JS implementation of the MD5 algorithm that was published by Ronald L. Rivest in 1991. I needed a npm package of the algorithm, so I used Jeff’s implementation for this package. The original implementation can be found in the [CryptoJS](http://code.google.com/p/crypto-js/) project. ## License ~~~ Copyright © 2011-2015, Paul Vorbach. Copyright © 2009, Jeff Mott. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name Crypto-JS nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ~~~ tcp-port-used ============= A simple Node.js module to check if a TCP port is currently in use. It returns a deferred promise from the q library. ## Installation npm install tcp-port-used ## Examples To check a port's state: var tcpPortUsed = require('tcp-port-used'); tcpPortUsed.check(44201, '127.0.0.1') .then(function(inUse) { console.log('Port 44201 usage: '+inUse); }, function(err) { console.error('Error on check:', err.message); }); To wait until a port on localhost is available: tcpPortUsed.waitUntilFree(44203, 500, 4000) .then(function() { console.log('Port 44203 is now free.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is available: tcpPortUsed.waitUntilFreeOnHost(44203, 'some.host.com', 500, 4000) .then(function() { console.log('Port 44203 on some.host.com is now free.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on localhost is accepting connections: tcpPortUsed.waitUntilUsed(44204, 500, 4000) .then(function() { console.log('Port 44204 is now in use.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is accepting connections: tcpPortUsed.waitUntilUsedOnHost(44204, 'some.host.com', 500, 4000) .then(function() { console.log('Port 44204 on some.host.com is now in use.'); }, function(err) { console.log('Error:', err.message); }); To wait until a port on a host is in specific state: var inUse = true; // wait until the port is in use tcpPortUsed.waitForStatus(44204, 'some.host.com', inUse, 500, 4000) .then(function() { console.log('Port 44204 on some.host.com is now in use.'); }, function(err) { console.log('Error:', err.message); }); ## API ### check(port [, host]) Checks if a TCP port is in use by attempting to connect to the port on host. If no host is specified, the module uses '127.0.0.1' (localhost). When the promise is resolved, there is a parameter `inUse`, when true means the port is in use and false means the port is free. **Parameters:** * **Number|Object** *port* The port you are curious to see if available. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' **Returns:** **Object** A deferred promise from the q module. ### waitUntilFree(port [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the localhost socket is free. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object must contain all the parameters as properties. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilFreeOnHost(port [, host] [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the localhost socket is free. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. If the host is not defined, the modules uses the default '127.0.0.1'. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilUsed(port [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the socket is accepting connections. Will retry on an interval specified in retryTimeMs until the timeout. If the host is not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitUntilUsedOnHost(port [, host] [, retryTimeMs] [, timeOutMs]) Returns a deferred promise and fulfills it only when the socket is accepting connections. Will retry on an interval specified in retryTimeMs until the timeout. If not defined the retryTime is 200 ms and the timeout is 2000 ms. If the host is not defined the module uses the default '127.0.0.1'. **Parameters:** * **Number|Object** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ### waitForStatus(port, host, status [, retryTimeMs] [, timeOutMs]) Waits until the port on host matches the boolean status in terms of use. If the status is true, the promise defers until the port is in use. If the status is false the promise defers until the port is free. If the host is undefined or null, the module uses the default '127.0.0.1'. Also, if not defined the retryTime is 200 ms and the timeout is 2000 ms. **Parameters:** * **Number** *port* a valid TCP port number. If an object, must contain all the parameters as properties. * **String** *host* The host name or IP address of the host. Default, if not defined: '127.0.0.1' * **Boolean** *status* A boolean describing the condition to wait for in terms of "in use." True indicates wait until the port is in use. False indicates wait until the port is free. * **Number** *[retryTimeMs]* the retry interval in milliseconds - defaultis is 100ms. * **Number** *[timeOutMs]* the amount of time to wait until port is free. Default 300ms. **Returns:** **Object** A deferred promise from the q module. ## License The MIT License (MIT) Copyright (c) 2013 jut-io Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ncp - Asynchronous recursive file & directory copying [![Build Status](https://secure.travis-ci.org/AvianFlu/ncp.png)](http://travis-ci.org/AvianFlu/ncp) Think `cp -r`, but pure node, and asynchronous. `ncp` can be used both as a CLI tool and programmatically. ## Command Line usage Usage is simple: `ncp [source] [dest] [--limit=concurrency limit] [--filter=filter] --stopOnErr` The 'filter' is a Regular Expression - matched files will be copied. The 'concurrency limit' is an integer that represents how many pending file system requests `ncp` has at a time. 'stoponerr' is a boolean flag that will tell `ncp` to stop immediately if any errors arise, rather than attempting to continue while logging errors. The default behavior is to complete as many copies as possible, logging errors along the way. If there are no errors, `ncp` will output `done.` when complete. If there are errors, the error messages will be logged to `stdout` and to `./ncp-debug.log`, and the copy operation will attempt to continue. ## Programmatic usage Programmatic usage of `ncp` is just as simple. The only argument to the completion callback is a possible error. ```javascript var ncp = require('ncp').ncp; ncp.limit = 16; ncp(source, destination, function (err) { if (err) { return console.error(err); } console.log('done!'); }); ``` You can also call ncp like `ncp(source, destination, options, callback)`. `options` should be a dictionary. Currently, such options are available: * `options.filter` - a `RegExp` instance, against which each file name is tested to determine whether to copy it or not, or a function taking single parameter: copied file name, returning `true` or `false`, determining whether to copy file or not. * `options.transform` - a function: `function (read, write) { read.pipe(write) }` used to apply streaming transforms while copying. * `options.clobber` - boolean=true. if set to false, `ncp` will not overwrite destination files that already exist. * `options.dereference` - boolean=false. If set to true, `ncp` will follow symbolic links. For example, a symlink in the source tree pointing to a regular file will become a regular file in the destination tree. Broken symlinks will result in errors. * `options.stopOnErr` - boolean=false. If set to true, `ncp` will behave like `cp -r`, and stop on the first error it encounters. By default, `ncp` continues copying, logging all errors and returning an array. * `options.errs` - stream. If `options.stopOnErr` is `false`, a stream can be provided, and errors will be written to this stream. Please open an issue if any bugs arise. As always, I accept (working) pull requests, and refunds are available at `/dev/null`. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript [![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x) [![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs) [![Join the chat at https://gitter.im/Reactive-Extensions/RxJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Reactive-Extensions/RxJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) # RxJS 6 Stable ### MIGRATION AND RELEASE INFORMATION: Find out how to update to v6, **automatically update your TypeScript code**, and more! - [Current home is MIGRATION.md](./docs_app/content/guide/v6/migration.md) ### FOR V 5.X PLEASE GO TO [THE 5.0 BRANCH](https://github.com/ReactiveX/rxjs/tree/5.x) Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Extensions/RxJS](https://github.com/Reactive-Extensions/RxJS) and is the latest production-ready version of RxJS. This rewrite is meant to have better performance, better modularity, better debuggable call stacks, while staying mostly backwards compatible, with some breaking changes that reduce the API surface. [Apache 2.0 License](LICENSE.txt) - [Code of Conduct](CODE_OF_CONDUCT.md) - [Contribution Guidelines](CONTRIBUTING.md) - [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md) - [API Documentation](https://rxjs.dev/) ## Versions In This Repository - [master](https://github.com/ReactiveX/rxjs/commits/master) - This is all of the current, unreleased work, which is against v6 of RxJS right now - [stable](https://github.com/ReactiveX/rxjs/commits/stable) - This is the branch for the latest version you'd get if you do `npm install rxjs` ## Important By contributing or commenting on issues in this repository, whether you've read them or not, you're agreeing to the [Contributor Code of Conduct](CODE_OF_CONDUCT.md). Much like traffic laws, ignorance doesn't grant you immunity. ## Installation and Usage ### ES6 via npm ```sh npm install rxjs ``` It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`. ```ts import { range } from "rxjs"; import { map, filter } from "rxjs/operators"; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information. ### CommonJS via npm To install this library for CommonJS (CJS) usage, use the following command: ```sh npm install rxjs ``` (Note: destructuring available in Node 8+) ```js const { range } = require('rxjs'); const { map, filter } = require('rxjs/operators'); range(1, 200).pipe( filter(x => x % 2 === 1), map(x => x + x) ).subscribe(x => console.log(x)); ``` ### CDN For CDN, you can use [unpkg](https://unpkg.com/): https://unpkg.com/rxjs/bundles/rxjs.umd.min.js The global namespace for rxjs is `rxjs`: ```js const { range } = rxjs; const { map, filter } = rxjs.operators; range(1, 200) .pipe( filter(x => x % 2 === 1), map(x => x + x) ) .subscribe(x => console.log(x)); ``` ## Goals - Smaller overall bundles sizes - Provide better performance than preceding versions of RxJS - To model/follow the [Observable Spec Proposal](https://github.com/zenparsing/es-observable) to the observable - Provide more modular file structure in a variety of formats - Provide more debuggable call stacks than preceding versions of RxJS ## Building/Testing - `npm run build_all` - builds everything - `npm test` - runs tests - `npm run test_no_cache` - run test with `ts-node` set to false ## Performance Tests Run `npm run build_perf` or `npm run perf` to run the performance tests with `protractor`. Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator. ## Adding documentation We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app). ## Generating PNG marble diagrams The script `npm run tests2png` requires some native packages installed locally: `imagemagick`, `graphicsmagick`, and `ghostscript`. For Mac OS X with [Homebrew](http://brew.sh/): - `brew install imagemagick` - `brew install graphicsmagick` - `brew install ghostscript` - You may need to install the Ghostscript fonts manually: - Download the tarball from the [gs-fonts project](https://sourceforge.net/projects/gs-fonts) - `mkdir -p /usr/local/share/ghostscript && tar zxvf /path/to/ghostscript-fonts.tar.gz -C /usr/local/share/ghostscript` For Debian Linux: - `sudo add-apt-repository ppa:dhor/myway` - `apt-get install imagemagick` - `apt-get install graphicsmagick` - `apt-get install ghostscript` For Windows and other Operating Systems, check the download instructions here: - http://imagemagick.org - http://www.graphicsmagick.org - http://www.ghostscript.com/ # libusb [![Build Status](https://travis-ci.org/libusb/libusb.svg?branch=master)](https://travis-ci.org/libusb/libusb) [![Build status](https://ci.appveyor.com/api/projects/status/xvrfam94jii4a6lw?svg=true)](https://ci.appveyor.com/project/LudovicRousseau/libusb) [![Coverity Scan Build Status](https://scan.coverity.com/projects/2180/badge.svg)](https://scan.coverity.com/projects/libusb-libusb) libusb is a library for USB device access from Linux, macOS, Windows, OpenBSD/NetBSD and Haiku userspace. It is written in C (Haiku backend in C++) and licensed under the GNU Lesser General Public License version 2.1 or, at your option, any later version (see [COPYING](COPYING)). libusb is abstracted internally in such a way that it can hopefully be ported to other operating systems. Please see the [PORTING](PORTING) file for more information. libusb homepage: http://libusb.info/ Developers will wish to consult the API documentation: http://api.libusb.info Use the mailing list for questions, comments, etc: http://mailing-list.libusb.info - Hans de Goede <[email protected]> - Xiaofan Chen <[email protected]> - Ludovic Rousseau <[email protected]> - Nathan Hjelm <[email protected]> - Chris Dickens <[email protected]> (Please use the mailing list rather than mailing developers directly) Like `chown -R`. Takes the same arguments as `fs.chown()` Pure-UUID ========= **Pure JavaScript Based Universally Unique Identifier (UUID)** <p/> <img src="https://nodei.co/npm/pure-uuid.png?downloads=true&stars=true" alt=""/> <p/> <img src="https://david-dm.org/rse/pure-uuid.png" alt=""/> Abstract -------- This is a pure JavaScript and dependency-free library for the generation of DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122 compliant Universally Unique Identifier (UUID). It supports DCE 1.1 variant UUIDs of version 1 (time and node based), version 3 (name based, MD5), version 4 (random number based) and version 5 (name based, SHA-1). It can be used in both [Node.js](http://nodejs.org/) based server and browser based client environments. The essential points of this implementation (in contrast to the many others) are: First, although internally 32/64 bit unsigned integer arithmentic and MD5/SHA-1 digest algorithmic is required, this UUID implementation is fully self-contained and dependency-free. Second, this implementation wraps around either `Uint8Array`, `Buffer` or `Array` standard classes and this way tries to represent UUIDs as best as possible in the particular environment. Third, thanks to a Universal Module Definition (UMD) wrapper, this library works out-of-the-box in all important JavaScript run-time environments. What is a UUID? --------------- UUIDs are 128 bit numbers which are intended to have a high likelihood of uniqueness over space and time and are computationally difficult to guess. They are globally unique identifiers which can be locally generated without contacting a global registration authority. UUIDs are intended as unique identifiers for both mass tagging objects with an extremely short lifetime and to reliably identifying very persistent objects across a network. ### UUID Binary Representation According to the DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122 standards, a DCE 1.1 variant UUID is a 128 bit number defined out of 7 fields, each field a multiple of an octet in size and stored in network byte order: ```txt [4] version -->| |<-- | | | | [16] [32] [16] | |time_hi time_low time_mid | _and_version |<---------------------------->||<------------>||<------------>| | MSB || || | | | / || || | | |/ || || | | +------++------++------++------++------++------++------++------+~~ | 15 || 14 || 13 || 12 || 11 || 10 |####9 || 8 | | MSO || || || || || |#### || | +------++------++------++------++------++------++------++------+~~ 7654321076543210765432107654321076543210765432107654321076543210 ~~+------++------++------++------++------++------++------++------+ ##* 7 || 6 || 5 || 4 || 3 || 2 || 1 || 0 | ##* || || || || || || || LSO | ~~+------++------++------++------++------++------++------++------+ 7654321076543210765432107654321076543210765432107654321076543210 | | || || /| | | || || / | | | || || LSB | |<---->||<---->||<-------------------------------------------->| |clk_seq clk_seq node |_hi_res _low [48] |[5-6] [8] | | -->| |<-- variant [2-3] ``` An example of a UUID binary representation is the octet stream 0xF8 0x1D 0x4F 0xAE 0x7D 0xEC 0x11 0xD0 0xA7 0x65 0x00 0xA0 0xC9 0x1E 0x6B 0xF6. ### UUID ASCII String Representation According to the DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122 standards, a DCE 1.1 variant UUID is represented as an ASCII string consisting of 8 hexadecimal digits followed by a hyphen, then three groups of 4 hexadecimal digits each followed by a hyphen, then 12 hexadecimal digits. Getting Pure-UUID ----------------- ``` $ npm install pure-uuid ``` Using Pure-UUID --------------- - global environment: ```js var uuid = new UUID(3, "ns:URL", "http://example.com/"); ``` - CommonJS environment: ```js var UUID = require("pure-uuid"); var uuid = new UUID(3, "ns:URL", "http://example.com/"); ``` - AMD environment: ```js define(["pure-uuid"], function (UUID) { var uuid = new UUID(3, "ns:URL", "http://example.com/"); }); ``` API --- ```ts interface UUID { /* making */ make(version: number, ...params: any[]): UUID; /* parsing */ parse(str: string): UUID; /* formatting */ format(type?: string): string; /* formatting (alias) */ toString(type?: string): string; /* sensible JSON serialization */ toJSON(): string; /* importing */ import(arr: number[]): UUID; /* exporting */ export(): number[]; /* byte-wise comparison */ compare(other: UUID): boolean; /* equal check */ equal(other: UUID): boolean; /* fold 1-4 times */ fold(k: number): number[]; } export interface UUIDConstructor { /* default construction */ new(): UUID; /* parsing construction */ new(uuid: string): UUID; /* making construction */ new(version: number): UUID; new(version: number, ns: string, data: string): UUID; } declare var UUID: UUIDConstructor; export default UUID; ``` Examples -------- ```js // load a UUID uuid = new UUID("0a300ee9-f9e4-5697-a51a-efc7fafaba67"); // make a UUID version 1 (time and node based) uuid = new UUID(1); // make a UUID version 3 (name-based, MD5) uuid = new UUID(3, "ns:URL", "http://example.com/"); // make a UUID version 4 (random number based) uuid = new UUID(4); // make a UUID version 5 (name-based, SHA-1) uuid = new UUID(5, "ns:URL", "http://example.com/"); // format a UUID in standard format str = uuid.format() str = uuid.format("std") // format a UUID in Base16 format str = uuid.format("b16") // format a UUID in ZeroMQ-Base85 format str = uuid.format("z85") ``` License ------- Copyright (c) 2004-2021 Dr. Ralf S. Engelschall (http://engelschall.com/) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <p align="center"> <a href="https://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # glob-parent [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Azure Pipelines Build Status][azure-pipelines-image]][azure-pipelines-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] Extract the non-magic parent path from a glob string. ## Usage ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## API ### `globParent(maybeGlobString, [options])` Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. #### options ```js { // Disables the automatic conversion of slashes for Windows flipBackslashes: true } ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) unless used as a path segment alone - `*` (asterisk) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations ### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. ### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` ## License ISC [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets [downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg [npm-url]: https://www.npmjs.com/package/glob-parent [npm-image]: https://img.shields.io/npm/v/glob-parent.svg [azure-pipelines-url]: https://dev.azure.com/gulpjs/gulp/_build/latest?definitionId=2&branchName=master [azure-pipelines-image]: https://dev.azure.com/gulpjs/gulp/_apis/build/status/glob-parent?branchName=master [travis-url]: https://travis-ci.org/gulpjs/glob-parent [travis-image]: https://img.shields.io/travis/gulpjs/glob-parent.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/glob-parent [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/glob-parent.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent [coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # path-browserify [![Build Status](https://travis-ci.org/browserify/path-browserify.png?branch=master)](https://travis-ci.org/browserify/path-browserify) > The `path` module from Node.js for browsers This implements the Node.js [`path`][path] module for environments that do not have it, like browsers. > `path-browserify` currently matches the **Node.js 10.3** API. ## Install You usually do not have to install `path-browserify` yourself! If your code runs in Node.js, `path` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) include the `path-browserify` module by default. But if none of those apply, with npm do: ``` npm install path-browserify ``` ## Usage ```javascript var path = require('path') var filename = 'logo.png'; var logo = path.join('./assets/img', filename); document.querySelector('#logo').src = logo; ``` ## API See the [Node.js path docs][path]. `path-browserify` currently matches the Node.js 10.3 API. `path-browserify` only implements the POSIX functions, not the win32 ones. ## Contributing PRs are very welcome! The main way to contribute to `path-browserify` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core `path` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. If there is a difference in behaviour between Node.js's `path` module and this module, please open an issue! ## License [MIT](./LICENSE) [path]: https://nodejs.org/docs/v10.3.0/api/path.html # node-error-ex [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-error-ex.svg?style=flat-square)](https://travis-ci.org/Qix-/node-error-ex) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-error-ex.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-error-ex) > Easily subclass and customize new Error types ## Examples To include in your project: ```javascript var errorEx = require('error-ex'); ``` To create an error message type with a specific name (note, that `ErrorFn.name` will not reflect this): ```javascript var JSONError = errorEx('JSONError'); var err = new JSONError('error'); err.name; //-> JSONError throw err; //-> JSONError: error ``` To add a stack line: ```javascript var JSONError = errorEx('JSONError', {fileName: errorEx.line('in %s')}); var err = new JSONError('error') err.fileName = '/a/b/c/foo.json'; throw err; //-> (line 2)-> in /a/b/c/foo.json ``` To append to the error message: ```javascript var JSONError = errorEx('JSONError', {fileName: errorEx.append('in %s')}); var err = new JSONError('error'); err.fileName = '/a/b/c/foo.json'; throw err; //-> JSONError: error in /a/b/c/foo.json ``` ## API #### `errorEx([name], [properties])` Creates a new ErrorEx error type - `name`: the name of the new type (appears in the error message upon throw; defaults to `Error.name`) - `properties`: if supplied, used as a key/value dictionary of properties to use when building up the stack message. Keys are property names that are looked up on the error message, and then passed to function values. - `line`: if specified and is a function, return value is added as a stack entry (error-ex will indent for you). Passed the property value given the key. - `stack`: if specified and is a function, passed the value of the property using the key, and the raw stack lines as a second argument. Takes no return value (but the stack can be modified directly). - `message`: if specified and is a function, return value is used as new `.message` value upon get. Passed the property value of the property named by key, and the existing message is passed as the second argument as an array of lines (suitable for multi-line messages). Returns a constructor (Function) that can be used just like the regular Error constructor. ```javascript var errorEx = require('error-ex'); var BasicError = errorEx(); var NamedError = errorEx('NamedError'); // -- var AdvancedError = errorEx('AdvancedError', { foo: { line: function (value, stack) { if (value) { return 'bar ' + value; } return null; } } } var err = new AdvancedError('hello, world'); err.foo = 'baz'; throw err; /* AdvancedError: hello, world bar baz at tryReadme() (readme.js:20:1) */ ``` #### `errorEx.line(str)` Creates a stack line using a delimiter > This is a helper function. It is to be used in lieu of writing a value object > for `properties` values. - `str`: The string to create - Use the delimiter `%s` to specify where in the string the value should go ```javascript var errorEx = require('error-ex'); var FileError = errorEx('FileError', {fileName: errorEx.line('in %s')}); var err = new FileError('problem reading file'); err.fileName = '/a/b/c/d/foo.js'; throw err; /* FileError: problem reading file in /a/b/c/d/foo.js at tryReadme() (readme.js:7:1) */ ``` #### `errorEx.append(str)` Appends to the `error.message` string > This is a helper function. It is to be used in lieu of writing a value object > for `properties` values. - `str`: The string to append - Use the delimiter `%s` to specify where in the string the value should go ```javascript var errorEx = require('error-ex'); var SyntaxError = errorEx('SyntaxError', {fileName: errorEx.append('in %s')}); var err = new SyntaxError('improper indentation'); err.fileName = '/a/b/c/d/foo.js'; throw err; /* SyntaxError: improper indentation in /a/b/c/d/foo.js at tryReadme() (readme.js:7:1) */ ``` ## License Licensed under the [MIT License](http://opensource.org/licenses/MIT). You can find a copy of it in [LICENSE](LICENSE). # jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](https://coveralls.io/repos/mathiasbynens/jsesc/badge.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc) Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except: 1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets; 2. it offers [many options](#api) to customize the output; 3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed. For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes) jsesc’s output can be used instead of `JSON.stringify`’s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install jsesc ``` In [Node.js](https://nodejs.org/): ```js const jsesc = require('jsesc'); ``` ## API ### `jsesc(value, options)` This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings: ```js jsesc('Ich ♥ Bücher'); // → 'Ich \\u2665 B\\xFCcher' jsesc('foo 𝌆 bar'); // → 'foo \\uD834\\uDF06 bar' ``` Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way. ```js // Escaping an array jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ]); // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']' // Escaping an object jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }); // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}' ``` The optional `options` argument accepts an object with the following options: #### `quotes` The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.'); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single' }); // → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.' // → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc." ``` If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double' }); // → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.' // → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc." ``` If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'backtick' }); // → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.' // → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc." // → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.` ``` This setting also affects the output for arrays and objects: ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'quotes': 'double' }); // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'quotes': 'double' }); // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]' ``` #### `numbers` The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. ```js jsesc(42, { 'numbers': 'binary' }); // → '0b101010' jsesc(42, { 'numbers': 'octal' }); // → '0o52' jsesc(42, { 'numbers': 'decimal' }); // → '42' jsesc(42, { 'numbers': 'hexadecimal' }); // → '0x2A' ``` #### `wrap` The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. ```js jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true }); // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true }); // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" ``` #### `es6` The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`). ```js // By default, the `es6` option is disabled: jsesc('foo 𝌆 bar 💩 baz'); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To explicitly disable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': false }); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To enable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': true }); // → 'foo \\u{1D306} bar \\u{1F4A9} baz' ``` #### `escapeEverything` The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols. ```js jsesc('lolwat"foo\'bar', { 'escapeEverything': true }); // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72' // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72" ``` This setting also affects the output for string literals within arrays and objects. #### `minimal` The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped: * U+0000 `\0` * U+0008 `\b` * U+0009 `\t` * U+000A `\n` * U+000C `\f` * U+000D `\r` * U+005C `\\` * U+2028 `\u2028` * U+2029 `\u2029` * whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes)) Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe. ```js jsesc('foo\u2029bar\nbaz©qux𝌆flops', { 'minimal': false }); // → 'foo\\u2029bar\\nbaz©qux𝌆flops' ``` #### `isScriptContext` The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`</script` and `</style`](https://mathiasbynens.be/notes/etago) in the output are escaped as `<\/script` and `<\/style`, and [`<!--`](https://mathiasbynens.be/notes/etago#comment-8) is escaped as `\x3C!--` (or `\u003C!--` when the `json` option is enabled). This setting is useful when jsesc’s output ends up as part of a `<script>` or `<style>` element in an HTML document. ```js jsesc('foo</script>bar', { 'isScriptContext': true }); // → 'foo<\\/script>bar' ``` #### `compact` The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects is as compact as possible; it’s not formatted nicely. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': true // this is the default }); // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false }); // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `indent` The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is enabled (`true`), the value of the `indent` option is used to format the output for arrays and objects. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': '\t' // this is the default }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': ' ' }); // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false, 'indent': ' ' }); // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `indentLevel` The `indentLevel` option takes a numeric value, and defaults to `0`. It represents the current indentation level, i.e. the number of times the value of [the `indent` option](#indent) is repeated. ```js jsesc(['a', 'b', 'c'], { 'compact': false, 'indentLevel': 1 }); // → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]' jsesc(['a', 'b', 'c'], { 'compact': false, 'indentLevel': 2 }); // → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]' ``` #### `json` The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore. ```js jsesc('foo\x00bar\xFF\uFFFDbaz', { 'json': true }); // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"' jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, { 'json': true }); // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}' jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], { 'json': true }); // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]' // Values that are acceptable in JSON but aren’t strings, arrays, or object // literals can’t be escaped, so they’ll just be preserved: jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], { 'json': true }); // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]' // Values that aren’t allowed in JSON are run through `JSON.stringify()`: jsesc([ undefined, -Infinity ], { 'json': true }); // → '[null,null]' ``` **Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/). #### `lowercaseHex` The `lowercaseHex` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any alphabetical hexadecimal digits in escape sequences as well as any hexadecimal integer literals (see [the `numbers` option](#numbers)) in the output are in lowercase. ```js jsesc('Ich ♥ Bücher', { 'lowercaseHex': true }); // → 'Ich \\u2665 B\\xfccher' // ^^ jsesc(42, { 'numbers': 'hexadecimal', 'lowercaseHex': true }); // → '0x2a' // ^^ ``` ### `jsesc.version` A string representing the semantic version number. ### Using the `jsesc` binary To use the `jsesc` binary in your shell, simply install jsesc globally using npm: ```bash npm install -g jsesc ``` After that you’re able to escape strings from the command line: ```bash $ jsesc 'föo ♥ bår 𝌆 baz' f\xF6o \u2665 b\xE5r \uD834\uDF06 baz ``` To escape arrays or objects containing string values, use the `-o`/`--object` option: ```bash $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }' {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'} ``` To prettify the output in such cases, use the `-p`/`--pretty` option: ```bash $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { 'f\xF6o': '\u2665', 'b\xE5r': '\uD834\uDF06 baz' } ``` For valid JSON output, use the `-j`/`--json` option: ```bash $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { "f\u00F6o": "\u2665", "b\u00E5r": "\uD834\uDF06 baz" } ``` Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file: ```bash $ jsesc --json --object < data-raw.json > data-escaped.json ``` Or do the same with an online JSON file: ```bash $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json ``` See `jsesc --help` for the full list of options. ## Support As of v2.0.0, jsesc supports Node.js v4+ only. Older versions (up to jsesc v1.3.0) support Chrome 27, Firefox 3, Safari 4, Opera 10, IE 6, Node.js v6.0.0, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7RC4. **Note:** Using the `json` option on objects or arrays that contain non-string values relies on `JSON.parse()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](https://bestiejs.github.io/json3/). ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License This library is available under the [MIT](https://mths.be/mit) license. # Tools ## clang-format The clang-format checking tools is designed to check changed lines of code compared to given git-refs. ## Migration Script The migration tool is designed to reduce repetitive work in the migration process. However, the script is not aiming to convert every thing for you. There are usually some small fixes and major reconstruction required. ### How To Use To run the conversion script, first make sure you have the latest `node-addon-api` in your `node_modules` directory. ``` npm install node-addon-api ``` Then run the script passing your project directory ``` node ./node_modules/node-addon-api/tools/conversion.js ./ ``` After finish, recompile and debug things that are missed by the script. ### Quick Fixes Here is the list of things that can be fixed easily. 1. Change your methods' return value to void if it doesn't return value to JavaScript. 2. Use `.` to access attribute or to invoke member function in Napi::Object instead of `->`. 3. `Napi::New(env, value);` to `Napi::[Type]::New(env, value); ### Major Reconstructions The implementation of `Napi::ObjectWrap` is significantly different from NAN's. `Napi::ObjectWrap` takes a pointer to the wrapped object and creates a reference to the wrapped object inside ObjectWrap constructor. `Napi::ObjectWrap` also associates wrapped object's instance methods to Javascript module instead of static methods like NAN. So if you use Nan::ObjectWrap in your module, you will need to execute the following steps. 1. Convert your [ClassName]::New function to a constructor function that takes a `Napi::CallbackInfo`. Declare it as ``` [ClassName](const Napi::CallbackInfo& info); ``` and define it as ``` [ClassName]::[ClassName](const Napi::CallbackInfo& info) : Napi::ObjectWrap<[ClassName]>(info){ ... } ``` This way, the `Napi::ObjectWrap` constructor will be invoked after the object has been instantiated and `Napi::ObjectWrap` can use the `this` pointer to create a reference to the wrapped object. 2. Move your original constructor code into the new constructor. Delete your original constructor. 3. In your class initialization function, associate native methods in the following way. ``` Napi::FunctionReference constructor; void [ClassName]::Init(Napi::Env env, Napi::Object exports, Napi::Object module) { Napi::HandleScope scope(env); Napi::Function ctor = DefineClass(env, "Canvas", { InstanceMethod<&[ClassName]::Func1>("Func1"), InstanceMethod<&[ClassName]::Func2>("Func2"), InstanceAccessor<&[ClassName]::ValueGetter>("Value"), StaticMethod<&[ClassName]::StaticMethod>("MethodName"), InstanceValue("Value", Napi::[Type]::New(env, value)), }); constructor = Napi::Persistent(ctor); constructor .SuppressDestruct(); exports.Set("[ClassName]", ctor); } ``` 4. In function where you need to Unwrap the ObjectWrap in NAN like `[ClassName]* native = Nan::ObjectWrap::Unwrap<[ClassName]>(info.This());`, use `this` pointer directly as the unwrapped object as each ObjectWrap instance is associated with a unique object instance. If you still find issues after following this guide, please leave us an issue describing your problem and we will try to resolve it. node-fetch ========== [![npm version][npm-image]][npm-url] [![build status][travis-image]][travis-url] [![coverage status][codecov-image]][codecov-url] [![install size][install-size-image]][install-size-url] [![Discord][discord-image]][discord-url] A light-weight module that brings `window.fetch` to Node.js (We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) [![Backers][opencollective-image]][opencollective-url] <!-- TOC --> - [Motivation](#motivation) - [Features](#features) - [Difference from client-side fetch](#difference-from-client-side-fetch) - [Installation](#installation) - [Loading and configuring the module](#loading-and-configuring-the-module) - [Common Usage](#common-usage) - [Plain text or HTML](#plain-text-or-html) - [JSON](#json) - [Simple Post](#simple-post) - [Post with JSON](#post-with-json) - [Post with form parameters](#post-with-form-parameters) - [Handling exceptions](#handling-exceptions) - [Handling client and server errors](#handling-client-and-server-errors) - [Advanced Usage](#advanced-usage) - [Streams](#streams) - [Buffer](#buffer) - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) - [Extract Set-Cookie Header](#extract-set-cookie-header) - [Post data using a file stream](#post-data-using-a-file-stream) - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) - [API](#api) - [fetch(url[, options])](#fetchurl-options) - [Options](#options) - [Class: Request](#class-request) - [Class: Response](#class-response) - [Class: Headers](#class-headers) - [Interface: Body](#interface-body) - [Class: FetchError](#class-fetcherror) - [License](#license) - [Acknowledgement](#acknowledgement) <!-- /TOC --> ## Motivation Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). ## Features - Stay consistent with `window.fetch` API. - Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. - Use native promise but allow substituting it with [insert your favorite promise library]. - Use native Node streams for body on both request and response. - Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. - Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. ## Difference from client-side fetch - See [Known Differences](LIMITS.md) for details. - If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. - Pull requests are welcomed too! ## Installation Current stable release (`2.x`) ```sh $ npm install node-fetch ``` ## Loading and configuring the module We suggest you load the module via `require` until the stabilization of ES modules in node: ```js const fetch = require('node-fetch'); ``` If you are using a Promise library other than native, set it through `fetch.Promise`: ```js const Bluebird = require('bluebird'); fetch.Promise = Bluebird; ``` ## Common Usage NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. #### Plain text or HTML ```js fetch('https://github.com/') .then(res => res.text()) .then(body => console.log(body)); ``` #### JSON ```js fetch('https://api.github.com/users/github') .then(res => res.json()) .then(json => console.log(json)); ``` #### Simple Post ```js fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) .then(res => res.json()) // expecting a json response .then(json => console.log(json)); ``` #### Post with JSON ```js const body = { a: 1 }; fetch('https://httpbin.org/post', { method: 'post', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' }, }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form parameters `URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: ```js const { URLSearchParams } = require('url'); const params = new URLSearchParams(); params.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: params }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Handling exceptions NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. ```js fetch('https://domain.invalid/') .catch(err => console.error(err)); ``` #### Handling client and server errors It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: ```js function checkStatus(res) { if (res.ok) { // res.status >= 200 && res.status < 300 return res; } else { throw MyCustomError(res.statusText); } } fetch('https://httpbin.org/status/400') .then(checkStatus) .then(res => console.log('will not get here...')) ``` ## Advanced Usage #### Streams The "Node.js way" is to use streams when possible: ```js fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => { const dest = fs.createWriteStream('./octocat.png'); res.body.pipe(dest); }); ``` #### Buffer If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) ```js const fileType = require('file-type'); fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') .then(res => res.buffer()) .then(buffer => fileType(buffer)) .then(type => { /* ... */ }); ``` #### Accessing Headers and other Meta data ```js fetch('https://github.com/') .then(res => { console.log(res.ok); console.log(res.status); console.log(res.statusText); console.log(res.headers.raw()); console.log(res.headers.get('content-type')); }); ``` #### Extract Set-Cookie Header Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. ```js fetch(url).then(res => { // returns an array of values, instead of a string of comma-separated values console.log(res.headers.raw()['set-cookie']); }); ``` #### Post data using a file stream ```js const { createReadStream } = require('fs'); const stream = createReadStream('input.txt'); fetch('https://httpbin.org/post', { method: 'POST', body: stream }) .then(res => res.json()) .then(json => console.log(json)); ``` #### Post with form-data (detect multipart) ```js const FormData = require('form-data'); const form = new FormData(); form.append('a', 1); fetch('https://httpbin.org/post', { method: 'POST', body: form }) .then(res => res.json()) .then(json => console.log(json)); // OR, using custom headers // NOTE: getHeaders() is non-standard API const form = new FormData(); form.append('a', 1); const options = { method: 'POST', body: form, headers: form.getHeaders() } fetch('https://httpbin.org/post', options) .then(res => res.json()) .then(json => console.log(json)); ``` #### Request cancellation with AbortSignal > NOTE: You may cancel streamed requests only on Node >= v8.0.0 You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). An example of timing out a request after 150ms could be achieved as the following: ```js import AbortController from 'abort-controller'; const controller = new AbortController(); const timeout = setTimeout( () => { controller.abort(); }, 150, ); fetch(url, { signal: controller.signal }) .then(res => res.json()) .then( data => { useData(data) }, err => { if (err.name === 'AbortError') { // request was aborted } }, ) .finally(() => { clearTimeout(timeout); }); ``` See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. ## API ### fetch(url[, options]) - `url` A string representing the URL for fetching - `options` [Options](#fetch-options) for the HTTP(S) request - Returns: <code>Promise&lt;[Response](#class-response)&gt;</code> Perform an HTTP(S) fetch. `url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. <a id="fetch-options"></a> ### Options The default values are shown after each option key. ```js { // These properties are part of the Fetch Standard method: 'GET', headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect signal: null, // pass an instance of AbortSignal to optionally abort requests // The following properties are node-fetch extensions follow: 20, // maximum redirect count. 0 to not follow redirect timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. compress: true, // support gzip/deflate content encoding. false to disable size: 0, // maximum response body size in bytes. 0 to disable agent: null // http(s).Agent instance or function that returns an instance (see below) } ``` ##### Default Headers If no values are set, the following request headers will be sent automatically: Header | Value ------------------- | -------------------------------------------------------- `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ `Accept` | `*/*` `Connection` | `close` _(when no `options.agent` is present)_ `Content-Length` | _(automatically calculated, if possible)_ `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ `User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` Note: when `body` is a `Stream`, `Content-Length` is not set automatically. ##### Custom Agent The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: - Support self-signed certificate - Use only IPv4 or IPv6 - Custom DNS Lookup See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. ```js const httpAgent = new http.Agent({ keepAlive: true }); const httpsAgent = new https.Agent({ keepAlive: true }); const options = { agent: function (_parsedURL) { if (_parsedURL.protocol == 'http:') { return httpAgent; } else { return httpsAgent; } } } ``` <a id="class-request"></a> ### Class: Request An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. Due to the nature of Node.js, the following properties are not implemented at this moment: - `type` - `destination` - `referrer` - `referrerPolicy` - `mode` - `credentials` - `cache` - `integrity` - `keepalive` The following node-fetch extension properties are provided: - `follow` - `compress` - `counter` - `agent` See [options](#fetch-options) for exact meaning of these extensions. #### new Request(input[, options]) <small>*(spec-compliant)*</small> - `input` A string representing a URL, or another `Request` (which will be cloned) - `options` [Options][#fetch-options] for the HTTP(S) request Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. <a id="class-response"></a> ### Class: Response An HTTP(S) response. This class implements the [Body](#iface-body) interface. The following properties are not implemented in node-fetch at this moment: - `Response.error()` - `Response.redirect()` - `type` - `trailer` #### new Response([body[, options]]) <small>*(spec-compliant)*</small> - `body` A `String` or [`Readable` stream][node-readable] - `options` A [`ResponseInit`][response-init] options dictionary Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. #### response.ok <small>*(spec-compliant)*</small> Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. #### response.redirected <small>*(spec-compliant)*</small> Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. <a id="class-headers"></a> ### Class: Headers This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. #### new Headers([init]) <small>*(spec-compliant)*</small> - `init` Optional argument to pre-fill the `Headers` object Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. ```js // Example adapted from https://fetch.spec.whatwg.org/#example-headers-class const meta = { 'Content-Type': 'text/xml', 'Breaking-Bad': '<3' }; const headers = new Headers(meta); // The above is equivalent to const meta = [ [ 'Content-Type', 'text/xml' ], [ 'Breaking-Bad', '<3' ] ]; const headers = new Headers(meta); // You can in fact use any iterable objects, like a Map or even another Headers const meta = new Map(); meta.set('Content-Type', 'text/xml'); meta.set('Breaking-Bad', '<3'); const headers = new Headers(meta); const copyOfHeaders = new Headers(headers); ``` <a id="iface-body"></a> ### Interface: Body `Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. The following methods are not yet implemented in node-fetch at this moment: - `formData()` #### body.body <small>*(deviation from spec)*</small> * Node.js [`Readable` stream][node-readable] Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. #### body.bodyUsed <small>*(spec-compliant)*</small> * `Boolean` A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. #### body.arrayBuffer() #### body.blob() #### body.json() #### body.text() <small>*(spec-compliant)*</small> * Returns: <code>Promise</code> Consume the body and return a promise that will resolve to one of these formats. #### body.buffer() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;Buffer&gt;</code> Consume the body and return a promise that will resolve to a Buffer. #### body.textConverted() <small>*(node-fetch extension)*</small> * Returns: <code>Promise&lt;String&gt;</code> Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. (This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) <a id="class-fetcherror"></a> ### Class: FetchError <small>*(node-fetch extension)*</small> An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. <a id="class-aborterror"></a> ### Class: AbortError <small>*(node-fetch extension)*</small> An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. ## Acknowledgement Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. `node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). ## License MIT [npm-image]: https://flat.badgen.net/npm/v/node-fetch [npm-url]: https://www.npmjs.com/package/node-fetch [travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch [travis-url]: https://travis-ci.org/bitinn/node-fetch [codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master [codecov-url]: https://codecov.io/gh/bitinn/node-fetch [install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch [install-size-url]: https://packagephobia.now.sh/result?p=node-fetch [discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square [discord-url]: https://discord.gg/Zxbndcm [opencollective-image]: https://opencollective.com/node-fetch/backers.svg [opencollective-url]: https://opencollective.com/node-fetch [whatwg-fetch]: https://fetch.spec.whatwg.org/ [response-init]: https://fetch.spec.whatwg.org/#responseinit [node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams [mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers [LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md [ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md [UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md # whatwg-url whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). ## Current Status whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). ## API ### The `URL` Constructor The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. ### Low-level URL Standard API The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. - [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` - [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` - [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` - [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` - [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` - [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` - [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` - [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` - [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` The `stateOverride` parameter is one of the following strings: - [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) - [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) - [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) - [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) - [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) - [`"relative"`](https://url.spec.whatwg.org/#relative-state) - [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) - [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) - [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) - [`"authority"`](https://url.spec.whatwg.org/#authority-state) - [`"host"`](https://url.spec.whatwg.org/#host-state) - [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) - [`"port"`](https://url.spec.whatwg.org/#port-state) - [`"file"`](https://url.spec.whatwg.org/#file-state) - [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) - [`"file host"`](https://url.spec.whatwg.org/#file-host-state) - [`"path start"`](https://url.spec.whatwg.org/#path-start-state) - [`"path"`](https://url.spec.whatwg.org/#path-state) - [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) - [`"query"`](https://url.spec.whatwg.org/#query-state) - [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) The URL record type has the following API: - [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) - [`username`](https://url.spec.whatwg.org/#concept-url-username) - [`password`](https://url.spec.whatwg.org/#concept-url-password) - [`host`](https://url.spec.whatwg.org/#concept-url-host) - [`port`](https://url.spec.whatwg.org/#concept-url-port) - [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) - [`query`](https://url.spec.whatwg.org/#concept-url-query) - [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) - [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```ts @NearBindgen({}) class HelloNear { greeting: string = "Hello"; @view // This method is read-only and can be called for free get_greeting(): string { return this.greeting; } @call // This method changes the state, for which it cost gas set_greeting({ greeting }: { greeting: string }): void { // Record a log permanently to the blockchain! near.log(`Saving greeting ${greeting}`); this.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. `objectMode` can also be set by doing `stream.objectMode = true`, or by writing any non-string/non-buffer data. `objectMode` cannot be set to false once it is set. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For some examples of streams that extend Minipass in various ways, check out: - [minizlib](http://npm.im/minizlib) - [fs-minipass](http://npm.im/fs-minipass) - [tar](http://npm.im/tar) - [minipass-collect](http://npm.im/minipass-collect) - [minipass-flush](http://npm.im/minipass-flush) - [minipass-pipeline](http://npm.im/minipass-pipeline) - [tap](http://npm.im/tap) - [tap-parser](http://npm.im/tap-parser) - [treport](http://npm.im/treport) - [minipass-fetch](http://npm.im/minipass-fetch) - [pacote](http://npm.im/pacote) - [make-fetch-happen](http://npm.im/make-fetch-happen) - [cacache](http://npm.im/cacache) - [ssri](http://npm.im/ssri) - [npm-registry-fetch](http://npm.im/npm-registry-fetch) - [minipass-json-stream](http://npm.im/minipass-json-stream) - [minipass-sized](http://npm.im/minipass-sized) ## Differences from Node.js Streams There are several things that make Minipass streams different from (and in some ways superior to) Node.js core streams. Please read these caveats if you are familiar with node-core streams and intend to use Minipass streams in your programs. You can avoid most of these differences entirely (for a very small performance penalty) by setting `{async: true}` in the constructor options. ### Timing Minipass streams are designed to support synchronous use-cases. Thus, data is emitted as soon as it is available, always. It is buffered until read, but no longer. Another way to look at it is that Minipass streams are exactly as synchronous as the logic that writes into them. This can be surprising if your code relies on `PassThrough.write()` always providing data on the next tick rather than the current one, or being able to call `resume()` and not have the entire buffer disappear immediately. However, without this synchronicity guarantee, there would be no way for Minipass to achieve the speeds it does, or support the synchronous use cases that it does. Simply put, waiting takes time. This non-deferring approach makes Minipass streams much easier to reason about, especially in the context of Promises and other flow-control mechanisms. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ async: true }) stream.on('data', () => console.log('data event')) console.log('before write') stream.write('hello') console.log('after write') // output: // before write // data event // after write ``` ### Exception: Async Opt-In If you wish to have a Minipass stream with behavior that more closely mimics Node.js core streams, you can set the stream in async mode either by setting `async: true` in the constructor options, or by setting `stream.async = true` later on. ```js const Minipass = require('minipass') const asyncStream = new Minipass({ async: true }) asyncStream.on('data', () => console.log('data event')) console.log('before write') asyncStream.write('hello') console.log('after write') // output: // before write // after write // data event <-- this is deferred until the next tick ``` Switching _out_ of async mode is unsafe, as it could cause data corruption, and so is not enabled. Example: ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') setStreamSyncAgainSomehow(stream) // <-- this doesn't actually exist! stream.write('world') console.log('after writes') // hypothetical output would be: // before writes // world // after writes // hello // NOT GOOD! ``` To avoid this problem, once set into async mode, any attempt to make the stream sync again will be ignored. ```js const Minipass = require('minipass') const stream = new Minipass({ encoding: 'utf8' }) stream.on('data', chunk => console.log(chunk)) stream.async = true console.log('before writes') stream.write('hello') stream.async = false // <-- no-op, stream already async stream.write('world') console.log('after writes') // actual output: // before writes // after writes // hello // world ``` ### No High/Low Water Marks Node.js core streams will optimistically fill up a buffer, returning `true` on all writes until the limit is hit, even if the data has nowhere to go. Then, they will not attempt to draw more data in until the buffer size dips below a minimum value. Minipass streams are much simpler. The `write()` method will return `true` if the data has somewhere to go (which is to say, given the timing guarantees, that the data is already there by the time `write()` returns). If the data has nowhere to go, then `write()` returns false, and the data sits in a buffer, to be drained out immediately as soon as anyone consumes it. Since nothing is ever buffered unnecessarily, there is much less copying data, and less bookkeeping about buffer capacity levels. ### Hazards of Buffering (or: Why Minipass Is So Fast) Since data written to a Minipass stream is immediately written all the way through the pipeline, and `write()` always returns true/false based on whether the data was fully flushed, backpressure is communicated immediately to the upstream caller. This minimizes buffering. Consider this case: ```js const {PassThrough} = require('stream') const p1 = new PassThrough({ highWaterMark: 1024 }) const p2 = new PassThrough({ highWaterMark: 1024 }) const p3 = new PassThrough({ highWaterMark: 1024 }) const p4 = new PassThrough({ highWaterMark: 1024 }) p1.pipe(p2).pipe(p3).pipe(p4) p4.on('data', () => console.log('made it through')) // this returns false and buffers, then writes to p2 on next tick (1) // p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2) // p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3) // p4 returns false and buffers, pausing p3, then emits 'data' and 'drain' // on next tick (4) // p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and // 'drain' on next tick (5) // p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6) // p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next // tick (7) p1.write(Buffer.alloc(2048)) // returns false ``` Along the way, the data was buffered and deferred at each stage, and multiple event deferrals happened, for an unblocked pipeline where it was perfectly safe to write all the way through! Furthermore, setting a `highWaterMark` of `1024` might lead someone reading the code to think an advisory maximum of 1KiB is being set for the pipeline. However, the actual advisory buffering level is the _sum_ of `highWaterMark` values, since each one has its own bucket. Consider the Minipass case: ```js const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) // m1 is flowing, so it writes the data to m2 immediately // m2 is flowing, so it writes the data to m3 immediately // m3 is flowing, so it writes the data to m4 immediately // m4 is flowing, so it fires the 'data' event immediately, returns true // m4's write returned true, so m3 is still flowing, returns true // m3's write returned true, so m2 is still flowing, returns true // m2's write returned true, so m1 is still flowing, returns true // No event deferrals or buffering along the way! m1.write(Buffer.alloc(2048)) // returns true ``` It is extremely unlikely that you _don't_ want to buffer any data written, or _ever_ buffer data that can be flushed all the way through. Neither node-core streams nor Minipass ever fail to buffer written data, but node-core streams do a lot of unnecessary buffering and pausing. As always, the faster implementation is the one that does less stuff and waits less time to do it. ### Immediately emit `end` for empty streams (when not paused) If a stream is not paused, and `end()` is called before writing any data into it, then it will emit `end` immediately. If you have logic that occurs on the `end` event which you don't want to potentially happen immediately (for example, closing file descriptors, moving on to the next entry in an archive parse stream, etc.) then be sure to call `stream.pause()` on creation, and then `stream.resume()` once you are ready to respond to the `end` event. However, this is _usually_ not a problem because: ### Emit `end` When Asked One hazard of immediately emitting `'end'` is that you may not yet have had a chance to add a listener. In order to avoid this hazard, Minipass streams safely re-emit the `'end'` event if a new listener is added after `'end'` has been emitted. Ie, if you do `stream.on('end', someFunction)`, and the stream has already emitted `end`, then it will call the handler right away. (You can think of this somewhat like attaching a new `.then(fn)` to a previously-resolved Promise.) To prevent calling handlers multiple times who would not expect multiple ends to occur, all listeners are removed from the `'end'` event whenever it is emitted. ### Emit `error` When Asked The most recent error object passed to the `'error'` event is stored on the stream. If a new `'error'` event handler is added, and an error was previously emitted, then the event handler will be called immediately (or on `process.nextTick` in the case of async streams). This makes it much more difficult to end up trying to interact with a broken stream, if the error handler is added after an error was previously emitted. ### Impact of "immediate flow" on Tee-streams A "tee stream" is a stream piping to multiple destinations: ```js const tee = new Minipass() t.pipe(dest1) t.pipe(dest2) t.write('foo') // goes to both destinations ``` Since Minipass streams _immediately_ process any pending data through the pipeline when a new pipe destination is added, this can have surprising effects, especially when a stream comes in from some other function and may or may not have data in its buffer. ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone src.pipe(dest2) // gets nothing! ``` One solution is to create a dedicated tee-stream junction that pipes to both locations, and then pipe to _that_ instead. ```js // Safe example: tee to both places const src = new Minipass() src.write('foo') const tee = new Minipass() tee.pipe(dest1) tee.pipe(dest2) src.pipe(tee) // tee gets 'foo', pipes to both locations ``` The same caveat applies to `on('data')` event listeners. The first one added will _immediately_ receive all of the data, leaving nothing for the second: ```js // WARNING! WILL LOSE DATA! const src = new Minipass() src.write('foo') src.on('data', handler1) // receives 'foo' right away src.on('data', handler2) // nothing to see here! ``` Using a dedicated tee-stream can be used in this case as well: ```js // Safe example: tee to both data handlers const src = new Minipass() src.write('foo') const tee = new Minipass() tee.on('data', handler1) tee.on('data', handler2) src.pipe(tee) ``` All of the hazards in this section are avoided by setting `{ async: true }` in the Minipass constructor, or by setting `stream.async = true` afterwards. Note that this does add some overhead, so should only be done in cases where you are willing to lose a bit of performance in order to avoid having to refactor program logic. ## USAGE It's a stream! Use it like a stream and it'll most likely do what you want. ```js const Minipass = require('minipass') const mp = new Minipass(options) // optional: { encoding, objectMode } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### OPTIONS * `encoding` How would you like the data coming _out_ of the stream to be encoded? Accepts any values that can be passed to `Buffer.toString()`. * `objectMode` Emit data exactly as it comes in. This will be flipped on by default if you write() something other than a string or Buffer at any point. Setting `objectMode: true` will prevent setting any encoding value. * `async` Defaults to `false`. Set to `true` to defer data emission until next tick. This reduces performance slightly, but makes Minipass streams use timing behavior closer to Node core streams. See [Timing](#timing) for more details. ### API Implements the user-facing portions of Node.js's `Readable` and `Writable` streams. ### Methods * `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the base Minipass class, the same data will come out.) Returns `false` if the stream will buffer the next write, or true if it's still in "flowing" mode. * `end([chunk, [encoding]], [callback])` - Signal that you have no more data to write. This will queue an `end` event to be fired when all the data has been consumed. * `setEncoding(encoding)` - Set the encoding for data coming of the stream. This can only be done once. * `pause()` - No more data for a while, please. This also prevents `end` from being emitted for empty streams until the stream is resumed. * `resume()` - Resume the stream. If there's data in the buffer, it is all discarded. Any buffered events are immediately emitted. * `pipe(dest)` - Send all output to the stream provided. When data is emitted, it is immediately written to any and all pipe destinations. (Or written on next tick in `async` mode.) * `unpipe(dest)` - Stop piping to the destination stream. This is immediate, meaning that any asynchronously queued data will _not_ make it to the destination when running in `async` mode. * `options.end` - Boolean, end the destination stream when the source stream ends. Default `true`. * `options.proxyErrors` - Boolean, proxy `error` events from the source stream to the destination stream. Note that errors are _not_ proxied after the pipeline terminates, either due to the source emitting `'end'` or manually unpiping with `src.unpipe(dest)`. Default `false`. * `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some events are given special treatment, however. (See below under "events".) * `promise()` - Returns a Promise that resolves when the stream emits `end`, or rejects if the stream emits `error`. * `collect()` - Return a Promise that resolves on `end` with an array containing each chunk of data that was emitted, or rejects if the stream emits `error`. Note that this consumes the stream data. * `concat()` - Same as `collect()`, but concatenates the data into a single Buffer object. Will reject the returned promise if the stream is in objectMode, or if it goes into objectMode by the end of the data. * `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not provided, then consume all of it. If `n` bytes are not available, then it returns null. **Note** consuming streams in this way is less efficient, and can lead to unnecessary Buffer copying. * `destroy([er])` - Destroy the stream. If an error is provided, then an `'error'` event is emitted. If the stream has a `close()` method, and has not emitted a `'close'` event yet, then `stream.close()` will be called. Any Promises returned by `.promise()`, `.collect()` or `.concat()` will be rejected. After being destroyed, writing to the stream will emit an error. No more data will be emitted if the stream is destroyed, even if it was previously buffered. ### Properties * `bufferLength` Read-only. Total number of bytes buffered, or in the case of objectMode, the total number of objects. * `encoding` The encoding that has been set. (Setting this is equivalent to calling `setEncoding(enc)` and has the same prohibition against setting multiple times.) * `flowing` Read-only. Boolean indicating whether a chunk written to the stream will be immediately emitted. * `emittedEnd` Read-only. Boolean indicating whether the end-ish events (ie, `end`, `prefinish`, `finish`) have been emitted. Note that listening on any end-ish event will immediateyl re-emit it if it has already been emitted. * `writable` Whether the stream is writable. Default `true`. Set to `false` when `end()` * `readable` Whether the stream is readable. Default `true`. * `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written to the stream that have not yet been emitted. (It's probably a bad idea to mess with this.) * `pipes` A [yallist](http://npm.im/yallist) linked list of streams that this stream is piping into. (It's probably a bad idea to mess with this.) * `destroyed` A getter that indicates whether the stream was destroyed. * `paused` True if the stream has been explicitly paused, otherwise false. * `objectMode` Indicates whether the stream is in `objectMode`. Once set to `true`, it cannot be set to `false`. ### Events * `data` Emitted when there's data to read. Argument is the data to read. This is never emitted while not flowing. If a listener is attached, that will resume the stream. * `end` Emitted when there's no more data to read. This will be emitted immediately for empty streams when `end()` is called. If a listener is attached, and `end` was already emitted, then it will be emitted again. All listeners are removed when `end` is emitted. * `prefinish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'end'`. * `finish` An end-ish event that follows the same logic as `end` and is emitted in the same conditions where `end` is emitted. Emitted after `'prefinish'`. * `close` An indication that an underlying resource has been released. Minipass does not emit this event, but will defer it until after `end` has been emitted, since it throws off some stream libraries otherwise. * `drain` Emitted when the internal buffer empties, and it is again suitable to `write()` into the stream. * `readable` Emitted when data is buffered and ready to be read by a consumer. * `resume` Emitted when stream changes state from buffering to flowing mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event listener is added.) ### Static Methods * `Minipass.isStream(stream)` Returns `true` if the argument is a stream, and false otherwise. To be considered a stream, the object must be either an instance of Minipass, or an EventEmitter that has either a `pipe()` method, or both `write()` and `end()` methods. (Pretty much any stream in node-land will return `true` for this.) ## EXAMPLES Here are some examples of things you can do with Minipass streams. ### simple "are you done yet" promise ```js mp.promise().then(() => { // stream is finished }, er => { // stream emitted an error }) ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### collecting into a single blob This is a bit slower because it concatenates the data into one chunk for you, but if you're going to do it yourself anyway, it's convenient this way: ```js mp.concat().then(onebigchunk => { // onebigchunk is a string if the stream // had an encoding set, or a buffer otherwise. }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i-- > 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` ### subclass that `console.log()`s everything written into it ```js class Logger extends Minipass { write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } } someSource.pipe(new Logger()).pipe(someDest) ``` ### same thing, but using an inline anonymous class ```js // js classes are fun someSource .pipe(new (class extends Minipass { emit (ev, ...data) { // let's also log events, because debugging some weird thing console.log('EMIT', ev) return super.emit(ev, ...data) } write (chunk, encoding, callback) { console.log('WRITE', chunk, encoding) return super.write(chunk, encoding, callback) } end (chunk, encoding, callback) { console.log('END', chunk, encoding) return super.end(chunk, encoding, callback) } })) .pipe(someDest) ``` ### subclass that defers 'end' for some reason ```js class SlowEnd extends Minipass { emit (ev, ...args) { if (ev === 'end') { console.log('going to end, hold on a sec') setTimeout(() => { console.log('ok, ready to end now') super.emit('end', ...args) }, 100) } else { return super.emit(ev, ...args) } } } ``` ### transform that creates newline-delimited JSON ```js class NDJSONEncode extends Minipass { write (obj, cb) { try { // JSON.stringify can throw, emit an error on that return super.write(JSON.stringify(obj) + '\n', 'utf8', cb) } catch (er) { this.emit('error', er) } } end (obj, cb) { if (typeof obj === 'function') { cb = obj obj = undefined } if (obj !== undefined) { this.write(obj) } return super.end(cb) } } ``` ### transform that parses newline-delimited JSON ```js class NDJSONDecode extends Minipass { constructor (options) { // always be in object mode, as far as Minipass is concerned super({ objectMode: true }) this._jsonBuffer = '' } write (chunk, encoding, cb) { if (typeof chunk === 'string' && typeof encoding === 'string' && encoding !== 'utf8') { chunk = Buffer.from(chunk, encoding).toString() } else if (Buffer.isBuffer(chunk)) chunk = chunk.toString() } if (typeof encoding === 'function') { cb = encoding } const jsonData = (this._jsonBuffer + chunk).split('\n') this._jsonBuffer = jsonData.pop() for (let i = 0; i < jsonData.length; i++) { try { // JSON.parse can throw, emit an error on that super.write(JSON.parse(jsonData[i])) } catch (er) { this.emit('error', er) continue } } if (cb) cb() } } ``` An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` # convert-source-map [![Build Status][ci-image]][ci-url] Converts a source-map from/to different formats and allows adding/changing properties. ```js var convert = require('convert-source-map'); var json = convert .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .toJSON(); var modified = convert .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .setProperty('sources', [ 'SRC/FOO.JS' ]) .toJSON(); console.log(json); console.log(modified); ``` ```json {"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"} {"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"} ``` ## API ### fromObject(obj) Returns source map converter from given object. ### fromJSON(json) Returns source map converter from given json string. ### fromBase64(base64) Returns source map converter from given base64 encoded json string. ### fromComment(comment) Returns source map converter from given base64 encoded json string prefixed with `//# sourceMappingURL=...`. ### fromMapFileComment(comment, mapFileDir) Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`. `filename` must point to a file that is found inside the `mapFileDir`. Most tools store this file right next to the generated file, i.e. the one containing the source map. ### fromSource(source) Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. ### fromMapFileSource(source, mapFileDir) Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. The sourcemap will be read from the map file found by parsing `# sourceMappingURL=file` comment. For more info see fromMapFileComment. ### toObject() Returns a copy of the underlying source map. ### toJSON([space]) Converts source map to json string. If `space` is given (optional), this will be passed to [JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the JSON string is generated. ### toBase64() Converts source map to base64 encoded json string. ### toComment([options]) Converts source map to an inline comment that can be appended to the source-file. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. ### addProperty(key, value) Adds given property to the source map. Throws an error if property already exists. ### setProperty(key, value) Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated. ### getProperty(key) Gets given property of the source map. ### removeComments(src) Returns `src` with all source map comments removed ### removeMapFileComments(src) Returns `src` with all source map comments pointing to map files removed. ### commentRegex Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments. ### mapFileCommentRegex Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files. ### generateMapFileComment(file, [options]) Returns a comment that links to an external source map via `file`. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. [ci-url]: https://github.com/thlorenz/convert-source-map/actions?query=workflow:ci [ci-image]: https://img.shields.io/github/workflow/status/thlorenz/convert-source-map/CI?style=flat-square Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). # `resolve-alpn` [![Node CI](https://github.com/szmarczak/resolve-alpn/workflows/Node%20CI/badge.svg)](https://github.com/szmarczak/resolve-alpn/actions) [![codecov](https://codecov.io/gh/szmarczak/resolve-alpn/branch/master/graph/badge.svg)](https://codecov.io/gh/szmarczak/resolve-alpn) ## API ### resolveALPN(options, connect = tls.connect) Returns an object with an `alpnProtocol` property. The `socket` property may be also present. ```js const result = await resolveALPN({ host: 'nghttp2.org', port: 443, ALPNProtocols: ['h2', 'http/1.1'], servername: 'nghttp2.org' }); console.log(result); // {alpnProtocol: 'h2'} ``` **Note:** While the `servername` option is not required in this case, many other servers do. It's best practice to set it anyway. **Note:** If the socket times out, the promise will resolve and `result.timeout` will be set to `true`. #### options Same as [TLS options](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). ##### options.resolveSocket By default, the socket gets destroyed and the promise resolves.<br> If you set this to true, it will return the socket in a `socket` property. ```js const result = await resolveALPN({ host: 'nghttp2.org', port: 443, ALPNProtocols: ['h2', 'http/1.1'], servername: 'nghttp2.org', resolveSocket: true }); console.log(result); // {alpnProtocol: 'h2', socket: tls.TLSSocket} // Remember to destroy the socket if you don't use it! result.socket.destroy(); ``` #### connect Type: `Function<TLSSocket> | AsyncFunction<TLSSocket>`\ Default: [`tls.connect`](https://nodejs.org/dist/latest-v16.x/docs/api/tls.html#tls_tls_connect_options_callback) **Note:** No matter which function is used (synchronous or asynchronous), it **must** accept a `callback` function as a second argument. The `callback` function gets executed when the socket has successfully connected. ## License MIT <p align="center"> <a href="https://rollupjs.org/"><img src="https://rollupjs.org/logo.svg" width="150" /></a> </p> <p align="center"> <a href="https://www.npmjs.com/package/rollup"> <img src="https://img.shields.io/npm/v/rollup.svg" alt="npm version" > </a> <a href="https://packagephobia.now.sh/result?p=rollup"> <img src="https://packagephobia.now.sh/badge?p=rollup" alt="install size" > </a> <a href="https://codecov.io/gh/rollup/rollup"> <img src="https://codecov.io/gh/rollup/rollup/graph/badge.svg" alt="code coverage" > </a> <a href="#backers" alt="sponsors on Open Collective"> <img src="https://opencollective.com/rollup/backers/badge.svg" alt="backers" > </a> <a href="#sponsors" alt="Sponsors on Open Collective"> <img src="https://opencollective.com/rollup/sponsors/badge.svg" alt="sponsors" > </a> <a href="https://github.com/rollup/rollup/blob/master/LICENSE.md"> <img src="https://img.shields.io/npm/l/rollup.svg" alt="license"> </a> <a href='https://is.gd/rollup_chat?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge'> <img src='https://img.shields.io/discord/466787075518365708?color=778cd1&label=chat' alt='Join the chat at https://is.gd/rollup_chat'> </a> </p> <h1 align="center">Rollup</h1> ## Overview Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. ## Quick Start Guide Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/#command-line-reference) with an optional configuration file or else through its [JavaScript API](https://rollupjs.org/guide/en/#javascript-api). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/). ### Commands These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. For browsers: ```bash # compile to a <script> containing a self-executing function rollup main.js --format iife --name "myBundle" --file bundle.js ``` For Node.js: ```bash # compile to a CommonJS module rollup main.js --format cjs --file bundle.js ``` For both browsers and Node.js: ```bash # UMD format requires a bundle name rollup main.js --format umd --name "myBundle" --file bundle.js ``` ## Why Developing software is usually easier if you break your project into smaller separate pieces, since that often removes unexpected interactions and dramatically reduces the complexity of the problems you'll need to solve, and simply writing smaller projects in the first place [isn't necessarily the answer](https://medium.com/@Rich_Harris/small-modules-it-s-not-quite-that-simple-3ca532d65de4). Unfortunately, JavaScript has not historically included this capability as a core feature in the language. This finally changed with ES modules support in JavaScript, which provides a syntax for importing and exporting functions and data so they can be shared between separate scripts. Most browsers and Node.js support ES modules. However, Node.js releases before 12.17 support ES modules only behind the `--experimental-modules` flag, and older browsers like Internet Explorer do not support ES modules at all. Rollup allows you to write your code using ES modules, and run your application even in environments that do not support ES modules natively. For environments that support them, Rollup can output optimized ES modules; for environments that don't, Rollup can compile your code to other formats such as CommonJS modules, AMD modules, and IIFE-style scripts. This means that you get to _write future-proof code_, and you also get the tremendous benefits of... ## Tree Shaking In addition to enabling the use of ES modules, Rollup also statically analyzes and optimizes the code you are importing, and will exclude anything that isn't actually used. This allows you to build on top of existing tools and modules without adding extra dependencies or bloating the size of your project. For example, with CommonJS, the _entire tool or library must be imported_. ```js // import the entire utils object with CommonJS var utils = require('utils'); var query = 'Rollup'; // use the ajax method of the utils object utils.ajax('https://api.example.com?search=' + query).then(handleResponse); ``` But with ES modules, instead of importing the whole `utils` object, we can just import the one `ajax` function we need: ```js // import the ajax function with an ES import statement import { ajax } from 'utils'; var query = 'Rollup'; // call the ajax function ajax('https://api.example.com?search=' + query).then(handleResponse); ``` Because Rollup includes the bare minimum, it results in lighter, faster, and less complicated libraries and applications. Since this approach is based on explicit `import` and `export` statements, it is vastly more effective than simply running an automated minifier to detect unused variables in the compiled output code. ## Compatibility ### Importing CommonJS Rollup can import existing CommonJS modules [through a plugin](https://github.com/rollup/plugins/tree/master/packages/commonjs). ### Publishing ES Modules To make sure your ES modules are immediately usable by tools that work with CommonJS such as Node.js and webpack, you can use Rollup to compile to UMD or CommonJS format, and then point to that compiled version with the `main` property in your `package.json` file. If your `package.json` file also has a `module` field, ES-module-aware tools like Rollup and [webpack](https://webpack.js.org/) will [import the ES module version](https://github.com/rollup/rollup/wiki/pkg.module) directly. ## Contributors This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. <a href="https://github.com/rollup/rollup/graphs/contributors"><img src="https://opencollective.com/rollup/contributors.svg?width=890" /></a> ## Backers Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/rollup#backer)] <a href="https://opencollective.com/rollup#backers" target="_blank"><img src="https://opencollective.com/rollup/backers.svg?width=890"></a> ## Sponsors Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/rollup#sponsor)] <a href="https://opencollective.com/rollup/sponsor/0/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/1/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/2/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/3/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/4/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/5/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/6/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/7/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/8/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/rollup/sponsor/9/website" target="_blank"><img src="https://opencollective.com/rollup/sponsor/9/avatar.svg"></a> ## License [MIT](https://github.com/rollup/rollup/blob/master/LICENSE.md) wide-align ---------- A wide-character aware text alignment function for use in terminals / on the console. ### Usage ``` var align = require('wide-align') // Note that if you view this on a unicode console, all of the slashes are // aligned. This is because on a console, all narrow characters are // an en wide and all wide characters are an em. In browsers, this isn't // held to and wide characters like "古" can be less than two narrow // characters even with a fixed width font. console.log(align.center('abc', 10)) // ' abc ' console.log(align.center('古古古', 10)) // ' 古古古 ' console.log(align.left('abc', 10)) // 'abc ' console.log(align.left('古古古', 10)) // '古古古 ' console.log(align.right('abc', 10)) // ' abc' console.log(align.right('古古古', 10)) // ' 古古古' ``` ### Functions #### `align.center(str, length)` → `str` Returns *str* with spaces added to both sides such that that it is *length* chars long and centered in the spaces. #### `align.left(str, length)` → `str` Returns *str* with spaces to the right such that it is *length* chars long. ### `align.right(str, length)` → `str` Returns *str* with spaces to the left such that it is *length* chars long. ### Origins These functions were originally taken from [cliui](https://npmjs.com/package/cliui). Changes include switching to the MUCH faster pad generation function from [lodash](https://npmjs.com/package/lodash), making center alignment pad both sides and adding left alignment. # Statuses [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP status utility for node. This module provides a list of status codes and messages sourced from a few different projects: * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) * The [Node.js project](https://nodejs.org/) * The [NGINX project](https://www.nginx.com/) * The [Apache HTTP Server project](https://httpd.apache.org/) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install statuses ``` ## API <!-- eslint-disable no-unused-vars --> ```js var status = require('statuses') ``` ### var code = status(Integer || String) If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. <!-- eslint-disable no-undef --> ```js status(403) // => 403 status('403') // => 403 status('forbidden') // => 403 status('Forbidden') // => 403 status(306) // throws, as it's not supported by node.js ``` ### status.STATUS_CODES Returns an object which maps status codes to status messages, in the same format as the [Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). ### status.codes Returns an array of all the status codes as `Integer`s. ### var msg = status[code] Map of `code` to `status message`. `undefined` for invalid `code`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status[404] // => 'Not Found' ``` ### var code = status[msg] Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status['not found'] // => 404 status['Not Found'] // => 404 ``` ### status.redirect[code] Returns `true` if a status code is a valid redirect status. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.redirect[200] // => undefined status.redirect[301] // => true ``` ### status.empty[code] Returns `true` if a status code expects an empty body. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.empty[200] // => undefined status.empty[204] // => true status.empty[304] // => true ``` ### status.retry[code] Returns `true` if you should retry the rest. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.retry[501] // => undefined status.retry[503] // => true ``` [npm-image]: https://img.shields.io/npm/v/statuses.svg [npm-url]: https://npmjs.org/package/statuses [node-version-image]: https://img.shields.io/node/v/statuses.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/statuses.svg [travis-url]: https://travis-ci.org/jshttp/statuses [coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg [coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master [downloads-image]: https://img.shields.io/npm/dm/statuses.svg [downloads-url]: https://npmjs.org/package/statuses # to-regex-range [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ``` <details> <summary><strong>What does this do?</strong></summary> <br> This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js const toRegexRange = require('to-regex-range'); const regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). <br> </details> <details> <summary><strong>Why use this library?</strong></summary> <br> ### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 07, 2019, this library runs [>1m test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are correct. Tests run in ~280ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Optimized Generated regular expressions are optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once <br> </details> ## Usage Add this library to your javascript application with the following line of code ```js const toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js const source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] const regex = new RegExp(`^${source}$`); console.log(regex.test('14')); //=> false console.log(regex.test('50')); //=> true console.log(regex.test('94')); //=> true console.log(regex.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', { capture: true })); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', { shorthand: true })); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option relaxes matching for leading zeros when when ranges are zero-padded. ```js const source = toRegexRange('-0010', '0010'); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> true console.log(regex.test('-010')); //=> true console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> true console.log(regex.test('010')); //=> true console.log(regex.test('0010')); //=> true ``` When `relaxZeros` is false, matching is strict: ```js const source = toRegexRange('-0010', '0010', { relaxZeros: false }); const regex = new RegExp(`^${source}$`); console.log(regex.test('-10')); //=> false console.log(regex.test('-010')); //=> false console.log(regex.test('-0010')); //=> true console.log(regex.test('10')); //=> false console.log(regex.test('010')); //=> false console.log(regex.test('0010')); //=> true ``` ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange(-10, 10)` | `-[1-9]\|-?10\|[0-9]` | _132μs_ | | `toRegexRange(-100, -10)` | `-1[0-9]\|-[2-9][0-9]\|-100` | _50μs_ | | `toRegexRange(-100, 100)` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _42μs_ | | `toRegexRange(001, 100)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|100` | _109μs_ | | `toRegexRange(001, 555)` | `0{0,2}[1-9]\|0?[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _51μs_ | | `toRegexRange(0010, 1000)` | `0{0,2}1[0-9]\|0{0,2}[2-9][0-9]\|0?[1-9][0-9]{2}\|1000` | _31μs_ | | `toRegexRange(1, 50)` | `[1-9]\|[1-4][0-9]\|50` | _24μs_ | | `toRegexRange(1, 55)` | `[1-9]\|[1-4][0-9]\|5[0-5]` | _23μs_ | | `toRegexRange(1, 555)` | `[1-9]\|[1-9][0-9]\|[1-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _30μs_ | | `toRegexRange(1, 5555)` | `[1-9]\|[1-9][0-9]{1,2}\|[1-4][0-9]{3}\|5[0-4][0-9]{2}\|55[0-4][0-9]\|555[0-5]` | _43μs_ | | `toRegexRange(111, 555)` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _38μs_ | | `toRegexRange(29, 51)` | `29\|[34][0-9]\|5[01]` | _24μs_ | | `toRegexRange(31, 877)` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _32μs_ | | `toRegexRange(5, 5)` | `5` | _8μs_ | | `toRegexRange(5, 6)` | `5\|6` | _11μs_ | | `toRegexRange(1, 2)` | `1\|2` | _6μs_ | | `toRegexRange(1, 5)` | `[1-5]` | _15μs_ | | `toRegexRange(1, 10)` | `[1-9]\|10` | _22μs_ | | `toRegexRange(1, 100)` | `[1-9]\|[1-9][0-9]\|100` | _25μs_ | | `toRegexRange(1, 1000)` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _31μs_ | | `toRegexRange(1, 10000)` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _34μs_ | | `toRegexRange(1, 100000)` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _36μs_ | | `toRegexRange(1, 1000000)` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _42μs_ | | `toRegexRange(1, 10000000)` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _42μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 63 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [doowb](https://github.com/doowb) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 07, 2019._ # rc The non-configurable configuration loader for lazy people. ## Usage The only option is to pass rc the name of your app, and your default configuration. ```javascript var conf = require('rc')(appname, { //defaults go here. port: 2468, //defaults which are objects will be merged, not replaced views: { engine: 'jade' } }); ``` `rc` will return your configuration options merged with the defaults you specify. If you pass in a predefined defaults object, it will be mutated: ```javascript var conf = {}; require('rc')(appname, conf); ``` If `rc` finds any config files for your app, the returned config object will have a `configs` array containing their paths: ```javascript var appCfg = require('rc')(appname, conf); appCfg.configs[0] // /etc/appnamerc appCfg.configs[1] // /home/dominictarr/.config/appname appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] ``` ## Standards Given your application name (`appname`), rc will look in all the obvious places for configuration. * command line arguments, parsed by minimist _(e.g. `--foo baz`, also nested: `--foo.bar=baz`)_ * environment variables prefixed with `${appname}_` * or use "\_\_" to indicate nested properties <br/> _(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ * if you passed an option `--config file` then from that file * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. * `$HOME/.${appname}rc` * `$HOME/.${appname}/config` * `$HOME/.config/${appname}` * `$HOME/.config/${appname}/config` * `/etc/${appname}rc` * `/etc/${appname}/config` * the defaults object you passed in. All configuration sources that were found will be flattened into one object, so that sources **earlier** in this list override later ones. ## Configuration File Formats Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. **No** file extension (`.json` or `.ini`) should be used. The example configurations below are equivalent: #### Formatted as `ini` ``` ; You can include comments in `ini` format if you want. dependsOn=0.10.0 ; `rc` has built-in support for ini sections, see? [commands] www = ./commands/www console = ./commands/repl ; You can even do nested sections [generators.options] engine = ejs [generators.modules] new = generate-new engine = generate-backend ``` #### Formatted as `json` ```javascript { // You can even comment your JSON, if you want "dependsOn": "0.10.0", "commands": { "www": "./commands/www", "console": "./commands/repl" }, "generators": { "options": { "engine": "ejs" }, "modules": { "new": "generate-new", "backend": "generate-backend" } } } ``` Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). > Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. To ensure that string representations of booleans and numbers are always converted into their proper types (especially useful if you intend to do strict `===` comparisons), consider using a module such as [parse-strings-in-object](https://github.com/anselanza/parse-strings-in-object) to wrap the config object returned from rc. ## Simple example demonstrating precedence Assume you have an application like this (notice the hard-coded defaults passed to rc): ``` const conf = require('rc')('myapp', { port: 12345, mode: 'test' }); console.log(JSON.stringify(conf, null, 2)); ``` You also have a file `config.json`, with these contents: ``` { "port": 9000, "foo": "from config json", "something": "else" } ``` And a file `.myapprc` in the same folder, with these contents: ``` { "port": "3001", "foo": "bar" } ``` Here is the expected output from various commands: `node .` ``` { "port": "3001", "mode": "test", "foo": "bar", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Default `mode` from hard-coded object is retained, but port is overridden by `.myapprc` file (automatically found based on appname match), and `foo` is added.* `node . --foo baz` ``` { "port": "3001", "mode": "test", "foo": "baz", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Same result as above but `foo` is overridden because command-line arguments take precedence over `.myapprc` file.* `node . --foo barbar --config config.json` ``` { "port": 9000, "mode": "test", "foo": "barbar", "something": "else", "_": [], "config": "config.json", "configs": [ "/Users/stephen/repos/conftest/.myapprc", "config.json" ] } ``` *Now the `port` comes from the `config.json` file specified (overriding the value from `.myapprc`), and `foo` value is overriden by command-line despite also being specified in the `config.json` file.* ## Advanced Usage #### Pass in your own `argv` You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). ```javascript require('rc')(appname, defaults, customArgvParser); ``` ## Pass in your own parser If you have a special need to use a non-standard parser, you can do so by passing in the parser as the 4th argument. (leave the 3rd as null to get the default args parser) ```javascript require('rc')(appname, defaults, null, parser); ``` This may also be used to force a more strict format, such as strict, valid JSON only. ## Note on Performance `rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) ## License Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 # toidentifier [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][github-actions-ci-image]][github-actions-ci-url] [![Test Coverage][codecov-image]][codecov-url] > Convert a string of words to a JavaScript identifier ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install toidentifier ``` ## Example ```js var toIdentifier = require('toidentifier') console.log(toIdentifier('Bad Request')) // => "BadRequest" ``` ## API This CommonJS module exports a single default function: `toIdentifier`. ### toIdentifier(string) Given a string as the argument, it will be transformed according to the following rules and the new string will be returned: 1. Split into words separated by space characters (`0x20`). 2. Upper case the first character of each word. 3. Join the words together with no separator. 4. Remove all non-word (`[0-9a-z_]`) characters. ## License [MIT](LICENSE) [codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg [codecov-url]: https://codecov.io/gh/component/toidentifier [downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg [downloads-url]: https://npmjs.org/package/toidentifier [github-actions-ci-image]: https://img.shields.io/github/workflow/status/component/toidentifier/ci/master?label=ci [github-actions-ci-url]: https://github.com/component/toidentifier?query=workflow%3Aci [npm-image]: https://img.shields.io/npm/v/toidentifier.svg [npm-url]: https://npmjs.org/package/toidentifier ## [npm]: https://www.npmjs.com/ [yarn]: https://yarnpkg.com/ # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ci-info Get details about the current Continuous Integration environment. Please [open an issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md) if your CI server isn't properly detected :) [![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info) [![Build status](https://travis-ci.org/watson/ci-info.svg?branch=master)](https://travis-ci.org/watson/ci-info) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ```bash npm install ci-info --save ``` ## Usage ```js var ci = require('ci-info') if (ci.isCI) { console.log('The name of the CI server is:', ci.name) } else { console.log('This program is not running on a CI server') } ``` ## Supported CI tools Officially supported CI servers: | Name | Constant | isPR | |------|----------|------| | [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 | | [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ | | [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ | | [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 | | [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ | | [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ | | [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ | | [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ | | [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ | | [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ | | [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 | | [Drone](https://drone.io) | `ci.DRONE` | ✅ | | [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 | | [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | 🚫 | | [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 | | [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 | | [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ | | [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 | | [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ | | [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ | | [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ | | [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ | | [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ | | [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 | | [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 | | [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 | | [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ | ## API ### `ci.name` Returns a string containing name of the CI server the code is running on. If CI server is not detected, it returns `null`. Don't depend on the value of this string not to change for a specific vendor. If you find your self writing `ci.name === 'Travis CI'`, you most likely want to use `ci.TRAVIS` instead. ### `ci.isCI` Returns a boolean. Will be `true` if the code is running on a CI server, otherwise `false`. Some CI servers not listed here might still trigger the `ci.isCI` boolean to be set to `true` if they use certain vendor neutral environment variables. In those cases `ci.name` will be `null` and no vendor specific boolean will be set to `true`. ### `ci.isPR` Returns a boolean if PR detection is supported for the current CI server. Will be `true` if a PR is being tested, otherwise `false`. If PR detection is not supported for the current CI server, the value will be `null`. ### `ci.<VENDOR-CONSTANT>` A vendor specific boolean constant is exposed for each support CI vendor. A constant will be `true` if the code is determined to run on the given CI server, otherwise `false`. Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a complete list, see the support table above. Deprecated vendor constants that will be removed in the next major release: - `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO` ## License [MIT](LICENSE) # axios [![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios) [![CDNJS](https://img.shields.io/cdnjs/v/axios.svg?style=flat-square)](https://cdnjs.com/libraries/axios) ![Build status](https://github.com/axios/axios/actions/workflows/ci.yml/badge.svg) [![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/axios/axios) [![code coverage](https://img.shields.io/coveralls/mzabriskie/axios.svg?style=flat-square)](https://coveralls.io/r/mzabriskie/axios) [![install size](https://packagephobia.now.sh/badge?p=axios)](https://packagephobia.now.sh/result?p=axios) [![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](http://npm-stat.com/charts.html?package=axios) [![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios) [![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios) [![Known Vulnerabilities](https://snyk.io/test/npm/axios/badge.svg)](https://snyk.io/test/npm/axios) Promise based HTTP client for the browser and node.js > New axios docs website: [click here](https://axios-http.com/) ## Table of Contents - [Features](#features) - [Browser Support](#browser-support) - [Installing](#installing) - [Example](#example) - [Axios API](#axios-api) - [Request method aliases](#request-method-aliases) - [Concurrency 👎](#concurrency-deprecated) - [Creating an instance](#creating-an-instance) - [Instance methods](#instance-methods) - [Request Config](#request-config) - [Response Schema](#response-schema) - [Config Defaults](#config-defaults) - [Global axios defaults](#global-axios-defaults) - [Custom instance defaults](#custom-instance-defaults) - [Config order of precedence](#config-order-of-precedence) - [Interceptors](#interceptors) - [Multiple Interceptors](#multiple-interceptors) - [Handling Errors](#handling-errors) - [Cancellation](#cancellation) - [AbortController](#abortcontroller) - [CancelToken 👎](#canceltoken-deprecated) - [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format) - [Browser](#browser) - [Node.js](#nodejs) - [Query string](#query-string) - [Form data](#form-data) - [Automatic serialization](#-automatic-serialization) - [Manual FormData passing](#manual-formdata-passing) - [Semver](#semver) - [Promises](#promises) - [TypeScript](#typescript) - [Resources](#resources) - [Credits](#credits) - [License](#license) ## Features - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser - Make [http](http://nodejs.org/api/http.html) requests from node.js - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API - Intercept request and response - Transform request and response data - Cancel requests - Automatic transforms for JSON data - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) ## Browser Support ![Chrome](https://raw.github.com/alrra/browser-logos/master/src/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/src/firefox/firefox_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/src/safari/safari_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/src/opera/opera_48x48.png) | ![Edge](https://raw.github.com/alrra/browser-logos/master/src/edge/edge_48x48.png) | ![IE](https://raw.github.com/alrra/browser-logos/master/src/archive/internet-explorer_9-11/internet-explorer_9-11_48x48.png) | --- | --- | --- | --- | --- | --- | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ | [![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios) ## Installing Using npm: ```bash $ npm install axios ``` Using bower: ```bash $ bower install axios ``` Using yarn: ```bash $ yarn add axios ``` Using jsDelivr CDN: ```html <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> ``` Using unpkg CDN: ```html <script src="https://unpkg.com/axios/dist/axios.min.js"></script> ``` ## Example ### note: CommonJS usage In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: ```js const axios = require('axios').default; // axios.<method> will now provide autocomplete and parameter typings ``` Performing a `GET` request ```js const axios = require('axios').default; // Make a request for a user with a given ID axios.get('/user?ID=12345') .then(function (response) { // handle success console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); // Optionally the request above could also be done as axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed }); // Want to use async/await? Add the `async` keyword to your outer function/method. async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } } ``` > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet > Explorer and older browsers, so use with caution. Performing a `POST` request ```js axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` Performing multiple concurrent requests ```js function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } Promise.all([getUserAccount(), getUserPermissions()]) .then(function (results) { const acct = results[0]; const perm = results[1]; }); ``` ## axios API Requests can be made by passing the relevant config to `axios`. ##### axios(config) ```js // Send a POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); ``` ```js // GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); ``` ##### axios(url[, config]) ```js // Send a GET request (default method) axios('/user/12345'); ``` ### Request method aliases For convenience, aliases have been provided for all common request methods. ##### axios.request(config) ##### axios.get(url[, config]) ##### axios.delete(url[, config]) ##### axios.head(url[, config]) ##### axios.options(url[, config]) ##### axios.post(url[, data[, config]]) ##### axios.put(url[, data[, config]]) ##### axios.patch(url[, data[, config]]) ###### NOTE When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. ### Concurrency (Deprecated) Please use `Promise.all` to replace the below functions. Helper functions for dealing with concurrent requests. axios.all(iterable) axios.spread(callback) ### Creating an instance You can create a new instance of axios with a custom config. ##### axios.create([config]) ```js const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); ``` ### Instance methods The available instance methods are listed below. The specified config will be merged with the instance config. ##### axios#request(config) ##### axios#get(url[, config]) ##### axios#delete(url[, config]) ##### axios#head(url[, config]) ##### axios#options(url[, config]) ##### axios#post(url[, data[, config]]) ##### axios#put(url[, data[, config]]) ##### axios#patch(url[, data[, config]]) ##### axios#getUri([config]) ## Request Config These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified. ```js { // `url` is the server URL that will be used for the request url: '/user', // `method` is the request method to be used when making the request method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute. // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs // to methods of that instance. baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE' // The last function in the array must return a string or an instance of Buffer, ArrayBuffer, // FormData or Stream // You may modify the headers object. transformRequest: [function (data, headers) { // Do whatever you want to transform the data return data; }], // `transformResponse` allows changes to the response data to be made before // it is passed to then/catch transformResponse: [function (data) { // Do whatever you want to transform the data return data; }], // `headers` are custom headers to be sent headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request // Must be a plain object or a URLSearchParams object params: { ID: 12345 }, // `paramsSerializer` is an optional function in charge of serializing `params` // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function (params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` is the data to be sent as the request body // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH' // When no `transformRequest` is set, must be of one of the following types: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream, Buffer data: { firstName: 'Fred' }, // syntax alternative to send data into the body // method post // only the value is sent, not the key data: 'Country=Brasil&City=Belo Horizonte', // `timeout` specifies the number of milliseconds before the request times out. // If the request takes longer than `timeout`, the request will be aborted. timeout: 1000, // default is `0` (no timeout) // `withCredentials` indicates whether or not cross-site Access-Control requests // should be made using credentials withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier. // Return a promise and supply a valid response (see lib/adapters/README.md). adapter: function (config) { /* ... */ }, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials. // This will set an `Authorization` header, overwriting any existing // `Authorization` custom headers you have set using `headers`. // Please note that only HTTP Basic auth is configurable through this parameter. // For Bearer tokens and such, use `Authorization` custom headers instead. auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` indicates the type of data that the server will respond with // options are: 'arraybuffer', 'document', 'json', 'text', 'stream' // browser only: 'blob' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses (Node.js only) // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` allows handling of progress events for uploads // browser only onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` allows handling of progress events for downloads // browser only onDownloadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js maxContentLength: 2000, // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed maxBodyLength: 2000, // `validateStatus` defines whether to resolve or reject the promise for a given // HTTP response status code. If `validateStatus` returns `true` (or is set to `null` // or `undefined`), the promise will be resolved; otherwise, the promise will be // rejected. validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` defines the maximum number of redirects to follow in node.js. // If set to 0, no redirects will be followed. maxRedirects: 21, // default // `beforeRedirect` defines a function that will be called before redirect. // Use this to adjust the request options upon redirecting, // to inspect the latest response headers, // or to cancel the request by throwing an error // If maxRedirects is set to 0, `beforeRedirect` is not used. beforeRedirect: (options, { headers }) => { if (options.hostname === "example.com") { options.auth = "user:password"; } }; // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http // and https requests, respectively, in node.js. This allows options to be added like // `keepAlive` that are not enabled by default. httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // `proxy` defines the hostname, port, and protocol of the proxy server. // You can also define your proxy using the conventional `http_proxy` and // `https_proxy` environment variables. If you are using environment variables // for your proxy configuration, you can also define a `no_proxy` environment // variable as a comma-separated list of domains that should not be proxied. // Use `false` to disable proxies, ignoring environment variables. // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and // supplies credentials. // This will set an `Proxy-Authorization` header, overwriting any existing // `Proxy-Authorization` custom headers you have set using `headers`. // If the proxy server uses HTTPS, then you must set the protocol to `https`. proxy: { protocol: 'https', host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` specifies a cancel token that can be used to cancel the request // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }), // an alternative way to cancel Axios requests using AbortController signal: new AbortController().signal, // `decompress` indicates whether or not the response body should be decompressed // automatically. If set to `true` will also remove the 'content-encoding' header // from the responses objects of all decompressed responses // - Node only (XHR cannot turn off decompression) decompress: true // default // `insecureHTTPParser` boolean. // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers. // This may allow interoperability with non-conformant HTTP implementations. // Using the insecure parser should be avoided. // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none insecureHTTPParser: undefined // default // transitional options for backward compatibility that may be removed in the newer versions transitional: { // silent JSON parsing mode // `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour) // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json') silentJSONParsing: true, // default value for the current Axios version // try to parse the response string as JSON even if `responseType` is not 'json' forcedJSONParsing: true, // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts clarifyTimeoutError: false, }, env: { // The FormData class to be used to automatically serialize the payload into a FormData object FormData: window?.FormData || global?.FormData } } ``` ## Response Schema The response for a request contains the following information. ```js { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the HTTP headers that the server responded with // All header names are lower cased and can be accessed using the bracket notation. // Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } ``` When using `then`, you will receive the response as follows: ```js axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); ``` When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section. ## Config Defaults You can specify config defaults that will be applied to every request. ### Global axios defaults ```js axios.defaults.baseURL = 'https://api.example.com'; // Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them. // See below for an example using Custom instance defaults instead. axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; ``` ### Custom instance defaults ```js // Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; ``` ### Config order of precedence Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. ```js // Create an instance using the config defaults provided by the library // At this point the timeout config value is `0` as is the default for the library const instance = axios.create(); // Override timeout default for the library // Now all requests using this instance will wait 2.5 seconds before timing out instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time instance.get('/longRequest', { timeout: 5000 }); ``` ## Interceptors You can intercept requests or responses before they are handled by `then` or `catch`. ```js // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error return Promise.reject(error); }); ``` If you need to remove an interceptor later you can. ```js const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); ``` You can add interceptors to a custom instance of axios. ```js const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); ``` When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay in the execution of your axios request when the main thread is blocked (a promise is created under the hood for the interceptor and your request gets put on the bottom of the call stack). If your request interceptors are synchronous you can add a flag to the options object that will tell axios to run the code synchronously and avoid any delays in request execution. ```js axios.interceptors.request.use(function (config) { config.headers.test = 'I am only a header!'; return config; }, null, { synchronous: true }); ``` If you want to execute a particular interceptor based on a runtime check, you can add a `runWhen` function to the options object. The interceptor will not be executed **if and only if** the return of `runWhen` is `false`. The function will be called with the config object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an asynchronous request interceptor that only needs to run at certain times. ```js function onGetCall(config) { return config.method === 'get'; } axios.interceptors.request.use(function (config) { config.headers.test = 'special get headers'; return config; }, null, { runWhen: onGetCall }); ``` ### Multiple Interceptors Given you add multiple response interceptors and when the response was fulfilled - then each interceptor is executed - then they are executed in the order they were added - then only the last interceptor's result is returned - then every interceptor receives the result of it's predecessor - and when the fulfillment-interceptor throws - then the following fulfillment-interceptor is not called - then the following rejection-interceptor is called - once caught, another following fulfill-interceptor is called again (just like in a promise chain). Read [the interceptor tests](./test/specs/interceptors.spec.js) for seeing all this in code. ## Handling Errors ```js axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); ``` Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. ```js axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Resolve only if the status code is less than 500 } }) ``` Using `toJSON` you get an object with more information about the HTTP error. ```js axios.get('/user/12345') .catch(function (error) { console.log(error.toJSON()); }); ``` ## Cancellation ### AbortController Starting from `v0.22.0` Axios supports AbortController to cancel requests in fetch API way: ```js const controller = new AbortController(); axios.get('/foo/bar', { signal: controller.signal }).then(function(response) { //... }); // cancel the request controller.abort() ``` ### CancelToken `👎deprecated` You can also cancel a request using a *CancelToken*. > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). > This API is deprecated since v0.22.0 and shouldn't be used in new projects You can create a cancel token using the `CancelToken.source` factory as shown below: ```js const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/user/12345', { cancelToken: source.token }).catch(function (thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // handle error } }); axios.post('/user/12345', { name: 'new name' }, { cancelToken: source.token }) // cancel the request (the message parameter is optional) source.cancel('Operation canceled by the user.'); ``` You can also create a cancel token by passing an executor function to the `CancelToken` constructor: ```js const CancelToken = axios.CancelToken; let cancel; axios.get('/user/12345', { cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter cancel = c; }) }); // cancel the request cancel(); ``` > Note: you can cancel several requests with the same cancel token/abort controller. > If a cancellation token is already cancelled at the moment of starting an Axios request, then the request is cancelled immediately, without any attempts to make real request. > During the transition period, you can use both cancellation APIs, even for the same request: ## Using application/x-www-form-urlencoded format By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options. ### Browser In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows: ```js const params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params); ``` > Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment). Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library: ```js const qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 })); ``` Or in another way (ES6), ```js import qs from 'qs'; const data = { 'bar': 123 }; const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, data: qs.stringify(data), url, }; axios(options); ``` ### Node.js #### Query string In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows: ```js const querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' })); ``` or ['URLSearchParams'](https://nodejs.org/api/url.html#url_class_urlsearchparams) from ['url module'](https://nodejs.org/api/url.html) as follows: ```js const url = require('url'); const params = new url.URLSearchParams({ foo: 'bar' }); axios.post('http://something.com/', params.toString()); ``` You can also use the [`qs`](https://github.com/ljharb/qs) library. > NOTE: > The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case. #### Form data ##### 🆕 Automatic serialization Starting from `v0.27.0`, Axios supports automatic object serialization to a FormData object if the request `Content-Type` header is set to `multipart/form-data`. The following request will submit the data in a FormData format (Browser & Node.js): ```js import axios from 'axios'; axios.post('https://httpbin.org/post', {x: 1}, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` In the `node.js` build, the ([`form-data`](https://github.com/form-data/form-data)) polyfill is used by default. You can overload the FormData class by setting the `env.FormData` config variable, but you probably won't need it in most cases: ```js const axios= require('axios'); var FormData = require('form-data'); axios.post('https://httpbin.org/post', {x: 1, buf: new Buffer(10)}, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios FormData serializer supports some special endings to perform the following operations: - `{}` - serialize the value with JSON.stringify - `[]` - unwrap the array like object as separate fields with the same key ```js const axios= require('axios'); axios.post('https://httpbin.org/post', { 'myObj{}': {x: 1, s: "foo"}, 'files[]': document.querySelector('#fileInput').files }, { headers: { 'Content-Type': 'multipart/form-data' } }).then(({data})=> console.log(data)); ``` Axios supports the following shortcut methods: `postForm`, `putForm`, `patchForm` which are just the corresponding http methods with a header preset: `Content-Type`: `multipart/form-data`. FileList object can be passed directly: ```js await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files) ``` All files will be sent with the same field names: `files[]`; ##### Manual FormData passing In node.js, you can use the [`form-data`](https://github.com/form-data/form-data) library as follows: ```js const FormData = require('form-data'); const form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); axios.post('https://example.com', form) ``` ## Semver Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. ## Promises axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). ## TypeScript axios includes [TypeScript](http://typescriptlang.org) definitions and a type guard for axios errors. ```typescript let user: User = null; try { const { data } = await axios.get('/user?ID=12345'); user = data.userDetails; } catch (error) { if (axios.isAxiosError(error)) { handleAxiosError(error); } else { handleUnexpectedError(error); } } ``` ## Online one-click setup You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online. [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/master/examples/server.js) ## Resources * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) ## Credits axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [AngularJS](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of AngularJS. ## License [MIT](LICENSE) # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # js-sha256 [![Build Status](https://travis-ci.org/emn178/js-sha256.svg?branch=master)](https://travis-ci.org/emn178/js-sha256) [![Coverage Status](https://coveralls.io/repos/emn178/js-sha256/badge.svg?branch=master)](https://coveralls.io/r/emn178/js-sha256?branch=master) [![CDNJS](https://img.shields.io/cdnjs/v/js-sha256.svg)](https://cdnjs.com/libraries/js-sha256/) [![NPM](https://nodei.co/npm/js-sha256.png?stars&downloads)](https://nodei.co/npm/js-sha256/) A simple SHA-256 / SHA-224 hash function for JavaScript supports UTF-8 encoding. ## Demo [SHA256 Online](http://emn178.github.io/online-tools/sha256.html) [SHA224 Online](http://emn178.github.io/online-tools/sha224.html) ## Download [Compress](https://raw.github.com/emn178/js-sha256/master/build/sha256.min.js) [Uncompress](https://raw.github.com/emn178/js-sha256/master/src/sha256.js) ## Installation You can also install js-sha256 by using Bower. bower install js-sha256 For node.js, you can use this command to install: npm install js-sha256 ## Usage You could use like this: ```JavaScript sha256('Message to hash'); sha224('Message to hash'); var hash = sha256.create(); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.update('Message to hash'); hash2.update('Message2 to hash'); hash2.array(); // HMAC sha256.hmac('key', 'Message to hash'); sha224.hmac('key', 'Message to hash'); var hash = sha256.hmac.create('key'); hash.update('Message to hash'); hash.hex(); var hash2 = sha256.hmac.update('key', 'Message to hash'); hash2.update('Message2 to hash'); hash2.array(); ``` If you use node.js, you should require the module first: ```JavaScript var sha256 = require('js-sha256'); ``` or ```JavaScript var sha256 = require('js-sha256').sha256; var sha224 = require('js-sha256').sha224; ``` It supports AMD: ```JavaScript require(['your/path/sha256.js'], function(sha256) { // ... }); ``` or TypeScript ```TypeScript import { sha256, sha224 } from 'js-sha256'; ``` ## Example ```JavaScript sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256('The quick brown fox jumps over the lazy dog'); // d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 sha256('The quick brown fox jumps over the lazy dog.'); // ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c sha224(''); // d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f sha224('The quick brown fox jumps over the lazy dog'); // 730e109bd7a8a32b1cb9d9a09aa2325d2430587ddbc0c38bad911525 sha224('The quick brown fox jumps over the lazy dog.'); // 619cba8e8e05826e9b8c519c0a5c68f4fb653e8a3d8aa04bb2c8cd4c // It also supports UTF-8 encoding sha256('中文'); // 72726d8818f693066ceb69afa364218b692e62ea92b385782363780f47529c21 sha224('中文'); // dfbab71afdf54388af4d55f8bd3de8c9b15e0eb916bf9125f4a959d4 // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer` input sha256([]); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256(new Uint8Array([211, 212])); // 182889f925ae4e5cc37118ded6ed87f7bdc7cab5ec5e78faef2e50048999473f // Different output sha256(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.hex(''); // e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sha256.array(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.digest(''); // [227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39, 174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85] sha256.arrayBuffer(''); // ArrayBuffer ``` ## License The project is released under the [MIT license](http://www.opensource.org/licenses/MIT). ## Contact The project's website is located at https://github.com/emn178/js-sha256 Author: Chen, Yi-Cyuan ([email protected]) # simple-concat [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/simple-concat/master.svg [travis-url]: https://travis-ci.org/feross/simple-concat [npm-image]: https://img.shields.io/npm/v/simple-concat.svg [npm-url]: https://npmjs.org/package/simple-concat [downloads-image]: https://img.shields.io/npm/dm/simple-concat.svg [downloads-url]: https://npmjs.org/package/simple-concat [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com ### Super-minimalist version of [`concat-stream`](https://github.com/maxogden/concat-stream). Less than 15 lines! ## install ``` npm install simple-concat ``` ## usage This example is longer than the implementation. ```js var s = new stream.PassThrough() concat(s, function (err, buf) { if (err) throw err console.error(buf) }) s.write('abc') setTimeout(function () { s.write('123') }, 10) setTimeout(function () { s.write('456') }, 20) setTimeout(function () { s.end('789') }, 30) ``` ## license MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). # bl *(BufferList)* [![Build Status](https://api.travis-ci.com/rvagg/bl.svg?branch=master)](https://travis-ci.com/rvagg/bl/) **A Node.js Buffer list collector, reader and streamer thingy.** [![NPM](https://nodei.co/npm/bl.svg)](https://nodei.co/npm/bl/) **bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. ```js const { BufferList } = require('bl') const bl = new BufferList() bl.append(Buffer.from('abcd')) bl.append(Buffer.from('efg')) bl.append('hi') // bl will also accept & convert Strings bl.append(Buffer.from('j')) bl.append(Buffer.from([ 0x3, 0x4 ])) console.log(bl.length) // 12 console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' console.log(bl.slice(3, 6).toString('ascii')) // 'def' console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' console.log(bl.indexOf('def')) // 3 console.log(bl.indexOf('asdf')) // -1 // or just use toString! console.log(bl.toString()) // 'abcdefghij\u0003\u0004' console.log(bl.toString('ascii', 3, 8)) // 'defgh' console.log(bl.toString('ascii', 5, 10)) // 'fghij' // other standard Buffer readables console.log(bl.readUInt16BE(10)) // 0x0304 console.log(bl.readUInt16LE(10)) // 0x0403 ``` Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: ```js const { BufferListStream } = require('bl') const fs = require('fs') fs.createReadStream('README.md') .pipe(BufferListStream((err, data) => { // note 'new' isn't strictly required // `data` is a complete Buffer object containing the full data console.log(data.toString()) })) ``` Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): ```js const hyperquest = require('hyperquest') const { BufferListStream } = require('bl') const url = 'https://raw.github.com/rvagg/bl/master/README.md' hyperquest(url).pipe(BufferListStream((err, data) => { console.log(data.toString()) })) ``` Or, use it as a readable stream to recompose a list of Buffers to an output source: ```js const { BufferListStream } = require('bl') const fs = require('fs') var bl = new BufferListStream() bl.append(Buffer.from('abcd')) bl.append(Buffer.from('efg')) bl.append(Buffer.from('hi')) bl.append(Buffer.from('j')) bl.pipe(fs.createWriteStream('gibberish.txt')) ``` ## API * <a href="#ctor"><code><b>new BufferList([ buf ])</b></code></a> * <a href="#isBufferList"><code><b>BufferList.isBufferList(obj)</b></code></a> * <a href="#length"><code>bl.<b>length</b></code></a> * <a href="#append"><code>bl.<b>append(buffer)</b></code></a> * <a href="#get"><code>bl.<b>get(index)</b></code></a> * <a href="#indexOf"><code>bl.<b>indexOf(value[, byteOffset][, encoding])</b></code></a> * <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a> * <a href="#shallowSlice"><code>bl.<b>shallowSlice([ start[, end ] ])</b></code></a> * <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a> * <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a> * <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a> * <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a> * <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a> * <a href="#ctorStream"><code><b>new BufferListStream([ callback ])</b></code></a> -------------------------------------------------------- <a name="ctor"></a> ### new BufferList([ Buffer | Buffer array | BufferList | BufferList array | String ]) No arguments are _required_ for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` objects. `new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: ```js const { BufferList } = require('bl') const bl = BufferList() // equivalent to: const { BufferList } = require('bl') const bl = new BufferList() ``` -------------------------------------------------------- <a name="isBufferList"></a> ### BufferList.isBufferList(obj) Determines if the passed object is a `BufferList`. It will return `true` if the passed object is an instance of `BufferList` **or** `BufferListStream` and `false` otherwise. N.B. this won't return `true` for `BufferList` or `BufferListStream` instances created by versions of this library before this static method was added. -------------------------------------------------------- <a name="length"></a> ### bl.length Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. -------------------------------------------------------- <a name="append"></a> ### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) `append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. -------------------------------------------------------- <a name="get"></a> ### bl.get(index) `get()` will return the byte at the specified index. -------------------------------------------------------- <a name="indexOf"></a> ### bl.indexOf(value[, byteOffset][, encoding]) `get()` will return the byte at the specified index. `indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. -------------------------------------------------------- <a name="slice"></a> ### bl.slice([ start, [ end ] ]) `slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. -------------------------------------------------------- <a name="shallowSlice"></a> ### bl.shallowSlice([ start, [ end ] ]) `shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. No copies will be performed. All buffers in the result share memory with the original list. -------------------------------------------------------- <a name="copy"></a> ### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) `copy()` 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`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. -------------------------------------------------------- <a name="duplicate"></a> ### bl.duplicate() `duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: ```js var bl = new BufferListStream() bl.append('hello') bl.append(' world') bl.append('\n') bl.duplicate().pipe(process.stdout, { end: false }) console.log(bl.toString()) ``` -------------------------------------------------------- <a name="consume"></a> ### bl.consume(bytes) `consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers&mdash;initial offsets will be calculated accordingly in order to give you a consistent view of the data. -------------------------------------------------------- <a name="toString"></a> ### bl.toString([encoding, [ start, [ end ]]]) `toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. -------------------------------------------------------- <a name="readXX"></a> ### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work. -------------------------------------------------------- <a name="ctorStream"></a> ### new BufferListStream([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) **BufferListStream** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **BufferListStream** instance. The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. `new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: ```js const { BufferListStream } = require('bl') const bl = BufferListStream() // equivalent to: const { BufferListStream } = require('bl') const bl = new BufferListStream() ``` N.B. For backwards compatibility reasons, `BufferListStream` is the **default** export when you `require('bl')`: ```js const { BufferListStream } = require('bl') // equivalent to: const BufferListStream = require('bl') ``` -------------------------------------------------------- ## Contributors **bl** is brought to you by the following hackers: * [Rod Vagg](https://github.com/rvagg) * [Matteo Collina](https://github.com/mcollina) * [Jarett Cruger](https://github.com/jcrugzz) <a name="license"></a> ## License &amp; copyright Copyright (c) 2013-2019 bl contributors (listed above). bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. # axios // env The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually. # graceful-fs graceful-fs functions as a drop-in replacement for the fs module, making various improvements. The improvements are meant to normalize behavior across different platforms and environments, and to make filesystem access more resilient to errors. ## Improvements over [fs module](https://nodejs.org/api/fs.html) * Queues up `open` and `readdir` calls, and retries them once something closes if there is an EMFILE error from too many file descriptors. * fixes `lchmod` for Node versions prior to 0.6.2. * implements `fs.lutimes` if possible. Otherwise it becomes a noop. * ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or `lchown` if the user isn't root. * makes `lchmod` and `lchown` become noops, if not available. * retries reading a file if `read` results in EAGAIN error. On Windows, it retries renaming a file for up to one second if `EACCESS` or `EPERM` error occurs, likely because antivirus software has locked the directory. ## USAGE ```javascript // use just like fs var fs = require('graceful-fs') // now go and do stuff with it... fs.readFile('some-file-or-whatever', (err, data) => { // Do stuff here. }) ``` ## Sync methods This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync methods. If you use sync methods which open file descriptors then you are responsible for dealing with any errors. This is a known limitation, not a bug. ## Global Patching If you want to patch the global fs module (or any other fs-like module) you can do this: ```javascript // Make sure to read the caveat below. var realFs = require('fs') var gracefulFs = require('graceful-fs') gracefulFs.gracefulify(realFs) ``` This should only ever be done at the top-level application layer, in order to delay on EMFILE errors from any fs-using dependencies. You should **not** do this in a library, because it can cause unexpected delays in other parts of the program. ## Changes This module is fairly stable at this point, and used by a lot of things. That being said, because it implements a subtle behavior change in a core part of the node API, even modest changes can be extremely breaking, and the versioning is thus biased towards bumping the major when in doubt. The main change between major versions has been switching between providing a fully-patched `fs` module vs monkey-patching the node core builtin, and the approach by which a non-monkey-patched `fs` was created. The goal is to trade `EMFILE` errors for slower fs operations. So, if you try to open a zillion files, rather than crashing, `open` operations will be queued up and wait for something else to `close`. There are advantages to each approach. Monkey-patching the fs means that no `EMFILE` errors can possibly occur anywhere in your application, because everything is using the same core `fs` module, which is patched. However, it can also obviously cause undesirable side-effects, especially if the module is loaded multiple times. Implementing a separate-but-identical patched `fs` module is more surgical (and doesn't run the risk of patching multiple times), but also imposes the challenge of keeping in sync with the core module. The current approach loads the `fs` module, and then creates a lookalike object that has all the same methods, except a few that are patched. It is safe to use in all versions of Node from 0.8 through 7.0. ### v4 * Do not monkey-patch the fs module. This module may now be used as a drop-in dep, and users can opt into monkey-patching the fs builtin if their app requires it. ### v3 * Monkey-patch fs, because the eval approach no longer works on recent node. * fixed possible type-error throw if rename fails on windows * verify that we *never* get EMFILE errors * Ignore ENOSYS from chmod/chown * clarify that graceful-fs must be used as a drop-in ### v2.1.0 * Use eval rather than monkey-patching fs. * readdir: Always sort the results * win32: requeue a file if error has an OK status ### v2.0 * A return to monkey patching * wrap process.cwd ### v1.1 * wrap readFile * Wrap fs.writeFile. * readdir protection * Don't clobber the fs builtin * Handle fs.read EAGAIN errors by trying again * Expose the curOpen counter * No-op lchown/lchmod if not implemented * fs.rename patch only for win32 * Patch fs.rename to handle AV software on Windows * Close #4 Chown should not fail on einval or eperm if non-root * Fix isaacs/fstream#1 Only wrap fs one time * Fix #3 Start at 1024 max files, then back off on EMFILE * lutimes that doens't blow up on Linux * A full on-rewrite using a queue instead of just swallowing the EMFILE error * Wrap Read/Write streams as well ### 1.0 * Update engines for node 0.6 * Be lstat-graceful on Windows * first # u3 - Utility Functions This lib contains utility functions for e3, dataflower and other projects. ## Documentation ### Installation ```bash npm install u3 ``` ```bash bower install u3 ``` #### Usage In this documentation I used the lib as follows: ```js var u3 = require("u3"), cache = u3.cache, eachCombination = u3.eachCombination; ``` ### Function wrappers #### cache The `cache(fn)` function caches the fn results, so by the next calls it will return the result of the first call. You can use different arguments, but they won't affect the return value. ```js var a = cache(function fn(x, y, z){ return x + y + z; }); console.log(a(1, 2, 3)); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` It is possible to cache a value too. ```js var a = cache(1 + 2 + 3); console.log(a()); // 6 console.log(a()); // 6 console.log(a()); // 6 ``` ### Math #### eachCombination The `eachCombination(alternativesByDimension, callback)` calls the `callback(a,b,c,...)` on each combination of the `alternatives[a[],b[],c[],...]`. ```js eachCombination([ [1, 2, 3], ["a", "b"] ], console.log); /* 1, "a" 1, "b" 2, "a" 2, "b" 3, "a" 3, "b" */ ``` You can use any dimension and number of alternatives. In the current example we used 2 dimensions. By the first dimension we used 3 alternatives: `[1, 2, 3]` and by the second dimension we used 2 alternatives: `["a", "b"]`. ## License MIT - 2016 Jánszky László Lajos # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. * `fs` File-system object with Node's `fs` API. By default, the built-in `fs` module will be used. Set to a volume provided by a library like `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Glob Logo Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` ![](oh-my-glob.gif) # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). is2 === is2 is a type-checking module for JavaScript to test values. Is does not throw exceptions and every function only returns true or false. Use is2 to validate types in your node.js code. Every function in is2 returns either true of false. ## Installation To install is2, type: $ npm install is2 ## Usage const is = require('is2'); console.log(`1===1 is: ${is.equal(true, 1===1)}`); console.log(`10 is a positive number: ${is.positiveNumber(10)}`); console.log(`11 is an odd number: ${is.oddNumber(11)}`); ## API Each function returns true or false. The names after the '-' are aliases, which provide brevity. Environment: * is.browser() * is.defined(val) - is.def * is.nodejs() - is.node() * is.undefined(val) - is.udef, is.undef Types: * is.array(val) - is.ary, is.arry * is.arrayLike(val) - is.arryLike, is.aryLike, is.arrLike * is.arguments(val) - is.args * is.boolean(val) - is.bool * is.buffer(val) - is.buf, is.buff * is.date(val) * is.error(val) - is.err * is.false(val) * is.function(val) - is.funct, is.fun * is.mongoId - is.objectId, is.objId * is.null(val) * is.nullOrUndefined(val) - is.nullOrUndef * is.number(val) - is.num * is.object(val) - is.obj * is.regExp(val) - is.regexp, is.re * is.string(val) - is.str * is.true(val) * is.uuid(val) Relationships: * is.equal(val, other) - is.eq, is.objEquals * is.hosted(val, host) * is.instanceOf(val, constructor) - is.instOf, is.instanceof * is.matching(val1, val2 [, val3, ...]) - is.match : true if the first arument is strictly equal to any of the subsequent args. * is.objectInstanceof(obj, objType) - is.instOf, is.instanceOf, is.objInstOf, is.objectInstanceOf * is.type(val, type) - is.a * is.enumerator(val, array) - is.enum, is.inArray Object State: * is.empty(val) * is.emptyArguments(val) - is.emptyArgs, is.noArgs * is.emptyArray(val) - is.emptyArry, is.emptyAry, is.emptyArray * is.emptyArrayLike(val) - is.emptyArrLike * is.emptyString(val) - is.emptyStr * is.nonEmptyArray(val) - is.nonEmptyArry, is.nonEmptyAry * is.nonEmptyObject(val) - is.nonEmptyObj * is.emptyObject(val) - is.emptyObj * is.nonEmptyString(val) - is.nonEmptyStr Numeric Types within Number: * is.even(val) - is.evenNum, is.evenNumber * is.decimal(val) - is.decNum, is.dec * is.integer(val) - is.int * is.notANumber(val) - is.nan, is.notANum * is.odd(val) - is.oddNum, is.oddNumber Numeric Type and State: * is.positiveNumber(val) - is.pos, is.positive, is.posNum, is.positiveNum * is.negativeNumber(val) - is.neg, is.negNum, is.negativeNum, is.negativeNumber * is.negativeInteger(val) - is.negativeInt, is.negInt * is.positiveInteger(val) - is.posInt, is.positiveInt Numeric Relationship: * is.divisibleBy(val, other) - is.divisBy, is.divBy * is.greaterOrEqualTo(val, other) - is.ge, is.greaterOrEqual * is.greaterThan(val, other) - is.gt * is.lessThanOrEqualTo(val, other) - is.lessThanOrEq, is.lessThanOrEqual, is.le * is.lessThan(val, other) - is.lt * is.maximum(val, array) - is.max * is.minimum(val, array) - is.min * is.withIn(val, start, finish) - is.within * is.prettyClose(val, comp, precision) - is.closish, is.near Networking: * is.dnsAddress(val) - is.dnsAddr, is.dns * is.emailAddress(val) - is.email, is.emailAddr * is.ipv4Address(val) - is.ipv4, is.ipv4Addr * is.ipv6Address(val) - is.ipv6, is.ipv6Addr * is.ipAddress(val) - is.ip, is.ipAddr * is.hostAddress(val) - is.host = is.hostIp = is.hostAddr * is.port(val) * is.systemPort(val) - is.sysPort * is.url(val) - is.uri * is.userPort(val) Credit Cards: * is.creditCardNumber(str) - is.creditCard, is.creditCardNum * is.americanExpressCardNumber(str) - is.amexCardNum, is.amexCard * is.chinaUnionPayCardNumber(str) - is.chinaUnionPayCard, is.chinaUnion * is.dankortCardNumber(str) - is.dankortCard, is.dankort * is.dinersClubCarteBlancheCardNumber(str) - is.dinersClubCarteBlancheCard, is.dinersClubCB * is.dinersClubInternationalCardNumber(str) - is.dinersClubInternationalCard, is.dinersClubInt * is.dinersClubUSACanadaCardNumber(str) - is.dinersClubUSACanCard, is.dinersClub * is.discoverCardNumber(str) - is.discoverCard, is.discover * is.instaPaymentCardNumber(str) - is.instaPayment * is.jcbCardNumber(str) - is.jcbCard, is.jcb * is.laserCardNumber(str) - is.laserCard, is.laser * is.maestroCardNumber(str) - is.maestroCard, is.maestro * is.masterCardCardNumber - is.masterCardCard, is.masterCard * is.visaCardNumber(str) - is.visaCard, is.visa * is.visaElectronCardNumber(str) - is.visaElectronCard, is.visaElectron Personal information: * is.streetAddress(str) - is.street, is.address * is.zipCode(str) - is.zip * is.phoneNumber(str) - is.phone ## License The MIT License (MIT) Copyright (c) 2013,2014 Edmond Meinfelder Copyright (c) 2011 Enrico Marino Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # near-ledger-js A JavaScript library for communication with [Ledger](https://www.ledger.com/) Hardware Wallet. # Example usage ```javascript import { createClient, getSupportedTransport } from "near-ledger-js"; const transport = await getSupportedTransport(); transport.setScrambleKey("NEAR"); transport.on('disconnect', () => {...}); ``` In an onClick handler: ```javascript const client = await createClient(transport); // If no error thrown, ledger is available. NOTE: U2F transport will still get here even if device is not present ``` To see debug logging for `getSupportedTransport()`, import `setDebugLogging()` and call `setDebugLogging(true)` before using the package. # How to run demo project 1. `yarn` to install dependencies 2. `yarn start` to start local server with Parcel 3. Open https://localhost:1234 in your browser 4. Open browser console 5. Try examples shown on the page # License This repository is distributed under the terms of both the MIT license and the Apache License (Version 2.0). See [LICENSE](LICENSE) and [LICENSE-APACHE](LICENSE-APACHE) for details. # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes * `n` - the argument of the function must be a plain JavaScript Number. Decimals are not supported. * `rn` - both argument and return value of the function are plain JavaScript Numbers. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance * `BN.max(a, b)` - return `a` if `a` bigger than `b` * `BN.min(a, b)` - return `a` if `a` less than `b` ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divmod(b)` - quotient and modulus obtained by dividing * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b, value)` - set specified bit to `value` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ### Number Size Optimized for elliptic curves that work with 256-bit numbers. There is no limitation on the size of the numbers. ## LICENSE This software is licensed under the MIT License. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # end-of-stream A node module that calls a callback when a readable/writable/duplex stream has completed or failed. npm install end-of-stream [![Build status](https://travis-ci.org/mafintosh/end-of-stream.svg?branch=master)](https://travis-ci.org/mafintosh/end-of-stream) ## Usage Simply pass a stream and a callback to the `eos`. Both legacy streams, streams2 and stream3 are supported. ``` js var eos = require('end-of-stream'); eos(readableStream, function(err) { // this will be set to the stream instance if (err) return console.log('stream had an error or closed early'); console.log('stream has ended', this === readableStream); }); eos(writableStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished', this === writableStream); }); eos(duplexStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended and finished', this === duplexStream); }); eos(duplexStream, {readable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished but might still be readable'); }); eos(duplexStream, {writable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended but might still be writable'); }); eos(readableStream, {error:false}, function(err) { // do not treat emit('error', err) as a end-of-stream }); ``` ## License MIT ## Related `end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # capability.js - javascript environment capability detection [![Build Status](https://travis-ci.org/inf3rno/capability.png?branch=master)](https://travis-ci.org/inf3rno/capability) The capability.js library provides capability detection for different javascript environments. ## Documentation This project is empty yet. ### Installation ```bash npm install capability ``` ```bash bower install capability ``` #### Environment compatibility The lib requires only basic javascript features, so it will run in every js environments. #### Requirements If you want to use the lib in browser, you'll need a node module loader, e.g. browserify, webpack, etc... #### Usage In this documentation I used the lib as follows: ```js var capability = require("capability"); ``` ### Capabilities API #### Defining a capability You can define a capability by using the `define(name, test)` function. ```js capability.define("Object.create", function () { return Object.create; }); ``` The `name` parameter should contain the identifier of the capability and the `test` parameter should contain a function, which can detect the capability. If the capability is supported by the environment, then the `test()` should return `true`, otherwise it should return `false`. You don't have to convert the return value into a `Boolean`, the library will do that for you, so you won't have memory leaks because of this. #### Testing a capability The `test(name)` function will return a `Boolean` about whether the capability is supported by the actual environment. ```js console.log(capability.test("Object.create")); // true - in recent environments // false - by pre ES5 environments without Object.create ``` You can use `capability(name)` instead of `capability.test(name)` if you want a short code by optional requirements. #### Checking a capability The `check(name)` function will throw an Error when the capability is not supported by the actual environment. ```js capability.check("Object.create"); // this will throw an Error by pre ES5 environments without Object.create ``` #### Checking capability with require and modules It is possible to check the environments with `require()` by adding a module, which calls the `check(name)` function. By the capability definitions in this lib I added such modules by each definition, so you can do for example `require("capability/es5")`. Ofc. you can do fun stuff if you want, e.g. you can call multiple `check`s from a single `requirements.js` file in your lib, etc... ### Definitions Currently the following definitions are supported by the lib: - strict mode - `arguments.callee.caller` - es5 - `Array.prototype.forEach` - `Array.prototype.map` - `Function.prototype.bind` - `Object.create` - `Object.defineProperties` - `Object.defineProperty` - `Object.prototype.hasOwnProperty` - `Error.captureStackTrace` - `Error.prototype.stack` ## License MIT - 2016 Jánszky László Lajos
evgenykuzyakov_near-social-bot
README.md index.js package.json run.sh src bot.js near.js openai.js social.js utils.js
# near-social-bot OpenAI based bot for NEAR Social Add `.env` file: ```env OPENAI_ORG = "org-XXXXXXXXXXXXXXXXXXXXXXXX" OPENAI_API_KEY = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; AI_COMMAND = "Your name is Bob\nYour account ID is @bob.near\nYou're friendly. Please reply to the thread.\n" STOP_SEQ = "<BLA>" NEAR_ACCOUNT_ID = "bob.near" NEAR_PRIVATE_KEY = "ed25519:5FF83vFDQQzzidoN1a1HaUsosBTyhFvLyzwCPhNUBkeRSYnZYnYpZaakHASwNWLLk2iZvMmXzebrSyb6ggi4CWrU" MAX_TOKENS = "1024" MAX_TOKENS_PER_PROMPT = "256" MAX_PROMPT_TOKENS = "512" DAILY_PROMPT = "Tell me what important events happened on ${dateText}." MODEL = "gpt-3.5-turbo" ```
kirana-network_kirana-network-contracts
v0 Cargo.toml build.sh deploy.sh src lib.rs utils package-lock.json package.json test.js
NiFTyRent_nft-rental
.github workflows ci.yml .gitpod.yml README.md contract Cargo.toml README.md src externals.rs lib.rs nft core.rs data_image_svg.txt enumeration.rs internal.rs metadata.rs mod.rs utils.rs demo_nft_contract Cargo.toml README.md src lib.rs demo_nft_frontend index.html package.json src NftContract.js RentalContract.js Utils.js main.css tailwind.config.js vite.config.js docs NFT Rental Standard Draft.md frontend assets logo.svg index.html package.json src FtContract.js NftContract.js Utils.js main.css near-api.js near-config.js tailwind.config.js vite.config.js integration-tests Cargo.toml README.md stubs ft Cargo.toml src lib.rs nft_with_payout Cargo.toml src lib.rs nft_without_payout Cargo.toml src lib.rs tests gas_usage.rs integration.rs utils.rs marketplace Cargo.toml README.md src externals.rs ft_callbacks.rs lib.rs nft_callbacks.rs Initialization Admin Functions View Functions XCC RPCs Internal Helpers package.json scripts set_allowed_fts.js test_util.txt view_state_keys.js
Welcome to NiFTyRent! ================================= The [smart contract] written in [Rust] for [NiFTyRent]. Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Please also refer to ~/README.md for setup. Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. 2. Tests: You can run unit tests with the `yarn test:unit`. [smart contract]: https://docs.near.org/develop/welcome [Rust]: https://www.rust-lang.org/ [NiFTyRent]: https://testnet.niftyrent.xyz/ [correct target]: https://docs.near.org/develop/prerequisites#rust-and-wasm # NiftyRent ## Quick Start If you haven't installed dependencies during setup: yarn deps-install To deploy the rental dev contract on testnet yarn deploy Initilise the rental dev contract export OWNER=<your test account id> export RENTAL_CONTRACT=`cat contract/neardev/dev-account` near call $RENTAL_CONTRACT new "{\"owner_id\": \"$OWNER\"}" --accountId $OWNER Deploy the marketplace dev contract on testnet yarn deploy:marketplace Initilise the marketplace dev contract export MARKETPLACE_CONTRACT=`cat marketplace/neardev/dev-account` near call $MARKETPLACE_CONTRACT new "{\"owner_id\": \"$OWNER\", \"treasury_id\": \"$OWNER\", \"rental_contract_id\": \"$RENTAL_CONTRACT\"}" --accountId $OWNER Add and register allowed FTs for both contracts near repl -s ./scripts/set_allowed_fts.js --accountId $OWNER Add allowed NFT contracts for the marketplace contract near call $MARKETPLACE_CONTRACT add_allowed_nft_contract_ids '{"nft_contract_ids": ["niftyrpg.mintspace2.testnet"]}' --accountId $OWNER // You can add more testing NFT contracts To start dev server yarn start ## Allowed FT contract addresses For now, the contract only allow a limited number of FTs as the rent payment currency options. To check the current list: near call $CONTRACT_NAME get_allowed_ft_contract_addrs "" --accountId $ACCOUNT_ID To set the list (for the testnet for example): UPDATE: there is script automates the following: `./scripts/set_allowed_fts.js` near call $CONTRACT_NAME set_allowed_ft_contract_addrs '{"addrs": ["wrap.testnet", "usdc.fakes.testnet"]}' --accountId $ACCOUNT_ID Bear in mind that you need to make sure: 1. `$ACCOUNT_ID` is the owner of the contract. (Only owner can change the list.) 2. the contract itself have been registered in the FT contract for the storage deposit. For example, you can: `near call usdc.fakes.testnet storage_deposit "{\"account_id\": \"$CONTRACT_NAME\", \"registration_only\": true}" --accountId $ACCOUNT_ID --amount 0.1` Once updated, the UI should automatically pick up the new list of allowed FTs. NiFTyRent Marketplace contract ================================= A marketplace for users to lend and rent utility NFT assets. The actual rental logic is delegated to the core rental contract, for sake of responsibility separation. ``` mermaid sequenceDiagram actor Lender actor Borrower participant Marketplace participant Core participant Game Lender ->> Marketplace: Create lease offer Borrower ->> Marketplace: Take lease offer (by tranfer the rent) Marketplace->>Core: Transfer NFT, transfer rent, and create an active lease Lender ->> Core: View my lendings Borrower ->> Core: view my borowings Game ->> Core: Check current user Lender ->> Core: Claim back the NFT and rent ``` # Introduction Both unit tests and integrations tests are included for the project. ## Prerequisite Follow ../README.md to set up the environment # Unit Test Unit Tests are located in the contract file ./contract/src/lib.rs, inside the tests module. ## How to run unit tests - move to project root directory. e.g. ./nft-rental - `yarn test:unit` # Integration Test Integration test are based in a different directory ./integration-tests ## How to run test - move to the ./nft-rental/integration-tests - Run `yarn test:integration` ## Test plan - `test_claim_back_with_payout_success`: the lender, Alice, lends the testing NFT token to the borrower, Bob. This test will verify the ownership of the token is transferred back to Alice after being claimed back. The test will also verify the payout splits are made correctly as defined in the token. - `test_claim_back_without_payout_success`: similar to `test_claim_back_with_payout_success` but with an NFT which doesn't support payout. In this case all the rent should go to Alice. - `test_accept_leases_already_lent`: This test verifies that the call will pass for the first time when lender accepts the lease but should faile if borrowers accepts the same lease for multiple times. - `test_accept_lease_fails_already_transferred`: This test verifies that the call should fail if the token has been transferred before the borrowers accepts the lease. The following integration tests have been added for Lease Ownership NFT - `test_lender_receives_a_lease_nft_after_lease_activation`: lender can receive a lease nft token with correct token information after the leaes got activated. - `test_lease_nft_can_be_transferred_to_other_account`: owner of the lease nft token can transfer the token to other account. The underlying lease's lender info will also be udpated correctly. - `test_claim_back_without_payout_using_lease_nft`: owner of the lease nft token can claim back the renting nft successfully & rent should be paid in full to original lender. - `test_claim_back_with_payout_using_lease_nft`: owner of the lease nft token can claim back the renting nft successfully & rent should be paid correctly to all payout accounds. Inline comment and test output have also been added. Please refer the code. # Tamagotchi
kels-orien_nft-marketplace-part-1
README.md nft-contract Cargo.toml build.bat build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs royalty.rs test.sh package-lock.json package.json src App.css App.js Close.js Modal.js assets near-logo.svg config.js fonts OFL.txt README.txt index.html index.js useModal.js
# nft-marketplace-part-1 A [tutorial](https://dev.to/kels_orien/building-a-full-stack-nft-market-place-with-near-protocol-and-reactjs-ak9) of an NFT Market Place built using Near Protocol and React.js. #### Preview ![alt-text](https://res.cloudinary.com/dofiasjpi/image/upload/v1649243579/near-tutorial-nfts/near-tut-preview.png) ### Prerequisites * [Nodejs](https://github.com/nvm-sh/nvm) * [NEAR Wallet Account](https://wallet.testnet.near.org/) * [Rust Toolchain](https://docs.near.org/docs/develop/contracts/rust/intro#installing-the-rust-toolchain) * [NEAR-CLI](https://docs.near.org/docs/tools/near-cli#setup) ## Getting Started Near Protocol uses [rust](https://www.rust-lang.org/) programming language for it's smart contracts. We are going to start with a rust contract template. #### To run this app locally, follow below steps: ##### Clone using command line interface: ``` git clone https://github.com/kels-orien/nft-marketplace-part-1.git ``` ##### Create wallet testnet account open [wallet testnet account](wallet.testnet.near.org/) ##### From the `nft-contract` folder/directory using command CLI, login to near wallet account `near login` ##### Build the contract From `nft-contract` directory using CLI: For Windows users: ``` /build.bat ``` For Mac and Linux users: ``` /build.sh ``` ##### Create a subaccount To create subaccount from `nft-contract` directory via CLI use command: ``` near create-account nft-contract.youraccountname.testnet --masterAccount youraccountname.testnet ``` ##### Deploy the contract ``` near deploy --accountId nft-contract.youraccountname.testnet --wasmFile res/nft_contract.wasm ``` ##### Edit contract name Change the `youraccountName` part of the `contractName` constant in `config.js` file to your own account name. ##### Install packages for frontend Go to root directory `nft-marketplac-part-1` using CLI and install packages: ``` cd .. npm install ``` ##### Launch frontend ``` npm start ```
huerta2502_urdemocracy
README.md as-pect.config.js asconfig.json assembly __tests__ main.spec.ts as_types.d.ts index.ts model.ts tsconfig.json compile.js concept.txt neardev dev-account.env package.json src index.html main.js profile.html profile.js
# urdemocracy ==================== > Project developed for GSC ESCOM IPN NEAR Protocol blockchain course. ## urdemocracy is a software tool to help decision making process in political societies focused on a participatory democracy paradigm using near protocol blockchain. # urdemocracy lets you: 1. Create user account 2. Create collectives 3. Register Deliberations for collectives 4. Register Resources and Results for registered Delliberations. 5. Register Followups for Deliberation Results ## Pre-requisites: 1. node.js >=12 installed (https://nodejs.org) 2. yarn installed ```bash npm install --global yarn ``` 3. install dependencias ```bash yarn install --frozen-lockfile ``` 4. create a new account in NEAR testnet [testnet](https://docs.near.org/docs/develop/basics/create-account#creating-a-testnet-account) 5. install NEAR CLI ```bash yarn install --global near-cli ``` 6. authorize NEAR CLI to access your NEAR Account ```bash near login ``` ### Clone this repository ```bash git clone https://github.com/huerta2502/urdemocracy cd urdemocracy ``` ### Install project dependecies and compile the smart contract ```bash yarn install yarn build:contract:debug ``` ### Deploy the contract to the NEAR testnet ```bash yarn dev:deploy:contract ``` ### Install frontend dependeices ```bash yarn install ``` ### Execute frontend ```bash yarn start ```
esaminu_console-donation-template-q2e5
.github scripts runfe.sh workflows deploy-to-console.yml readme.yml tests.yml .gitpod.yml README.md contract README.md build.sh deploy.sh package-lock.json package.json src contract.ts model.ts utils.ts tsconfig.json integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
# Donation Contract The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. ```ts @call donate() { // Get who is calling the method and how much $NEAR they attached let donor = near.predecessorAccountId(); let donationAmount: bigint = near.attachedDeposit() as bigint; let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) let toTransfer = donationAmount; // This is the user's first donation, lets register it, which increases storage if(donatedSoFar == BigInt(0)) { assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); // Subtract the storage cost to the amount to transfer toTransfer -= STORAGE_COST } // Persist in storage the amount donated so far donatedSoFar += donationAmount this.donations.set(donor, donatedSoFar.toString()) // Send the money to the beneficiary const promise = near.promiseBatchCreate(this.beneficiary) near.promiseBatchActionTransfer(promise, toTransfer) // Return the total amount donated so far return donatedSoFar.toString() } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` The contract will be automatically initialized with a default `beneficiary`. To initialize the contract yourself do: ```bash # Use near-cli to initialize contract (optional) near call <dev-account> init '{"beneficiary":"<account>"}' --accountId <dev-account> ``` <br /> ## 2. Get Beneficiary `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> beneficiary ``` <br /> ## 3. Get Number of Donations `donate` forwards any attached money to the `beneficiary` while keeping track of it. `donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> donate --amount 1 --accountId <account> ``` **Tip:** If you would like to `donate` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`. # Donation 💸 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/donation-js) [![](https://img.shields.io/badge/Contract-js-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fdonation-js%2Fbadge&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/donation-js/goto) Our Donation example enables to forward money to an account while keeping track of it. It is one of the simplest examples on making a contract receive and send money. ![](https://docs.near.org/assets/images/donation-7cf65e5e131274fd1ae9aa34bc465bb8.png) # What This Example Shows 1. How to receive and transfer $NEAR on a contract. 2. How to divide a project into multiple modules. 3. How to handle the storage costs. 4. How to handle transaction results. 5. How to use a `Map`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-js). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome).
neararabic_near-hello-world-rs
Cargo.toml README.md rustfmt.toml src lib.rs
# مرحباً نير مع رست NEAR Rust Hello World! مشروع بسيط يعمل كنقطة بداية لمشاريعك ( العقود الذكية) على شبكة نيــر باستخدام لغة البرمجة رست Rust ## لتشغيل المشروع يحتاج المشروع لتثبيت أدوات التطوير الخاصة بلغة رست و ويب أسمبلي rust and web assembly tool chain يمكن اتباع خطوات تثبيتهم هنــاhttps://www.near-sdk.io/ 1- قم بنسخ المشروع لجهازك clone 2- من داخل مجلد المشروع فى شاشة الأوامر terminal قم بكتابة الأمر التالي ``` env 'RUSTFLAGS=-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release ``` - ملحوظة: الجزء `env 'RUSTFLAGS=-C link-arg=-s'` يقوم بعمل تحسين لعملية تحويل الكود و يؤثر جذرياً على حجم الملف الناتج و بالتالى تكلفة رفع الملف و استضافته على البلوك تشين. إذا كان الملف الناتج من العملية السابقة أكبر من 200 كيلو بايت لديك (14 ميجا بايت مثلاً أو أكثر) فهذا يعنى أن الأمر لم يعمل بشكل صحيح و يجب عليك فحص إعدادات رست و تفعيله. 3- ستلاحظ وجود ملفات جديدة تم انشائها داخل مجلد target و منها الملف `near_rust_helloworld.wasm` 4- يمكنك رفع هذا الملف مباشرة على البلوك تشين بالطرق المعتادة مثل ``` near dev-deploy .\target\wasm32-unknown-unknown\release\near_rust_helloworld.wasm ``` 5- يمكنك التجربة باستدعاء الدالة `hello_world` ``` near view CONTRACT_ACCOUNT_ID hello_world ```
near_near-discovery-components
.github ISSUE_TEMPLATE bug_report.md feature_request.md new-dig-component.md release.yml workflows deploy-dev-testnet.yml deploy-prod-mainnet.yml deploy-prod-testnet.yml promote-develop-to-main.yml prs_must_have_labels.yml release_notes.yml stale.yml CODE_OF_CONDUCT.md CONTRIBUTING.md README.md commitlint.config.js indexers README.md accounts accounts.js accounts.sql components components.js components.sql entities entities.js entities.sql entities_tests.js test_block.js feed README.md feed.js feed.sql relationships.json moderation moderation.js moderation.sql notifications notifications.js notifications.sql relationships.json social_feed social_feed.js social_feed.sql verifications verifications.js verifications.sql package.json replacements.dev.json replacements.mainnet.json replacements.testnet.json src AI DO_NOT_USE.md ActivityFeeds test.js AppLibrary IndexPage.metadata.json Nearcon IndexPage.metadata.json DIG Accordion.metadata.json Avatar.metadata.json Badge.metadata.json Button.metadata.json Checkbox.metadata.json Chip.metadata.json Dialog.metadata.json DropdownMenu.metadata.json Input.metadata.json InputSearch.metadata.json InputSelect.metadata.json InputTags.metadata.json InputTextarea.metadata.json OverviewPage.metadata.json Tabs.metadata.json Theme.metadata.json Toast.metadata.json Tooltip.metadata.json DS Button.metadata.json Theme.metadata.json FastAuth.metadata.json Onboarding ComponentCard.metadata.json ComponentCollection.metadata.json Starter.metadata.json vm.d.ts
# QueryApi Indexers used by components Several components use QueryApi Indexers as a source of data, specifically the ActivityFeed Posts & 'Following' Posts. These indexers can be modified at https://near.org/dataplatform.near/widget/QueryApi.App under the dataplatform.near account. Each indexer has a .sql schema file and a .js file which contains the Indexer Function code. # Feed indexer This indexer holds the top level views used to display the feed. It prevents a circular reference between the social_feed and moderation indexers. The relationships.json file documents the manually created GraphQL relationships used by the feed, in hasura metadata format. At some point QueryApi indexers may support a similar format for declarative relationships. # Near Discovery Components This is a repository that holds the source code of all NEAR discovery components that the team maintains for [near.org](https://near.org). Components will be deployed to production automatically as they are merged into the main branch. This occurs weekly, on Thursdays. Keep in mind that folders under `src` will be prepended to the component name when it's deployed. E.g. `src/post/comment.jsx` will be deployed as `post.comment`. ### Deployments Across Discovery Gateways #### tl;dr; >test.beta.near.org => discom-dev.testnet >test.near.org => discom.testnet >near.org => near TLA >beta.near.org => near TLA The [discovery gateway](https://github.com/near/near-discovery) deploys its main and develop branches across environments as follows - the `main` branch is deployed on [near.org](https://near.org), pointing to `mainnet` and [test.near.org](https://test.near.org) pointing to `testnet` - the `develop` branch is deployed to [beta.near.org](https://beta.near.org), pointing to `mainnet`, and [test.beta.near.org](https://test.beta.near.org), pointing to `testnet` This `discovery-components` repo deploys main and develop branches across accounts as follows - the `main` branch deploys components to the near top-level-acount for `mainnet` and `discom.testnet` for `testnet` except where indicated otherwise in replacements.[mainnet/testnet].json - the `develop` branch deploys components to `discom-dev.testnet` except where indicated otherwise in replacements.dev.json; there is currently no mainnet deployment for the develop branch. ## Contributing Please review the [contribution guide](CONTRIBUTING.md) ## Local Development Please review the [Local development with BOS-Loader](CONTRIBUTING.md#local-development-with-bos-loader) *Note:* This repository is not compatible with the [VS Code Extension](https://docs.near.org/bos/dev/vscode) due to the [replacements](CONTRIBUTING.md#testing-across-multiple-environments) strategy featured in this repository. ## Troubleshooting Deployments `near-social` cli tool will attempt to deploy any updated components with 1 NEAR of deposit and 100 Tgas. The deployment may fail if too many changes are present. There are several solutions for this. You can either plan releases more often or release components in batches from your local using `near-social`. If you get a `Not enough storage balance` error, you will need to make sure that the NEAR account has enough storage staked on the `social.near` contract. You can view the current storage and available storage for any account using `near-cli-rs`: `near-cli contract call-function as-read-only social.near storage_balance_of json-args '{"account_id":"adminalpha.near"}' network-config mainnet now` Note: replace `adminalpha.near` with any other account name on mainnet. You can then stake more of your NEAR for storage on `social.near` using `near-cli-rs`: `near-cli contract call-function as-transaction social.near storage_deposit json-args {} prepaid-gas '100.000 TeraGas' attached-deposit '0.5 NEAR' sign-as adminalpha.near network-config mainnet sign-with-seed-phrase '{{REPLACE_WITH_SEED_PHRASE}}' --seed-phrase-hd-path 'm/44'\''/397'\''/0'\
Na3aga_rust-near-basic
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
nearprotocol_leaderboard
.vscode launch.json settings.json README.md database.rules.json dist index.html firebase.json node_modules .bin sha.js @babel code-frame README.md lib index.js package.json core README.md lib config caching.js config-chain.js config-descriptors.js files configuration.js index-browser.js index.js package.js plugins.js types.js utils.js full.js helpers config-api.js environment.js index.js item.js partial.js pattern-to-regex.js plugin.js util.js validation option-assertions.js options.js plugins.js removed.js index.js parse.js tools build-external-helpers.js transform-ast.js transform-file-browser.js transform-file.js transform.js transformation block-hoist-plugin.js file file.js generate.js merge-map.js index.js normalize-file.js normalize-opts.js plugin-pass.js util missing-plugin-helper.js node_modules debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js json5 CHANGELOG.md LICENSE.md README.md dist index.js index.min.js lib cli.js index.js parse.js register.js require.js stringify.js unicode.js util.js package.json ms index.js license.md package.json readme.md package.json generator README.md lib buffer.js generators base.js classes.js expressions.js flow.js index.js jsx.js methods.js modules.js statements.js template-literals.js types.js typescript.js index.js node index.js parentheses.js whitespace.js printer.js source-map.js package.json helper-annotate-as-pure README.md lib index.js package.json helper-builder-binary-assignment-operator-visitor README.md lib index.js package.json helper-builder-react-jsx README.md lib index.js package.json helper-call-delegate README.md lib index.js package.json helper-define-map README.md lib index.js package.json helper-explode-assignable-expression README.md lib index.js package.json helper-function-name README.md lib index.js package.json helper-get-function-arity README.md lib index.js package.json helper-hoist-variables README.md lib index.js package.json helper-member-expression-to-functions README.md lib index.js package.json helper-module-imports README.md lib import-builder.js import-injector.js index.js is-module.js package.json helper-module-transforms README.md lib index.js normalize-and-load-metadata.js rewrite-live-references.js rewrite-this.js package.json helper-optimise-call-expression README.md lib index.js package.json helper-plugin-utils README.md lib index.js package.json src index.js helper-regex README.md lib index.js package.json helper-remap-async-to-generator README.md lib index.js package.json helper-replace-supers README.md lib index.js package.json helper-simple-access README.md lib index.js package.json helper-split-export-declaration README.md lib index.js package.json helper-wrap-function README.md lib index.js package.json helpers README.md lib helpers.js index.js package.json highlight README.md lib index.js package.json parser CHANGELOG.md README.md bin babel-parser.js lib index.js package.json typings babel-parser.d.ts plugin-proposal-async-generator-functions README.md lib for-await.js index.js package.json plugin-proposal-json-strings README.md lib index.js package.json plugin-proposal-object-rest-spread README.md lib index.js package.json plugin-proposal-optional-catch-binding README.md lib index.js package.json plugin-proposal-unicode-property-regex README.md lib index.js package.json src index.js test fixtures with-unicode-flag options.json script-extensions input.js output.js simple input.js output.js unicode-10 input.js output.js unicode-11 input.js output.js unicode-12 input.js output.js without-unicode-flag options.json script-extensions input.js output.js simple input.js output.js unicode-10 input.js output.js unicode-11 input.js output.js unicode-12 input.js output.js index.js plugin-syntax-async-generators README.md lib index.js package.json plugin-syntax-json-strings README.md lib index.js package.json plugin-syntax-jsx README.md lib index.js package.json plugin-syntax-object-rest-spread README.md lib index.js package.json plugin-syntax-optional-catch-binding README.md lib index.js package.json plugin-transform-arrow-functions README.md lib index.js package.json plugin-transform-async-to-generator README.md lib index.js package.json plugin-transform-block-scoped-functions README.md lib index.js package.json plugin-transform-block-scoping README.md lib index.js tdz.js package.json plugin-transform-classes README.md lib index.js transformClass.js package.json plugin-transform-computed-properties README.md lib index.js package.json plugin-transform-destructuring README.md lib index.js package.json plugin-transform-dotall-regex README.md lib index.js package.json src index.js test fixtures dotall-regex options.json simple input.js output.js with-unicode-flag input.js output.js index.js plugin-transform-duplicate-keys README.md lib index.js package.json plugin-transform-exponentiation-operator README.md lib index.js package.json plugin-transform-for-of README.md lib index.js package.json plugin-transform-function-name README.md lib index.js package.json plugin-transform-literals README.md lib index.js package.json plugin-transform-member-expression-literals README.md lib index.js package.json plugin-transform-modules-amd README.md lib index.js package.json plugin-transform-modules-commonjs README.md lib index.js package.json plugin-transform-modules-systemjs README.md lib index.js package.json plugin-transform-modules-umd README.md lib index.js package.json plugin-transform-named-capturing-groups-regex README.md lib index.js package.json plugin-transform-new-target README.md lib index.js package.json plugin-transform-object-super README.md lib index.js package.json plugin-transform-parameters README.md lib index.js params.js rest.js package.json plugin-transform-property-literals README.md lib index.js package.json plugin-transform-react-display-name README.md lib index.js package.json plugin-transform-react-jsx-self README.md lib index.js package.json plugin-transform-react-jsx-source README.md lib index.js package.json plugin-transform-react-jsx README.md lib index.js package.json plugin-transform-regenerator README.md lib index.js package.json plugin-transform-reserved-words README.md lib index.js package.json plugin-transform-shorthand-properties README.md lib index.js package.json plugin-transform-spread README.md lib index.js package.json plugin-transform-sticky-regex README.md lib index.js package.json plugin-transform-template-literals README.md lib index.js package.json plugin-transform-typeof-symbol README.md lib index.js package.json plugin-transform-unicode-regex README.md lib index.js package.json preset-env CHANGELOG.md CONTRIBUTING.md README.md data built-in-modules.json built-ins.json.js corejs2-built-in-features.js corejs2-built-ins.json plugin-features.js plugins.json shipped-proposals.js unreleased-labels.js lib available-plugins.js debug.js filter-items.js get-option-specific-excludes.js index.js module-transformations.js normalize-options.js options.js polyfills corejs2 built-in-definitions.js entry-plugin.js get-platform-specific-default.js usage-plugin.js corejs3 built-in-definitions.js entry-plugin.js shipped-proposals.js usage-plugin.js regenerator entry-plugin.js usage-plugin.js targets-parser.js utils.js package.json preset-react README.md lib index.js package.json template README.md lib builder.js formatters.js index.js literal.js options.js parse.js populate.js string.js package.json traverse README.md lib cache.js context.js hub.js index.js path ancestry.js comments.js context.js conversion.js evaluation.js family.js index.js inference index.js inferer-reference.js inferers.js introspection.js lib hoister.js removal-hooks.js virtual-types.js modification.js removal.js replacement.js scope binding.js index.js lib renamer.js visitors.js node_modules debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md package.json types README.md lib asserts assertNode.js generated index.js builders builder.js flow createTypeAnnotationBasedOnTypeof.js createUnionTypeAnnotation.js generated index.js react buildChildren.js clone clone.js cloneDeep.js cloneNode.js cloneWithoutLoc.js comments addComment.js addComments.js inheritInnerComments.js inheritLeadingComments.js inheritTrailingComments.js inheritsComments.js removeComments.js constants generated index.js index.js converters ensureBlock.js gatherSequenceExpressions.js toBindingIdentifierName.js toBlock.js toComputedKey.js toExpression.js toIdentifier.js toKeyAlias.js toSequenceExpression.js toStatement.js valueToNode.js definitions core.js es2015.js experimental.js flow.js index.js jsx.js misc.js placeholders.js typescript.js utils.js index.d.ts index.js modifications appendToMemberExpression.js flow removeTypeDuplicates.js inherits.js prependToMemberExpression.js removeProperties.js removePropertiesDeep.js retrievers getBindingIdentifiers.js getOuterBindingIdentifiers.js traverse traverse.js traverseFast.js utils inherit.js react cleanJSXElementLiteralChild.js shallowEqual.js validators buildMatchMemberExpression.js generated index.js is.js isBinding.js isBlockScoped.js isImmutable.js isLet.js isNode.js isNodesEquivalent.js isPlaceholderType.js isReferenced.js isScope.js isSpecifierDefault.js isType.js isValidES3Identifier.js isValidIdentifier.js isVar.js matchesPattern.js react isCompatTag.js isReactComponent.js validate.js package.json scripts generateTypeHelpers.js generators docs.js flow.js generateAsserts.js generateBuilders.js generateConstants.js generateValidators.js typescript.js utils formatBuilderName.js lowerFirst.js stringifyValidator.js toFunctionName.js @webassemblyjs ast README.md esm clone.js definitions.js index.js node-helpers.js node-path.js nodes.js signatures.js transform denormalize-type-references index.js wast-identifier-to-index index.js traverse.js types basic.js nodes.js traverse.js utils.js lib clone.js definitions.js index.js node-helpers.js node-path.js nodes.js signatures.js transform denormalize-type-references index.js wast-identifier-to-index index.js traverse.js types basic.js nodes.js traverse.js utils.js package.json scripts generateNodeUtils.js generateTypeDefinitions.js util.js floating-point-hex-parser README.md esm index.js lib index.js package.json helper-api-error esm index.js lib index.js package.json helper-buffer esm compare.js index.js lib compare.js index.js package.json helper-code-frame esm index.js lib index.js package.json helper-fsm esm index.js lib index.js package.json helper-module-context esm index.js lib index.js package.json src index.js test index.js helper-wasm-bytecode esm index.js section.js lib index.js section.js package.json helper-wasm-section esm create.js index.js remove.js resize.js lib create.js index.js remove.js resize.js package.json ieee754 esm index.js lib index.js package.json src index.js leb128 LICENSE.txt esm bits.js bufs.js index.js leb.js lib bits.js bufs.js index.js leb.js package.json utf8 esm decoder.js encoder.js index.js lib decoder.js encoder.js index.js package.json src decoder.js encoder.js index.js test index.js wasm-edit README.md esm apply.js index.js lib apply.js index.js package.json wasm-gen esm encoder index.js index.js lib encoder index.js index.js package.json wasm-opt esm index.js leb128.js lib index.js leb128.js package.json wasm-parser README.md esm decoder.js index.js types decoder.js lib decoder.js index.js types decoder.js package.json wast-parser README.md esm grammar.js index.js number-literals.js string-literals.js tokenizer.js lib grammar.js index.js number-literals.js string-literals.js tokenizer.js package.json wast-printer README.md esm index.js lib index.js package.json @xtuc ieee754 README.md dist index.cjs.js index.js package.json long README.md dist long.js index.d.ts index.js package.json src long.js abbrev README.md abbrev.js package.json accepts HISTORY.md README.md index.js package.json acorn-dynamic-import CHANGELOG.md README.md lib index.js walk.js package.json src index.js walk.js acorn CHANGELOG.md README.md dist acorn.d.ts acorn.js bin.js package.json ajv-errors README.md index.js lib dotjs README.md errorMessage.js package.json ajv-keywords README.md index.js keywords _formatLimit.js _util.js allRequired.js anyRequired.js deepProperties.js deepRequired.js dotjs README.md _formatLimit.js patternRequired.js switch.js dynamicDefaults.js formatMaximum.js formatMinimum.js index.js instanceof.js patternRequired.js prohibited.js range.js regexp.js select.js switch.js transform.js typeof.js uniqueItemProperties.js package.json ajv .tonic_example.js README.md dist ajv.bundle.js ajv.min.js lib ajv.d.ts ajv.js cache.js compile async.js equal.js error_classes.js formats.js index.js resolve.js rules.js schema_obj.js ucs2length.js util.js data.js dotjs README.md _limit.js _limitItems.js _limitLength.js _limitProperties.js allOf.js anyOf.js comment.js const.js contains.js custom.js dependencies.js enum.js format.js if.js index.js items.js multipleOf.js not.js oneOf.js pattern.js properties.js propertyNames.js ref.js required.js uniqueItems.js validate.js keyword.js refs data.json json-schema-draft-04.json json-schema-draft-06.json json-schema-draft-07.json json-schema-secure.json package.json scripts .eslintrc.yml bundle.js compile-dots.js amdefine README.md amdefine.js intercept.js package.json ansi-colors README.md index.js package.json symbols.js types index.d.ts ansi-html README.md index.js package.json ansi-regex index.js package.json readme.md ansi-styles index.js package.json readme.md anymatch README.md index.js node_modules normalize-path README.md index.js package.json package.json aproba README.md index.js package.json are-we-there-yet CHANGES.md README.md index.js package.json tracker-base.js tracker-group.js tracker-stream.js tracker.js arr-diff README.md index.js package.json arr-flatten README.md index.js package.json arr-union README.md index.js package.json array-find-index index.js package.json readme.md array-flatten README.md array-flatten.d.ts array-flatten.js package.json array-union index.js package.json readme.md array-uniq index.js package.json readme.md array-unique README.md index.js package.json asn1.js README.md lib asn1.js asn1 api.js base buffer.js index.js node.js reporter.js constants der.js index.js decoders der.js index.js pem.js encoders der.js index.js pem.js package.json asn1 README.md lib ber errors.js index.js reader.js types.js writer.js index.js package.json assert-plus CHANGES.md README.md assert.js package.json assert .travis.yml .zuul.yml README.md assert.js node_modules inherits README.md inherits.js inherits_browser.js package.json test.js util .travis.yml .zuul.yml README.md package.json support isBuffer.js isBufferBrowser.js test browser inspect.js is.js node debug.js format.js inspect.js log.js util.js util.js package.json test.js assign-symbols README.md index.js package.json async-each CHANGELOG.md README.md bower.json component.json index.js package.json async-foreach README.md dist ba-foreach.js ba-foreach.min.js grunt.js lib foreach.js package.json test foreach_test.js async CHANGELOG.md README.md dist async.js async.min.js lib async.js package.json asynckit README.md bench.js index.js lib abort.js async.js defer.js iterate.js readable_asynckit.js readable_parallel.js readable_serial.js readable_serial_ordered.js state.js streamify.js terminator.js package.json parallel.js serial.js serialOrdered.js stream.js atob README.md bin atob.js bower.json browser-atob.js node-atob.js package.json test.js aws-sign2 README.md index.js package.json aws4 .travis.yml README.md aws4.js lru.js package.json babel-loader CHANGELOG.md README.md lib Error.js cache.js index.js injectCaller.js transform.js package.json babel README.md index.js lib cli.js package.json balanced-match LICENSE.md README.md index.js package.json base README.md index.js node_modules define-property README.md index.js package.json is-accessor-descriptor README.md index.js package.json is-data-descriptor README.md index.js package.json is-descriptor README.md index.js package.json package.json base64-js README.md base64js.min.js index.js package.json test big-data.js convert.js corrupt.js url-safe.js batch History.md Readme.md component.json index.js package.json bcrypt-pbkdf CONTRIBUTING.md README.md index.js package.json big.js CHANGELOG.md README.md big.js big.min.js package.json binary-extensions binary-extensions.json package.json readme.md block-stream README.md block-stream.js package.json bluebird README.md changelog.md js browser bluebird.core.js bluebird.core.min.js bluebird.js bluebird.min.js release any.js assert.js async.js bind.js bluebird.js call_get.js cancel.js catch_filter.js context.js debuggability.js direct_resolve.js each.js errors.js es5.js filter.js finally.js generators.js join.js map.js method.js nodeback.js nodeify.js promise.js promise_array.js promisify.js props.js queue.js race.js reduce.js schedule.js settle.js some.js synchronous_inspection.js thenables.js timers.js using.js util.js package.json bn.js README.md lib bn.js package.json util genCombMulTo.js genCombMulTo10.js body-parser HISTORY.md README.md index.js lib read.js types json.js raw.js text.js urlencoded.js package.json bonjour .travis.yml README.md index.js lib browser.js mdns-server.js registry.js service.js package.json test bonjour.js service.js brace-expansion README.md index.js package.json braces README.md index.js lib braces.js compilers.js parsers.js utils.js node_modules extend-shallow README.md index.js package.json package.json brorand README.md index.js package.json test api-test.js browserify-aes .travis.yml README.md aes.js authCipher.js browser.js decrypter.js encrypter.js ghash.js incr32.js index.js modes cbc.js cfb.js cfb1.js cfb8.js ctr.js ecb.js index.js list.json ofb.js package.json streamCipher.js browserify-cipher .travis.yml README.md browser.js index.js package.json test.js browserify-des .travis.yml index.js modes.js package.json readme.md test.js browserify-rsa .travis.yml index.js package.json readme.md test.js browserify-sign README.md algos.js browser algorithms.json curves.json index.js sign.js verify.js index.js package.json browserify-zlib .travis.yml README.md karma.conf.js lib binding.js index.js package.json src binding.js index.js browserslist CHANGELOG.md README.md browser.js cli.js error.js index.js node.js package.json buffer-from index.js package.json readme.md buffer-indexof .travis.yml README.md bm.js index.js package.json test bm.js multibyteneedle.js partial-match.js test-buffer-indexof.js test.js buffer-xor .travis.yml README.md index.js inline.js inplace.js package.json test fixtures.json index.js buffer .travis.yml AUTHORS.md README.md bin download-node-tests.js test.js update-authors.sh zuul-es5.yml zuul-es6.yml index.js package.json test _polyfill.js base64.js basic.js compare.js constructor.js from-string.js is-buffer.js methods.js node test-buffer-alloc.js test-buffer-arraybuffer.js test-buffer-ascii.js test-buffer-bad-overload.js test-buffer-badhex.js test-buffer-bytelength.js test-buffer-compare-offset.js test-buffer-concat.js test-buffer-fill.js test-buffer-includes.js test-buffer-indexof.js test-buffer-inheritance.js test-buffer-inspect.js test-buffer-iterator.js test-buffer-safe-unsafe.js test-buffer-slow.js test-buffer-swap.js test-buffer-zero-fill-cli.js test-buffer-zero-fill-reset.js test-buffer.js slice.js static.js to-string.js write.js write_infinity.js builtin-status-codes browser.js build.js index.js package.json readme.md bytes History.md Readme.md index.js package.json cacache CHANGELOG.md LICENSE.md README.es.md README.md en.js es.js get.js index.js lib content path.js read.js rm.js write.js entry-index.js memoization.js util fix-owner.js hash-to-segments.js move-file.js tmp.js y.js verify.js locales en.js en.json es.js es.json ls.js node_modules lru-cache README.md index.js package.json yallist README.md iterator.js package.json yallist.js package.json put.js rm.js verify.js cache-base README.md index.js package.json camelcase-keys index.js node_modules camelcase index.js package.json readme.md package.json readme.md camelcase index.d.ts index.js package.json readme.md caniuse-lite CHANGELOG.md README.md data agents.js browserVersions.js browsers.js features.js features aac.js abortcontroller.js ac3-ec3.js accelerometer.js addeventlistener.js alternate-stylesheet.js ambient-light.js apng.js array-find-index.js array-find.js array-flat.js array-includes.js arrow-functions.js asmjs.js async-clipboard.js async-functions.js async-iterations-and-generators.js atob-btoa.js audio-api.js audio.js audiotracks.js autofocus.js aux-click.js auxclick.js av1.js background-attachment.js background-clip-text.js background-img-opts.js background-position-x-y.js background-repeat-round-space.js background-sync.js battery-status.js beacon.js beforeafterprint.js bigint.js blobbuilder.js bloburls.js border-image.js border-radius.js broadcastchannel.js brotli.js calc.js canvas-blending.js canvas-text.js canvas.js ch-unit.js chacha20-poly1305.js channel-messaging.js childnode-remove.js classlist.js clear-site-data-header.js client-hints-dpr-width-viewport.js clipboard.js comparedocumentposition.js console-basic.js console-time.js const.js constraint-validation.js contenteditable.js contentsecuritypolicy.js contentsecuritypolicy2.js cors.js createimagebitmap.js credential-management.js cryptography.js css-all.js css-animation.js css-any-link.js css-appearance.js css-apply-rule.js css-at-counter-style.js css-backdrop-filter.js css-background-offsets.js css-backgroundblendmode.js css-boxdecorationbreak.js css-boxshadow.js css-canvas.js css-caret-color.js css-case-insensitive.js css-clip-path.js css-color-adjust.js css-conic-gradients.js css-containment.js css-counters.js css-crisp-edges.js css-cross-fade.js css-default-pseudo.js css-descendant-gtgt.js css-deviceadaptation.js css-dir-pseudo.js css-display-contents.js css-element-function.js css-env-function.js css-exclusions.js css-featurequeries.js css-filter-function.js css-filters.js css-first-letter.js css-first-line.js css-fixed.js css-focus-ring.js css-focus-visible.js css-focus-within.js css-font-rendering-controls.js css-font-stretch.js css-gencontent.js css-gradients.js css-grid.js css-hanging-punctuation.js css-has.js css-hyphenate.js css-hyphens.js css-image-orientation.js css-image-set.js css-in-out-of-range.js css-indeterminate-pseudo.js css-initial-letter.js css-initial-value.js css-letter-spacing.js css-line-clamp.js css-logical-props.js css-marker-pseudo.js css-masks.js css-matches-pseudo.js css-math-functions.js css-media-interaction.js css-media-resolution.js css-media-scripting.js css-mediaqueries.js css-mixblendmode.js css-motion-paths.js css-namespaces.js css-not-sel-list.js css-nth-child-of.js css-opacity.js css-optional-pseudo.js css-overflow-anchor.js css-overflow.js css-overscroll-behavior.js css-page-break.js css-paged-media.js css-paint-api.js css-placeholder-shown.js css-placeholder.js css-read-only-write.js css-rebeccapurple.js css-reflections.js css-regions.js css-repeating-gradients.js css-resize.js css-revert-value.js css-rrggbbaa.js css-scroll-behavior.js css-scrollbar.js css-sel2.js css-sel3.js css-selection.js css-shapes.js css-snappoints.js css-sticky.js css-subgrid.js css-supports-api.js css-table.js css-text-align-last.js css-text-indent.js css-text-justify.js css-text-orientation.js css-text-spacing.js css-textshadow.js css-touch-action-2.js css-touch-action.js css-transitions.js css-unicode-bidi.js css-unset-value.js css-variables.js css-widows-orphans.js css-writing-mode.js css-zoom.js css3-attr.js css3-boxsizing.js css3-colors.js css3-cursors-grab.js css3-cursors-newer.js css3-cursors.js css3-tabsize.js currentcolor.js custom-elements.js custom-elementsv1.js customevent.js datalist.js dataset.js datauri.js details.js deviceorientation.js devicepixelratio.js dialog.js dispatchevent.js do-not-track.js document-currentscript.js document-evaluate-xpath.js document-execcommand.js document-scrollingelement.js documenthead.js dom-manip-convenience.js dom-range.js domcontentloaded.js domfocusin-domfocusout-events.js dommatrix.js download.js dragndrop.js element-closest.js element-from-point.js element-scroll-methods.js eme.js eot.js es5.js es6-class.js es6-generators.js es6-module-dynamic-import.js es6-module-nomodule.js es6-module.js es6-number.js es6-string-includes.js es6.js eventsource.js feature-policy.js fetch.js fieldset-disabled.js fileapi.js filereader.js filereadersync.js filesystem.js flac.js flexbox.js flow-root.js focusin-focusout-events.js focusoptions-preventscroll.js font-family-system-ui.js font-feature.js font-kerning.js font-loading.js font-size-adjust.js font-smooth.js font-unicode-range.js font-variant-alternates.js font-variant-east-asian.js font-variant-numeric.js fontface.js form-attribute.js form-submit-attributes.js form-validation.js forms.js fullscreen.js gamepad.js geolocation.js getboundingclientrect.js getcomputedstyle.js getelementsbyclassname.js getrandomvalues.js gyroscope.js hardwareconcurrency.js hashchange.js heif.js hevc.js hidden.js high-resolution-time.js history.js html-media-capture.js html5semantic.js http-live-streaming.js http2.js iframe-sandbox.js iframe-seamless.js iframe-srcdoc.js imagecapture.js ime.js img-naturalwidth-naturalheight.js imports.js indeterminate-checkbox.js indexeddb.js indexeddb2.js inline-block.js innertext.js input-autocomplete-onoff.js input-color.js input-datetime.js input-email-tel-url.js input-event.js input-file-accept.js input-file-directory.js input-file-multiple.js input-inputmode.js input-minlength.js input-number.js input-pattern.js input-placeholder.js input-range.js input-search.js input-selection.js insert-adjacent.js insertadjacenthtml.js internationalization-plural-rul.js internationalization.js intersectionobserver.js intrinsic-width.js jpeg2000.js jpegxr.js json.js justify-content-space-evenly.js kerning-pairs-ligatures.js keyboardevent-charcode.js keyboardevent-code.js keyboardevent-getmodifierstate.js keyboardevent-key.js keyboardevent-location.js keyboardevent-which.js lazyload.js let.js link-icon-png.js link-icon-svg.js link-rel-dns-prefetch.js link-rel-preconnect.js link-rel-prefetch.js link-rel-preload.js link-rel-prerender.js localecompare.js magnetometer.js matchesselector.js matchmedia.js mathml.js maxlength.js media-attribute.js media-fragments.js media-session-api.js mediacapture-fromelement.js mediarecorder.js mediasource.js menu.js meta-theme-color.js meter.js midi.js minmaxwh.js mp3.js mpeg-dash.js mpeg4.js multibackgrounds.js multicolumn.js mutation-events.js mutationobserver.js namevalue-storage.js nav-timing.js navigator-language.js netinfo.js node-contains.js node-parentelement.js notifications.js object-entries.js object-fit.js object-observe.js object-values.js objectrtc.js offline-apps.js offscreencanvas.js ogg-vorbis.js ogv.js ol-reversed.js once-event-listener.js online-status.js opus.js orientation-sensor.js outline.js pad-start-end.js page-transition-events.js pagevisibility.js passive-event-listener.js passwordrules.js path2d.js payment-request.js permissions-api.js picture-in-picture.js picture.js ping.js png-alpha.js pointer-events.js pointer.js pointerlock.js prefers-color-scheme.js prefers-reduced-motion.js progress.js promise-finally.js promises.js proximity.js proxy.js publickeypinning.js push-api.js queryselector.js readonly-attr.js referrer-policy.js registerprotocolhandler.js rel-noopener.js rel-noreferrer.js rellist.js rem.js requestanimationframe.js requestidlecallback.js resizeobserver.js resource-timing.js rest-parameters.js rtcpeerconnection.js ruby.js run-in.js same-site-cookie-attribute.js screen-orientation.js script-async.js script-defer.js scrollintoview.js scrollintoviewifneeded.js sdch.js selection-api.js server-timing.js serviceworkers.js setimmediate.js sha-2.js shadowdom.js shadowdomv1.js sharedarraybuffer.js sharedworkers.js sni.js spdy.js speech-recognition.js speech-synthesis.js spellcheck-attribute.js sql-storage.js srcset.js stopimmediatepropagation.js stream.js streams.js stricttransportsecurity.js style-scoped.js subresource-integrity.js svg-css.js svg-filters.js svg-fonts.js svg-fragment.js svg-html.js svg-html5.js svg-img.js svg-smil.js svg.js symbols.js tabindex-attr.js template-literals.js template.js testfeat.js text-decoration.js text-emphasis.js text-overflow.js text-size-adjust.js text-stroke.js textcontent.js textencoder.js tls1-1.js tls1-2.js tls1-3.js token-binding.js touch.js transforms2d.js transforms3d.js ttf.js typedarrays.js u2f.js unhandledrejection.js upgradeinsecurerequests.js url.js urlsearchparams.js use-strict.js user-select-none.js user-timing.js variable-fonts.js vibration.js video.js videotracks.js viewport-units.js wai-aria.js wasm.js wav.js wbr-element.js web-animation.js web-app-manifest.js web-bluetooth.js web-share.js webauthn.js webgl.js webgl2.js webm.js webp.js websockets.js webusb.js webvr.js webvtt.js webworkers.js will-change.js woff.js woff2.js word-break.js wordwrap.js x-doc-messaging.js x-frame-options.js xhr2.js xhtml.js xhtmlsmil.js xml-serializer.js regions AD.js AE.js AF.js AG.js AI.js AL.js AM.js AN.js AO.js AR.js AS.js AT.js AU.js AW.js AX.js AZ.js BA.js BB.js BD.js BE.js BF.js BG.js BH.js BI.js BJ.js BM.js BN.js BO.js BR.js BS.js BT.js BW.js BY.js BZ.js CA.js CD.js CF.js CG.js CH.js CI.js CK.js CL.js CM.js CN.js CO.js CR.js CU.js CV.js CX.js CY.js CZ.js DE.js DJ.js DK.js DM.js DO.js DZ.js EC.js EE.js EG.js ER.js ES.js ET.js FI.js FJ.js FK.js FM.js FO.js FR.js GA.js GB.js GD.js GE.js GF.js GG.js GH.js GI.js GL.js GM.js GN.js GP.js GQ.js GR.js GT.js GU.js GW.js GY.js HK.js HN.js HR.js HT.js HU.js ID.js IE.js IL.js IM.js IN.js IQ.js IR.js IS.js IT.js JE.js JM.js JO.js JP.js KE.js KG.js KH.js KI.js KM.js KN.js KP.js KR.js KW.js KY.js KZ.js LA.js LB.js LC.js LI.js LK.js LR.js LS.js LT.js LU.js LV.js LY.js MA.js MC.js MD.js ME.js MG.js MH.js MK.js ML.js MM.js MN.js MO.js MP.js MQ.js MR.js MS.js MT.js MU.js MV.js MW.js MX.js MY.js MZ.js NA.js NC.js NE.js NF.js NG.js NI.js NL.js NO.js NP.js NR.js NU.js NZ.js OM.js PA.js PE.js PF.js PG.js PH.js PK.js PL.js PM.js PN.js PR.js PS.js PT.js PW.js PY.js QA.js RE.js RO.js RS.js RU.js RW.js SA.js SB.js SC.js SD.js SE.js SG.js SH.js SI.js SK.js SL.js SM.js SN.js SO.js SR.js ST.js SV.js SY.js SZ.js TC.js TD.js TG.js TH.js TJ.js TK.js TL.js TM.js TN.js TO.js TR.js TT.js TV.js TW.js TZ.js UA.js UG.js US.js UY.js UZ.js VA.js VC.js VE.js VG.js VI.js VN.js VU.js WF.js WS.js YE.js YT.js ZA.js ZM.js ZW.js alt-af.js alt-an.js alt-as.js alt-eu.js alt-na.js alt-oc.js alt-sa.js alt-ww.js dist lib statuses.js supported.js unpacker agents.js browserVersions.js browsers.js feature.js features.js index.js region.js package.json caseless README.md index.js package.json test.js chalk index.js package.json readme.md templates.js types index.d.ts chokidar CHANGELOG.md README.md index.js lib fsevents-handler.js nodefs-handler.js package.json types index.d.ts chownr README.md chownr.js package.json chrome-trace-event .travis.yml CHANGES.md LICENSE.txt README.md dist trace-event.d.ts trace-event.js package.json tsconfig.json cipher-base .travis.yml README.md index.js package.json test.js class-utils README.md index.js node_modules define-property README.md index.js package.json package.json cliui CHANGELOG.md LICENSE.txt README.md index.js package.json clone-deep README.md index.js package.json code-point-at index.js package.json readme.md collection-visit README.md index.js package.json color-convert CHANGELOG.md README.md conversions.js index.js package.json route.js color-name .eslintrc.json README.md index.js package.json test.js combined-stream Readme.md lib combined_stream.js defer.js package.json commander CHANGELOG.md Readme.md index.js package.json typings index.d.ts commondir example dir.js index.js package.json test dirs.js component-emitter History.md Readme.md index.js package.json compressible HISTORY.md README.md index.js package.json compression HISTORY.md README.md index.js package.json concat-map .travis.yml example map.js index.js package.json test map.js concat-stream index.js package.json readme.md connect-history-api-fallback CHANGELOG.md README.md lib index.js package.json console-browserify .testem.json .travis.yml README.md index.js package.json test index.js static index.html test-adapter.js console-control-strings README.md index.js package.json constants-browserify README.md build.sh constants.json package.json test.js content-disposition HISTORY.md README.md index.js package.json content-type HISTORY.md README.md index.js package.json convert-source-map README.md index.js package.json cookie-signature History.md Readme.md index.js package.json cookie HISTORY.md README.md index.js package.json copy-concurrently README.md copy.js is-windows.js package.json copy-descriptor index.js package.json core-js-compat README.md data.json entries.json get-modules-list-for-target-version.js index.js modules-by-versions.json node_modules semver CHANGELOG.md README.md package.json semver.js package.json core-js-pure README.md configurator.js es README.md array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js function bind.js has-instance.js index.js name.js virtual bind.js index.js index.js instance bind.js code-point-at.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js json index.js stringify.js to-string-tag.js map index.js math acosh.js asinh.js atanh.js cbrt.js clz32.js cosh.js expm1.js fround.js hypot.js imul.js index.js log10.js log1p.js log2.js sign.js sinh.js tanh.js to-string-tag.js trunc.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js parse-float.js parse-int.js promise finally.js index.js reflect apply.js construct.js define-property.js delete-property.js get-own-property-descriptor.js get-prototype-of.js get.js has.js index.js is-extensible.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set index.js string anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match.js pad-end.js pad-start.js raw.js repeat.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js pad-end.js pad-start.js repeat.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js methods.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js weak-map index.js weak-set index.js features README.md aggregate-error.js array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js last-index.js last-item.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js clear-immediate.js composite-key.js composite-symbol.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js dom-collections for-each.js index.js iterator.js function bind.js has-instance.js index.js name.js virtual bind.js index.js get-iterator-method.js get-iterator.js global-this.js index.js instance at.js bind.js code-point-at.js code-points.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js match-all.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js replace-all.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js is-iterable.js json index.js stringify.js to-string-tag.js map delete-all.js every.js filter.js find-key.js find.js from.js group-by.js includes.js index.js key-by.js key-of.js map-keys.js map-values.js merge.js of.js reduce.js some.js update.js math acosh.js asinh.js atanh.js cbrt.js clamp.js clz32.js cosh.js deg-per-rad.js degrees.js expm1.js fround.js fscale.js hypot.js iaddh.js imul.js imulh.js index.js isubh.js log10.js log1p.js log2.js rad-per-deg.js radians.js scale.js seeded-prng.js sign.js signbit.js sinh.js tanh.js to-string-tag.js trunc.js umulh.js number constructor.js epsilon.js from-string.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js observable index.js parse-float.js parse-int.js promise all-settled.js any.js finally.js index.js try.js queue-microtask.js reflect apply.js construct.js define-metadata.js define-property.js delete-metadata.js delete-property.js get-metadata-keys.js get-metadata.js get-own-metadata-keys.js get-own-metadata.js get-own-property-descriptor.js get-prototype-of.js get.js has-metadata.js has-own-metadata.js has.js index.js is-extensible.js metadata.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set-immediate.js set-interval.js set-timeout.js set add-all.js delete-all.js difference.js every.js filter.js find.js from.js index.js intersection.js is-disjoint-from.js is-subset-of.js is-superset-of.js join.js map.js of.js reduce.js some.js symmetric-difference.js union.js string anchor.js at.js big.js blink.js bold.js code-point-at.js code-points.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match-all.js match.js pad-end.js pad-start.js raw.js repeat.js replace-all.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js at.js big.js blink.js bold.js code-point-at.js code-points.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js match-all.js pad-end.js pad-start.js repeat.js replace-all.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js dispose.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js observable.js pattern-match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js url-search-params index.js url index.js to-json.js weak-map delete-all.js from.js index.js of.js weak-set add-all.js delete-all.js from.js index.js of.js index.js internals README.md a-function.js add-to-unscopables.js advance-string-index.js an-instance.js an-object.js array-buffer-view-core.js array-buffer.js array-copy-within.js array-fill.js array-for-each.js array-from.js array-includes.js array-last-index-of.js array-method-has-species-support.js array-methods.js array-reduce.js array-species-create.js bind-context.js call-with-safe-iteration-closing.js check-correctness-of-iteration.js classof-raw.js classof.js collection-add-all.js collection-delete-all.js collection-from.js collection-of.js collection-strong.js collection-weak.js collection.js composite-key.js copy-constructor-properties.js correct-is-regexp-logic.js correct-prototype-getter.js create-html.js create-iterator-constructor.js create-property-descriptor.js create-property.js date-to-iso-string.js date-to-primitive.js define-iterator.js define-well-known-symbol.js descriptors.js document-create-element.js dom-iterables.js entry-unbind.js entry-virtual.js enum-bug-keys.js enum-keys.js export.js fails.js fix-regexp-well-known-symbol-logic.js flatten-into-array.js forced-object-prototype-accessors-methods.js forced-string-html-method.js forced-string-trim-method.js freezing.js function-bind.js function-to-string.js get-built-in.js get-iterator-method.js get-iterator.js get-map-iterator.js get-set-iterator.js global.js has.js hidden-keys.js hide.js host-report-errors.js html.js ie8-dom-define.js indexed-object.js inherit-if-required.js internal-metadata.js internal-state.js is-array-iterator-method.js is-array.js is-forced.js is-integer.js is-iterable.js is-object.js is-pure.js is-regexp.js iterate.js iterators-core.js iterators.js math-expm1.js math-fround.js math-log1p.js math-scale.js math-sign.js microtask.js native-symbol.js native-url.js native-weak-map.js new-promise-capability.js number-is-finite.js object-assign.js object-create.js object-define-properties.js object-define-property.js object-get-own-property-descriptor.js object-get-own-property-names-external.js object-get-own-property-names.js object-get-own-property-symbols.js object-get-prototype-of.js object-keys-internal.js object-keys.js object-property-is-enumerable.js object-set-prototype-of.js object-to-array.js object-to-string.js own-keys.js parse-float.js parse-int.js path.js perform.js promise-resolve.js punycode-to-ascii.js redefine-all.js redefine.js reflect-metadata.js regexp-exec-abstract.js regexp-exec.js regexp-flags.js require-object-coercible.js same-value-zero.js same-value.js set-global.js set-species.js set-to-string-tag.js shared-key.js shared.js sloppy-array-method.js species-constructor.js string-at.js string-pad.js string-repeat.js string-trim.js task.js this-number-value.js to-absolute-index.js to-index.js to-indexed-object.js to-integer.js to-length.js to-object.js to-offset.js to-primitive.js typed-array-constructor.js typed-array-from.js typed-arrays-constructors-requires-wrappers.js uid.js user-agent.js validate-set-prototype-of-arguments.js validate-string-method-arguments.js webkit-string-pad-bug.js well-known-symbol.js whitespaces.js wrapped-well-known-symbol.js modules README.md es.array-buffer.constructor.js es.array-buffer.is-view.js es.array-buffer.slice.js es.array.concat.js es.array.copy-within.js es.array.every.js es.array.fill.js es.array.filter.js es.array.find-index.js es.array.find.js es.array.flat-map.js es.array.flat.js es.array.for-each.js es.array.from.js es.array.includes.js es.array.index-of.js es.array.is-array.js es.array.iterator.js es.array.join.js es.array.last-index-of.js es.array.map.js es.array.of.js es.array.reduce-right.js es.array.reduce.js es.array.reverse.js es.array.slice.js es.array.some.js es.array.sort.js es.array.species.js es.array.splice.js es.array.unscopables.flat-map.js es.array.unscopables.flat.js es.data-view.js es.date.now.js es.date.to-iso-string.js es.date.to-json.js es.date.to-primitive.js es.date.to-string.js es.function.bind.js es.function.has-instance.js es.function.name.js es.json.to-string-tag.js es.map.js es.math.acosh.js es.math.asinh.js es.math.atanh.js es.math.cbrt.js es.math.clz32.js es.math.cosh.js es.math.expm1.js es.math.fround.js es.math.hypot.js es.math.imul.js es.math.log10.js es.math.log1p.js es.math.log2.js es.math.sign.js es.math.sinh.js es.math.tanh.js es.math.to-string-tag.js es.math.trunc.js es.number.constructor.js es.number.epsilon.js es.number.is-finite.js es.number.is-integer.js es.number.is-nan.js es.number.is-safe-integer.js es.number.max-safe-integer.js es.number.min-safe-integer.js es.number.parse-float.js es.number.parse-int.js es.number.to-fixed.js es.number.to-precision.js es.object.assign.js es.object.create.js es.object.define-getter.js es.object.define-properties.js es.object.define-property.js es.object.define-setter.js es.object.entries.js es.object.freeze.js es.object.from-entries.js es.object.get-own-property-descriptor.js es.object.get-own-property-descriptors.js es.object.get-own-property-names.js es.object.get-prototype-of.js es.object.is-extensible.js es.object.is-frozen.js es.object.is-sealed.js es.object.is.js es.object.keys.js es.object.lookup-getter.js es.object.lookup-setter.js es.object.prevent-extensions.js es.object.seal.js es.object.set-prototype-of.js es.object.to-string.js es.object.values.js es.parse-float.js es.parse-int.js es.promise.finally.js es.promise.js es.reflect.apply.js es.reflect.construct.js es.reflect.define-property.js es.reflect.delete-property.js es.reflect.get-own-property-descriptor.js es.reflect.get-prototype-of.js es.reflect.get.js es.reflect.has.js es.reflect.is-extensible.js es.reflect.own-keys.js es.reflect.prevent-extensions.js es.reflect.set-prototype-of.js es.reflect.set.js es.regexp.constructor.js es.regexp.exec.js es.regexp.flags.js es.regexp.to-string.js es.set.js es.string.anchor.js es.string.big.js es.string.blink.js es.string.bold.js es.string.code-point-at.js es.string.ends-with.js es.string.fixed.js es.string.fontcolor.js es.string.fontsize.js es.string.from-code-point.js es.string.includes.js es.string.italics.js es.string.iterator.js es.string.link.js es.string.match.js es.string.pad-end.js es.string.pad-start.js es.string.raw.js es.string.repeat.js es.string.replace.js es.string.search.js es.string.small.js es.string.split.js es.string.starts-with.js es.string.strike.js es.string.sub.js es.string.sup.js es.string.trim-end.js es.string.trim-start.js es.string.trim.js es.symbol.async-iterator.js es.symbol.description.js es.symbol.has-instance.js es.symbol.is-concat-spreadable.js es.symbol.iterator.js es.symbol.js es.symbol.match.js es.symbol.replace.js es.symbol.search.js es.symbol.species.js es.symbol.split.js es.symbol.to-primitive.js es.symbol.to-string-tag.js es.symbol.unscopables.js es.typed-array.copy-within.js es.typed-array.every.js es.typed-array.fill.js es.typed-array.filter.js es.typed-array.find-index.js es.typed-array.find.js es.typed-array.float32-array.js es.typed-array.float64-array.js es.typed-array.for-each.js es.typed-array.from.js es.typed-array.includes.js es.typed-array.index-of.js es.typed-array.int16-array.js es.typed-array.int32-array.js es.typed-array.int8-array.js es.typed-array.iterator.js es.typed-array.join.js es.typed-array.last-index-of.js es.typed-array.map.js es.typed-array.of.js es.typed-array.reduce-right.js es.typed-array.reduce.js es.typed-array.reverse.js es.typed-array.set.js es.typed-array.slice.js es.typed-array.some.js es.typed-array.sort.js es.typed-array.subarray.js es.typed-array.to-locale-string.js es.typed-array.to-string.js es.typed-array.uint16-array.js es.typed-array.uint32-array.js es.typed-array.uint8-array.js es.typed-array.uint8-clamped-array.js es.weak-map.js es.weak-set.js esnext.aggregate-error.js esnext.array.last-index.js esnext.array.last-item.js esnext.composite-key.js esnext.composite-symbol.js esnext.global-this.js esnext.map.delete-all.js esnext.map.every.js esnext.map.filter.js esnext.map.find-key.js esnext.map.find.js esnext.map.from.js esnext.map.group-by.js esnext.map.includes.js esnext.map.key-by.js esnext.map.key-of.js esnext.map.map-keys.js esnext.map.map-values.js esnext.map.merge.js esnext.map.of.js esnext.map.reduce.js esnext.map.some.js esnext.map.update.js esnext.math.clamp.js esnext.math.deg-per-rad.js esnext.math.degrees.js esnext.math.fscale.js esnext.math.iaddh.js esnext.math.imulh.js esnext.math.isubh.js esnext.math.rad-per-deg.js esnext.math.radians.js esnext.math.scale.js esnext.math.seeded-prng.js esnext.math.signbit.js esnext.math.umulh.js esnext.number.from-string.js esnext.observable.js esnext.promise.all-settled.js esnext.promise.any.js esnext.promise.try.js esnext.reflect.define-metadata.js esnext.reflect.delete-metadata.js esnext.reflect.get-metadata-keys.js esnext.reflect.get-metadata.js esnext.reflect.get-own-metadata-keys.js esnext.reflect.get-own-metadata.js esnext.reflect.has-metadata.js esnext.reflect.has-own-metadata.js esnext.reflect.metadata.js esnext.set.add-all.js esnext.set.delete-all.js esnext.set.difference.js esnext.set.every.js esnext.set.filter.js esnext.set.find.js esnext.set.from.js esnext.set.intersection.js esnext.set.is-disjoint-from.js esnext.set.is-subset-of.js esnext.set.is-superset-of.js esnext.set.join.js esnext.set.map.js esnext.set.of.js esnext.set.reduce.js esnext.set.some.js esnext.set.symmetric-difference.js esnext.set.union.js esnext.string.at.js esnext.string.code-points.js esnext.string.match-all.js esnext.string.replace-all.js esnext.symbol.dispose.js esnext.symbol.observable.js esnext.symbol.pattern-match.js esnext.weak-map.delete-all.js esnext.weak-map.from.js esnext.weak-map.of.js esnext.weak-set.add-all.js esnext.weak-set.delete-all.js esnext.weak-set.from.js esnext.weak-set.of.js web.dom-collections.for-each.js web.dom-collections.iterator.js web.immediate.js web.queue-microtask.js web.timers.js web.url-search-params.js web.url.js web.url.to-json.js package.json proposals array-last.js collection-methods.js collection-of-from.js efficient-64-bit-arithmetic.js global-this.js index.js keys-composition.js math-extensions.js math-signbit.js number-from-string.js observable.js pattern-matching.js promise-all-settled.js promise-any.js promise-try.js reflect-metadata.js seeded-random.js set-methods.js string-at.js string-code-points.js string-match-all.js string-replace-all.js url.js using-statement.js stable README.md array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js clear-immediate.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js dom-collections for-each.js index.js iterator.js function bind.js has-instance.js index.js name.js virtual bind.js index.js global-this.js index.js instance bind.js code-point-at.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js json index.js stringify.js to-string-tag.js map index.js math acosh.js asinh.js atanh.js cbrt.js clz32.js cosh.js expm1.js fround.js hypot.js imul.js index.js log10.js log1p.js log2.js sign.js sinh.js tanh.js to-string-tag.js trunc.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js parse-float.js parse-int.js promise finally.js index.js queue-microtask.js reflect apply.js construct.js define-property.js delete-property.js get-own-property-descriptor.js get-prototype-of.js get.js has.js index.js is-extensible.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set-immediate.js set-interval.js set-timeout.js set index.js string anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match.js pad-end.js pad-start.js raw.js repeat.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js pad-end.js pad-start.js repeat.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js url-search-params index.js url index.js to-json.js weak-map index.js weak-set index.js stage 0.js 1.js 2.js 3.js 4.js README.md index.js pre.js web README.md dom-collections.js immediate.js index.js queue-microtask.js timers.js url-search-params.js url.js core-js README.md configurator.js es README.md array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js function bind.js has-instance.js index.js name.js virtual bind.js index.js index.js instance bind.js code-point-at.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js json index.js stringify.js to-string-tag.js map index.js math acosh.js asinh.js atanh.js cbrt.js clz32.js cosh.js expm1.js fround.js hypot.js imul.js index.js log10.js log1p.js log2.js sign.js sinh.js tanh.js to-string-tag.js trunc.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js parse-float.js parse-int.js promise finally.js index.js reflect apply.js construct.js define-property.js delete-property.js get-own-property-descriptor.js get-prototype-of.js get.js has.js index.js is-extensible.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set index.js string anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match.js pad-end.js pad-start.js raw.js repeat.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js pad-end.js pad-start.js repeat.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js methods.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js weak-map index.js weak-set index.js features README.md aggregate-error.js array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js last-index.js last-item.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js clear-immediate.js composite-key.js composite-symbol.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js dom-collections for-each.js index.js iterator.js function bind.js has-instance.js index.js name.js virtual bind.js index.js get-iterator-method.js get-iterator.js global-this.js index.js instance at.js bind.js code-point-at.js code-points.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js match-all.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js replace-all.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js is-iterable.js json index.js stringify.js to-string-tag.js map delete-all.js every.js filter.js find-key.js find.js from.js group-by.js includes.js index.js key-by.js key-of.js map-keys.js map-values.js merge.js of.js reduce.js some.js update.js math acosh.js asinh.js atanh.js cbrt.js clamp.js clz32.js cosh.js deg-per-rad.js degrees.js expm1.js fround.js fscale.js hypot.js iaddh.js imul.js imulh.js index.js isubh.js log10.js log1p.js log2.js rad-per-deg.js radians.js scale.js seeded-prng.js sign.js signbit.js sinh.js tanh.js to-string-tag.js trunc.js umulh.js number constructor.js epsilon.js from-string.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js observable index.js parse-float.js parse-int.js promise all-settled.js any.js finally.js index.js try.js queue-microtask.js reflect apply.js construct.js define-metadata.js define-property.js delete-metadata.js delete-property.js get-metadata-keys.js get-metadata.js get-own-metadata-keys.js get-own-metadata.js get-own-property-descriptor.js get-prototype-of.js get.js has-metadata.js has-own-metadata.js has.js index.js is-extensible.js metadata.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set-immediate.js set-interval.js set-timeout.js set add-all.js delete-all.js difference.js every.js filter.js find.js from.js index.js intersection.js is-disjoint-from.js is-subset-of.js is-superset-of.js join.js map.js of.js reduce.js some.js symmetric-difference.js union.js string anchor.js at.js big.js blink.js bold.js code-point-at.js code-points.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match-all.js match.js pad-end.js pad-start.js raw.js repeat.js replace-all.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js at.js big.js blink.js bold.js code-point-at.js code-points.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js match-all.js pad-end.js pad-start.js repeat.js replace-all.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js dispose.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js observable.js pattern-match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js url-search-params index.js url index.js to-json.js weak-map delete-all.js from.js index.js of.js weak-set add-all.js delete-all.js from.js index.js of.js index.js internals README.md a-function.js add-to-unscopables.js advance-string-index.js an-instance.js an-object.js array-buffer-view-core.js array-buffer.js array-copy-within.js array-fill.js array-for-each.js array-from.js array-includes.js array-last-index-of.js array-method-has-species-support.js array-methods.js array-reduce.js array-species-create.js bind-context.js call-with-safe-iteration-closing.js check-correctness-of-iteration.js classof-raw.js classof.js collection-add-all.js collection-delete-all.js collection-from.js collection-of.js collection-strong.js collection-weak.js collection.js composite-key.js copy-constructor-properties.js correct-is-regexp-logic.js correct-prototype-getter.js create-html.js create-iterator-constructor.js create-property-descriptor.js create-property.js date-to-iso-string.js date-to-primitive.js define-iterator.js define-well-known-symbol.js descriptors.js document-create-element.js dom-iterables.js entry-unbind.js entry-virtual.js enum-bug-keys.js enum-keys.js export.js fails.js fix-regexp-well-known-symbol-logic.js flatten-into-array.js forced-object-prototype-accessors-methods.js forced-string-html-method.js forced-string-trim-method.js freezing.js function-bind.js function-to-string.js get-built-in.js get-iterator-method.js get-iterator.js get-map-iterator.js get-set-iterator.js global.js has.js hidden-keys.js hide.js host-report-errors.js html.js ie8-dom-define.js indexed-object.js inherit-if-required.js internal-metadata.js internal-state.js is-array-iterator-method.js is-array.js is-forced.js is-integer.js is-iterable.js is-object.js is-pure.js is-regexp.js iterate.js iterators-core.js iterators.js math-expm1.js math-fround.js math-log1p.js math-scale.js math-sign.js microtask.js native-symbol.js native-url.js native-weak-map.js new-promise-capability.js number-is-finite.js object-assign.js object-create.js object-define-properties.js object-define-property.js object-get-own-property-descriptor.js object-get-own-property-names-external.js object-get-own-property-names.js object-get-own-property-symbols.js object-get-prototype-of.js object-keys-internal.js object-keys.js object-property-is-enumerable.js object-set-prototype-of.js object-to-array.js object-to-string.js own-keys.js parse-float.js parse-int.js path.js perform.js promise-resolve.js punycode-to-ascii.js redefine-all.js redefine.js reflect-metadata.js regexp-exec-abstract.js regexp-exec.js regexp-flags.js require-object-coercible.js same-value-zero.js same-value.js set-global.js set-species.js set-to-string-tag.js shared-key.js shared.js sloppy-array-method.js species-constructor.js string-at.js string-pad.js string-repeat.js string-trim.js task.js this-number-value.js to-absolute-index.js to-index.js to-indexed-object.js to-integer.js to-length.js to-object.js to-offset.js to-primitive.js typed-array-constructor.js typed-array-from.js typed-arrays-constructors-requires-wrappers.js uid.js user-agent.js validate-set-prototype-of-arguments.js validate-string-method-arguments.js webkit-string-pad-bug.js well-known-symbol.js whitespaces.js wrapped-well-known-symbol.js modules README.md es.array-buffer.constructor.js es.array-buffer.is-view.js es.array-buffer.slice.js es.array.concat.js es.array.copy-within.js es.array.every.js es.array.fill.js es.array.filter.js es.array.find-index.js es.array.find.js es.array.flat-map.js es.array.flat.js es.array.for-each.js es.array.from.js es.array.includes.js es.array.index-of.js es.array.is-array.js es.array.iterator.js es.array.join.js es.array.last-index-of.js es.array.map.js es.array.of.js es.array.reduce-right.js es.array.reduce.js es.array.reverse.js es.array.slice.js es.array.some.js es.array.sort.js es.array.species.js es.array.splice.js es.array.unscopables.flat-map.js es.array.unscopables.flat.js es.data-view.js es.date.now.js es.date.to-iso-string.js es.date.to-json.js es.date.to-primitive.js es.date.to-string.js es.function.bind.js es.function.has-instance.js es.function.name.js es.json.to-string-tag.js es.map.js es.math.acosh.js es.math.asinh.js es.math.atanh.js es.math.cbrt.js es.math.clz32.js es.math.cosh.js es.math.expm1.js es.math.fround.js es.math.hypot.js es.math.imul.js es.math.log10.js es.math.log1p.js es.math.log2.js es.math.sign.js es.math.sinh.js es.math.tanh.js es.math.to-string-tag.js es.math.trunc.js es.number.constructor.js es.number.epsilon.js es.number.is-finite.js es.number.is-integer.js es.number.is-nan.js es.number.is-safe-integer.js es.number.max-safe-integer.js es.number.min-safe-integer.js es.number.parse-float.js es.number.parse-int.js es.number.to-fixed.js es.number.to-precision.js es.object.assign.js es.object.create.js es.object.define-getter.js es.object.define-properties.js es.object.define-property.js es.object.define-setter.js es.object.entries.js es.object.freeze.js es.object.from-entries.js es.object.get-own-property-descriptor.js es.object.get-own-property-descriptors.js es.object.get-own-property-names.js es.object.get-prototype-of.js es.object.is-extensible.js es.object.is-frozen.js es.object.is-sealed.js es.object.is.js es.object.keys.js es.object.lookup-getter.js es.object.lookup-setter.js es.object.prevent-extensions.js es.object.seal.js es.object.set-prototype-of.js es.object.to-string.js es.object.values.js es.parse-float.js es.parse-int.js es.promise.finally.js es.promise.js es.reflect.apply.js es.reflect.construct.js es.reflect.define-property.js es.reflect.delete-property.js es.reflect.get-own-property-descriptor.js es.reflect.get-prototype-of.js es.reflect.get.js es.reflect.has.js es.reflect.is-extensible.js es.reflect.own-keys.js es.reflect.prevent-extensions.js es.reflect.set-prototype-of.js es.reflect.set.js es.regexp.constructor.js es.regexp.exec.js es.regexp.flags.js es.regexp.to-string.js es.set.js es.string.anchor.js es.string.big.js es.string.blink.js es.string.bold.js es.string.code-point-at.js es.string.ends-with.js es.string.fixed.js es.string.fontcolor.js es.string.fontsize.js es.string.from-code-point.js es.string.includes.js es.string.italics.js es.string.iterator.js es.string.link.js es.string.match.js es.string.pad-end.js es.string.pad-start.js es.string.raw.js es.string.repeat.js es.string.replace.js es.string.search.js es.string.small.js es.string.split.js es.string.starts-with.js es.string.strike.js es.string.sub.js es.string.sup.js es.string.trim-end.js es.string.trim-start.js es.string.trim.js es.symbol.async-iterator.js es.symbol.description.js es.symbol.has-instance.js es.symbol.is-concat-spreadable.js es.symbol.iterator.js es.symbol.js es.symbol.match.js es.symbol.replace.js es.symbol.search.js es.symbol.species.js es.symbol.split.js es.symbol.to-primitive.js es.symbol.to-string-tag.js es.symbol.unscopables.js es.typed-array.copy-within.js es.typed-array.every.js es.typed-array.fill.js es.typed-array.filter.js es.typed-array.find-index.js es.typed-array.find.js es.typed-array.float32-array.js es.typed-array.float64-array.js es.typed-array.for-each.js es.typed-array.from.js es.typed-array.includes.js es.typed-array.index-of.js es.typed-array.int16-array.js es.typed-array.int32-array.js es.typed-array.int8-array.js es.typed-array.iterator.js es.typed-array.join.js es.typed-array.last-index-of.js es.typed-array.map.js es.typed-array.of.js es.typed-array.reduce-right.js es.typed-array.reduce.js es.typed-array.reverse.js es.typed-array.set.js es.typed-array.slice.js es.typed-array.some.js es.typed-array.sort.js es.typed-array.subarray.js es.typed-array.to-locale-string.js es.typed-array.to-string.js es.typed-array.uint16-array.js es.typed-array.uint32-array.js es.typed-array.uint8-array.js es.typed-array.uint8-clamped-array.js es.weak-map.js es.weak-set.js esnext.aggregate-error.js esnext.array.last-index.js esnext.array.last-item.js esnext.composite-key.js esnext.composite-symbol.js esnext.global-this.js esnext.map.delete-all.js esnext.map.every.js esnext.map.filter.js esnext.map.find-key.js esnext.map.find.js esnext.map.from.js esnext.map.group-by.js esnext.map.includes.js esnext.map.key-by.js esnext.map.key-of.js esnext.map.map-keys.js esnext.map.map-values.js esnext.map.merge.js esnext.map.of.js esnext.map.reduce.js esnext.map.some.js esnext.map.update.js esnext.math.clamp.js esnext.math.deg-per-rad.js esnext.math.degrees.js esnext.math.fscale.js esnext.math.iaddh.js esnext.math.imulh.js esnext.math.isubh.js esnext.math.rad-per-deg.js esnext.math.radians.js esnext.math.scale.js esnext.math.seeded-prng.js esnext.math.signbit.js esnext.math.umulh.js esnext.number.from-string.js esnext.observable.js esnext.promise.all-settled.js esnext.promise.any.js esnext.promise.try.js esnext.reflect.define-metadata.js esnext.reflect.delete-metadata.js esnext.reflect.get-metadata-keys.js esnext.reflect.get-metadata.js esnext.reflect.get-own-metadata-keys.js esnext.reflect.get-own-metadata.js esnext.reflect.has-metadata.js esnext.reflect.has-own-metadata.js esnext.reflect.metadata.js esnext.set.add-all.js esnext.set.delete-all.js esnext.set.difference.js esnext.set.every.js esnext.set.filter.js esnext.set.find.js esnext.set.from.js esnext.set.intersection.js esnext.set.is-disjoint-from.js esnext.set.is-subset-of.js esnext.set.is-superset-of.js esnext.set.join.js esnext.set.map.js esnext.set.of.js esnext.set.reduce.js esnext.set.some.js esnext.set.symmetric-difference.js esnext.set.union.js esnext.string.at.js esnext.string.code-points.js esnext.string.match-all.js esnext.string.replace-all.js esnext.symbol.dispose.js esnext.symbol.observable.js esnext.symbol.pattern-match.js esnext.weak-map.delete-all.js esnext.weak-map.from.js esnext.weak-map.of.js esnext.weak-set.add-all.js esnext.weak-set.delete-all.js esnext.weak-set.from.js esnext.weak-set.of.js web.dom-collections.for-each.js web.dom-collections.iterator.js web.immediate.js web.queue-microtask.js web.timers.js web.url-search-params.js web.url.js web.url.to-json.js package.json proposals array-last.js collection-methods.js collection-of-from.js efficient-64-bit-arithmetic.js global-this.js index.js keys-composition.js math-extensions.js math-signbit.js number-from-string.js observable.js pattern-matching.js promise-all-settled.js promise-any.js promise-try.js reflect-metadata.js seeded-random.js set-methods.js string-at.js string-code-points.js string-match-all.js string-replace-all.js url.js using-statement.js stable README.md array-buffer constructor.js index.js is-view.js slice.js array concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js from.js includes.js index-of.js index.js is-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js virtual concat.js copy-within.js entries.js every.js fill.js filter.js find-index.js find.js flat-map.js flat.js for-each.js includes.js index-of.js index.js iterator.js join.js keys.js last-index-of.js map.js reduce-right.js reduce.js reverse.js slice.js some.js sort.js splice.js values.js clear-immediate.js data-view index.js date index.js now.js to-iso-string.js to-json.js to-primitive.js to-string.js dom-collections for-each.js index.js iterator.js function bind.js has-instance.js index.js name.js virtual bind.js index.js global-this.js index.js instance bind.js code-point-at.js concat.js copy-within.js ends-with.js entries.js every.js fill.js filter.js find-index.js find.js flags.js flat-map.js flat.js for-each.js includes.js index-of.js keys.js last-index-of.js map.js pad-end.js pad-start.js reduce-right.js reduce.js repeat.js reverse.js slice.js some.js sort.js splice.js starts-with.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js values.js json index.js stringify.js to-string-tag.js map index.js math acosh.js asinh.js atanh.js cbrt.js clz32.js cosh.js expm1.js fround.js hypot.js imul.js index.js log10.js log1p.js log2.js sign.js sinh.js tanh.js to-string-tag.js trunc.js number constructor.js epsilon.js index.js is-finite.js is-integer.js is-nan.js is-safe-integer.js max-safe-integer.js min-safe-integer.js parse-float.js parse-int.js to-fixed.js to-precision.js virtual index.js to-fixed.js to-precision.js object assign.js create.js define-getter.js define-properties.js define-property.js define-setter.js entries.js freeze.js from-entries.js get-own-property-descriptor.js get-own-property-descriptors.js get-own-property-names.js get-own-property-symbols.js get-prototype-of.js index.js is-extensible.js is-frozen.js is-sealed.js is.js keys.js lookup-getter.js lookup-setter.js prevent-extensions.js seal.js set-prototype-of.js to-string.js values.js parse-float.js parse-int.js promise finally.js index.js queue-microtask.js reflect apply.js construct.js define-property.js delete-property.js get-own-property-descriptor.js get-prototype-of.js get.js has.js index.js is-extensible.js own-keys.js prevent-extensions.js set-prototype-of.js set.js regexp constructor.js flags.js index.js match.js replace.js search.js split.js to-string.js set-immediate.js set-interval.js set-timeout.js set index.js string anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js from-code-point.js includes.js index.js italics.js iterator.js link.js match.js pad-end.js pad-start.js raw.js repeat.js replace.js search.js small.js split.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js virtual anchor.js big.js blink.js bold.js code-point-at.js ends-with.js fixed.js fontcolor.js fontsize.js includes.js index.js italics.js iterator.js link.js pad-end.js pad-start.js repeat.js small.js starts-with.js strike.js sub.js sup.js trim-end.js trim-left.js trim-right.js trim-start.js trim.js symbol async-iterator.js description.js for.js has-instance.js index.js is-concat-spreadable.js iterator.js key-for.js match.js replace.js search.js species.js split.js to-primitive.js to-string-tag.js unscopables.js typed-array copy-within.js entries.js every.js fill.js filter.js find-index.js find.js float32-array.js float64-array.js for-each.js from.js includes.js index-of.js index.js int16-array.js int32-array.js int8-array.js iterator.js join.js keys.js last-index-of.js map.js of.js reduce-right.js reduce.js reverse.js set.js slice.js some.js sort.js subarray.js to-locale-string.js to-string.js uint16-array.js uint32-array.js uint8-array.js uint8-clamped-array.js values.js url-search-params index.js url index.js to-json.js weak-map index.js weak-set index.js stage 0.js 1.js 2.js 3.js 4.js README.md index.js pre.js web README.md dom-collections.js immediate.js index.js queue-microtask.js timers.js url-search-params.js url.js core-util-is README.md lib util.js package.json test.js create-ecdh .travis.yml browser.js index.js package.json readme.md create-hash .travis.yml README.md browser.js index.js md5.js package.json test.js create-hmac README.md browser.js index.js legacy.js package.json cross-spawn CHANGELOG.md README.md index.js lib enoent.js parse.js util escape.js readShebang.js resolveCommand.js package.json crypto-browserify .travis.yml .zuul.yml README.md example bundle.js index.html test.js index.js package.json test aes.js create-hash.js create-hmac.js dh.js ecdh.js index.js node dh.js pbkdf2.js public-encrypt.js random-bytes.js random-fill.js sign.js css-loader CHANGELOG.md README.md dist CssSyntaxError.js Warning.js cjs.js index.js options.json plugins index.js postcss-icss-parser.js postcss-import-parser.js postcss-url-parser.js runtime api.js url-escape.js utils.js package.json cssesc LICENSE-MIT.txt README.md cssesc.js package.json currently-unhandled browser.js core.js index.js package.json readme.md cyclist README.md index.js package.json dashdash CHANGES.md LICENSE.txt README.md lib dashdash.js package.json date-now .testem.json .travis.yml README.md index.js package.json seed.js test index.js static index.html debug .coveralls.yml .travis.yml CHANGELOG.md README.md component.json karma.conf.js node.js package.json src browser.js debug.js index.js inspector-log.js node.js decamelize index.js package.json readme.md decode-uri-component index.js package.json readme.md deep-equal .travis.yml example cmp.js index.js lib is_arguments.js keys.js package.json test cmp.js default-gateway README.md android.js darwin.js freebsd.js ibmi.js index.js linux.js openbsd.js package.json sunos.js win32.js define-properties .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test index.js define-property CHANGELOG.md README.md index.js node_modules is-accessor-descriptor README.md index.js package.json is-data-descriptor README.md index.js package.json is-descriptor README.md index.js package.json package.json del index.d.ts index.js package.json readme.md delayed-stream Readme.md lib delayed_stream.js package.json delegates History.md Readme.md index.js package.json test index.js depd History.md Readme.md index.js lib browser index.js compat callsite-tostring.js event-listener-count.js index.js package.json des.js README.md lib des.js des cbc.js cipher.js des.js ede.js utils.js package.json test cbc-test.js des-test.js ede-test.js fixtures.js utils-test.js destroy README.md index.js package.json detect-file README.md index.js package.json detect-node Readme.md browser.js index.js package.json diffie-hellman .travis.yml browser.js index.js lib dh.js generatePrime.js primes.json package.json readme.md dns-equal .travis.yml README.md index.js package.json test.js dns-packet README.md index.js opcodes.js package.json rcodes.js types.js dns-txt .travis.yml README.md index.js package.json test.js dom-walk README.md example index.js static bundle.js index.html index.js package.json domain-browser HISTORY.md LICENSE.md README.md package.json source index.js duplexify .travis.yml README.md example.js index.js package.json test.js ecc-jsbn README.md index.js lib ec.js sec.js package.json test.js ee-first README.md index.js package.json electron-to-chromium CHANGELOG.md README.md chromium-versions.js full-chromium-versions.js full-versions.js index.js package.json versions.js elliptic README.md lib elliptic.js elliptic curve base.js edwards.js index.js mont.js short.js curves.js ec index.js key.js signature.js eddsa index.js key.js signature.js precomputed secp256k1.js utils.js package.json emojis-list CHANGELOG.md LICENSE.md README.md index.js package.json encodeurl HISTORY.md README.md index.js package.json end-of-stream README.md index.js package.json enhanced-resolve README.md lib AliasFieldPlugin.js AliasPlugin.js AppendPlugin.js CachedInputFileSystem.js CloneBasenamePlugin.js ConcordExtensionsPlugin.js ConcordMainPlugin.js ConcordModulesPlugin.js DescriptionFilePlugin.js DescriptionFileUtils.js DirectoryExistsPlugin.js FileExistsPlugin.js FileKindPlugin.js JoinRequestPlugin.js LogInfoPlugin.js MainFieldPlugin.js ModuleAppendPlugin.js ModuleKindPlugin.js ModulesInHierachicDirectoriesPlugin.js ModulesInRootPlugin.js NextPlugin.js NodeJsInputFileSystem.js ParsePlugin.js Resolver.js ResolverFactory.js ResultPlugin.js SymlinkPlugin.js SyncAsyncFileSystemDecorator.js TryNextPlugin.js UnsafeCachePlugin.js UseFilePlugin.js concord.js createInnerCallback.js createInnerContext.js forEachBail.js getInnerRequest.js getPaths.js globToRegExp.js node.js package.json errno .travis.yml README.md build.js cli.js custom.js errno.js package.json test.js error-ex README.md index.js package.json es-abstract .travis.yml CHANGELOG.md GetIntrinsic.js README.md es2015.js es2016.js es2017.js es2018.js es5.js es6.js es7.js helpers assertRecord.js assign.js forEach.js isFinite.js isNaN.js isPrimitive.js mod.js sign.js index.js operations 2015.js 2016.js 2017.js 2018.js es5.js getOps.js package.json test GetIntrinsic.js diffOps.js es2015.js es2016.js es2017.js es2018.js es5.js es6.js es7.js helpers assertRecord.js values.js index.js tests.js es-to-primitive .jscs.json .travis.yml CHANGELOG.md README.md es2015.js es5.js es6.js helpers isPrimitive.js index.js package.json test es2015.js es5.js es6.js index.js escape-html Readme.md index.js package.json escape-string-regexp index.js package.json readme.md eslint-scope CHANGELOG.md README.md lib definition.js index.js pattern-visitor.js reference.js referencer.js scope-manager.js scope.js variable.js package.json esrecurse README.md esrecurse.js gulpfile.babel.js package.json estraverse estraverse.js gulpfile.js package.json esutils README.md lib ast.js code.js keyword.js utils.js package.json etag HISTORY.md README.md index.js package.json eventemitter3 README.md index.d.ts index.js package.json umd eventemitter3.js eventemitter3.min.js events .airtap.yml .travis.yml History.md Readme.md events.js package.json tests add-listeners.js check-listener-leaks.js common.js errors.js events-list.js index.js legacy-compat.js listener-count.js listeners-side-effects.js listeners.js max-listeners.js method-names.js modify-in-emit.js num-args.js once.js prepend.js remove-all-listeners.js remove-listeners.js set-max-listeners-side-effects.js special-event-names.js subclass.js symbols.js eventsource .travis.yml CONTRIBUTING.md HISTORY.md README.md example eventsource-polyfill.js index.html sse-client.js sse-server.js lib eventsource-polyfill.js eventsource.js package.json evp_bytestokey README.md index.js package.json execa index.js lib errname.js stdio.js package.json readme.md expand-brackets README.md changelog.md index.js lib compilers.js parsers.js utils.js node_modules define-property README.md index.js package.json extend-shallow README.md index.js package.json package.json expand-tilde README.md index.js package.json express History.md Readme.md index.js lib application.js express.js middleware init.js query.js request.js response.js router index.js layer.js route.js utils.js view.js node_modules array-flatten README.md array-flatten.js package.json package.json extend-shallow README.md index.js node_modules is-extendable README.md index.d.ts index.js package.json package.json extend .jscs.json .travis.yml CHANGELOG.md README.md component.json index.js package.json extglob README.md changelog.md index.js lib compilers.js extglob.js parsers.js utils.js node_modules define-property README.md index.js package.json extend-shallow README.md index.js package.json is-accessor-descriptor README.md index.js package.json is-data-descriptor README.md index.js package.json is-descriptor README.md index.js package.json package.json extsprintf README.md lib extsprintf.js package.json fast-deep-equal README.md index.d.ts index.js package.json fast-json-stable-stringify .eslintrc.yml .travis.yml README.md benchmark index.js test.json example key_cmp.js nested.js str.js value_cmp.js index.js package.json test cmp.js nested.js str.js to-json.js fast-levenshtein LICENSE.md README.md levenshtein.js package.json faye-websocket CHANGELOG.md README.md examples autobahn_client.js client.js proxy_server.js server.js sse.html ws.html lib faye eventsource.js websocket.js websocket api.js api event.js event_target.js client.js package.json figgy-pudding CHANGELOG.md LICENSE.md README.md index.js package.json fill-range README.md index.js node_modules extend-shallow README.md index.js package.json package.json finalhandler HISTORY.md README.md index.js package.json find-cache-dir index.js package.json readme.md find-up index.js package.json readme.md findup-sync README.md index.js node_modules is-glob README.md index.js package.json package.json flush-write-stream .travis.yml README.md example.js index.js package.json test.js follow-redirects README.md http.js https.js index.js node_modules debug CHANGELOG.md README.md dist debug.js node.js package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md package.json for-in README.md index.js package.json for-own README.md index.js package.json forever-agent README.md index.js package.json form-data README.md lib browser.js form_data.js populate.js package.json forwarded HISTORY.md README.md index.js package.json fragment-cache README.md index.js package.json fresh HISTORY.md README.md index.js package.json from2 .travis.yml LICENSE.md README.md index.js package.json test.js fs-write-stream-atomic .travis.yml README.md index.js package.json test basic.js chown.js rename-eperm.js rename-fail.js slow-close.js toolong.js fs.realpath README.md index.js old.js package.json fsevents .travis.yml ISSUE_TEMPLATE.md Readme.md fsevents.js install.js node_modules abbrev README.md abbrev.js package.json ansi-regex index.js package.json readme.md aproba README.md index.js package.json are-we-there-yet CHANGES.md README.md index.js package.json tracker-base.js tracker-group.js tracker-stream.js tracker.js balanced-match LICENSE.md README.md index.js package.json brace-expansion README.md index.js package.json chownr README.md chownr.js package.json code-point-at index.js package.json readme.md concat-map .travis.yml example map.js index.js package.json test map.js console-control-strings README.md index.js package.json core-util-is README.md lib util.js package.json test.js debug .coveralls.yml .travis.yml CHANGELOG.md README.md component.json karma.conf.js node.js package.json src browser.js debug.js index.js inspector-log.js node.js deep-extend CHANGELOG.md README.md index.js lib deep-extend.js package.json delegates History.md Readme.md index.js package.json test index.js detect-libc README.md bin detect-libc.js lib detect-libc.js package.json fs-minipass README.md index.js package.json fs.realpath README.md index.js old.js package.json gauge CHANGELOG.md README.md base-theme.js error.js has-color.js index.js package.json plumbing.js process.js progress-bar.js render-template.js set-immediate.js set-interval.js spin.js template-item.js theme-set.js themes.js wide-truncate.js glob README.md changelog.md common.js glob.js package.json sync.js has-unicode README.md index.js package.json iconv-lite Changelog.md README.md encodings dbcs-codec.js dbcs-data.js index.js internal.js sbcs-codec.js sbcs-data-generated.js sbcs-data.js tables big5-added.json cp936.json cp949.json cp950.json eucjp.json gb18030-ranges.json gbk-added.json shiftjis.json utf16.js utf7.js lib bom-handling.js extend-node.js index.d.ts index.js streams.js package.json ignore-walk README.md index.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json ini README.md ini.js package.json is-fullwidth-code-point index.js package.json readme.md isarray .travis.yml README.md component.json index.js package.json test.js minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test dash.js default_bool.js dotted.js long.js parse.js parse_modified.js short.js whitespace.js minipass README.md index.js package.json minizlib README.md constants.js index.js package.json mkdirp .travis.yml bin cmd.js usage.txt examples pow.js index.js package.json test chmod.js clobber.js mkdirp.js opts_fs.js opts_fs_sync.js perm.js perm_sync.js race.js rel.js return.js return_sync.js root.js sync.js umask.js umask_sync.js ms index.js license.md package.json readme.md needle README.md examples deflated-stream.js digest-auth.js download-to-file.js multipart-stream.js parsed-stream.js parsed-stream2.js stream-events.js stream-to-file.js upload-image.js lib auth.js cookies.js decoder.js multipart.js needle.js parsers.js querystring.js license.txt note.xml package.json test basic_auth_spec.js compression_spec.js cookies_spec.js decoder_spec.js errors_spec.js headers_spec.js helpers.js long_string_spec.js output_spec.js parsing_spec.js post_data_spec.js proxy_spec.js querystring_spec.js redirect_spec.js redirect_with_timeout.js request_stream_spec.js response_stream_spec.js socket_pool_spec.js url_spec.js utils formidable.js proxy.js test.js node-pre-gyp CHANGELOG.md README.md appveyor.yml bin node-pre-gyp.cmd contributing.md lib build.js clean.js configure.js info.js install.js node-pre-gyp.js package.js pre-binding.js publish.js rebuild.js reinstall.js reveal.js testbinary.js testpackage.js unpublish.js util abi_crosswalk.json compile.js handle_gyp_opts.js napi.js nw-pre-gyp index.html package.json s3_setup.js versioning.js package.json nopt .travis.yml CHANGELOG.md README.md bin nopt.js examples my-program.js lib nopt.js package.json test basic.js npm-bundled README.md index.js package.json npm-packlist README.md index.js package.json npmlog CHANGELOG.md README.md log.js package.json number-is-nan index.js package.json readme.md object-assign index.js package.json readme.md once README.md once.js package.json os-homedir index.js package.json readme.md os-tmpdir index.js package.json readme.md osenv README.md osenv.js package.json path-is-absolute index.js package.json readme.md process-nextick-args index.js license.md package.json readme.md rc README.md browser.js cli.js index.js lib utils.js node_modules minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js short.js stop_early.js unknown.js whitespace.js package.json test ini.js nested-env-vars.js test.js readable-stream .travis.yml CONTRIBUTING.md GOVERNANCE.md README.md doc wg-meetings 2015-01-30.md duplex-browser.js duplex.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams BufferList.js destroy.js stream-browser.js stream.js package.json passthrough.js readable-browser.js readable.js transform.js writable-browser.js writable.js rimraf README.md bin.js package.json rimraf.js safe-buffer README.md index.d.ts index.js package.json safer-buffer Porting-Buffer.md Readme.md dangerous.js package.json safer.js tests.js sax README.md lib sax.js package.json semver README.md package.json semver.js set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json signal-exit CHANGELOG.md LICENSE.txt README.md index.js package.json signals.js string-width index.js package.json readme.md string_decoder .travis.yml README.md lib string_decoder.js package.json strip-ansi index.js package.json readme.md strip-json-comments index.js package.json readme.md tar README.md index.js lib buffer.js create.js extract.js header.js high-level-opt.js large-numbers.js list.js mkdir.js mode-fix.js pack.js parse.js pax.js read-entry.js replace.js types.js unpack.js update.js warn-mixin.js winchars.js write-entry.js package.json util-deprecate History.md README.md browser.js node.js package.json wide-align README.md align.js package.json wrappy README.md package.json wrappy.js yallist README.md iterator.js package.json yallist.js package.json fstream .travis.yml README.md examples filter-pipe.js pipe.js reader.js symlink-write.js fstream.js lib abstract.js collect.js dir-reader.js dir-writer.js file-reader.js file-writer.js get-type.js link-reader.js link-writer.js proxy-reader.js proxy-writer.js reader.js socket-reader.js writer.js package.json function-bind .jscs.json .travis.yml README.md implementation.js index.js package.json test index.js gauge CHANGELOG.md README.md base-theme.js error.js has-color.js index.js node_modules ansi-regex index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.js package.json readme.md package.json plumbing.js process.js progress-bar.js render-template.js set-immediate.js set-interval.js spin.js template-item.js theme-set.js themes.js wide-truncate.js gaze README.md lib gaze.js helper.js package.json get-caller-file LICENSE.md README.md index.js package.json get-stdin index.js package.json readme.md get-stream buffer-stream.js index.js package.json readme.md get-value index.js package.json getpass .travis.yml README.md lib index.js package.json glob-parent README.md index.js node_modules is-glob README.md index.js package.json package.json glob README.md changelog.md common.js glob.js package.json sync.js global-modules README.md index.js package.json global-prefix README.md index.js package.json global .travis.yml README.md console.js document.js node_modules process README.md browser.js index.js package.json package.json process.js window.js globals globals.json index.js package.json readme.md globby index.js node_modules pify index.js package.json readme.md package.json readme.md globule README.md lib globule.js package.json graceful-fs README.md clone.js graceful-fs.js legacy-streams.js package.json polyfills.js handle-thing .travis.yml README.md lib handle.js queue.js package.json test api-test.js har-schema README.md lib afterRequest.json beforeRequest.json browser.json cache.json content.json cookie.json creator.json entry.json har.json header.json index.js log.json page.json pageTimings.json postData.json query.json request.json response.json timings.json package.json har-validator README.md lib async.js error.js promise.js package.json has-ansi index.js node_modules ansi-regex index.js package.json readme.md package.json readme.md has-flag index.js package.json readme.md has-symbols .travis.yml CHANGELOG.md README.md index.js package.json shams.js test index.js shams core-js.js get-own-property-symbols.js tests.js has-unicode README.md index.js package.json has-value README.md index.js package.json has-values README.md index.js node_modules kind-of README.md index.js package.json package.json has README.md package.json src index.js test index.js hash-base README.md index.js package.json hash.js .eslintrc.js .travis.yml README.md lib hash.d.ts hash.js hash common.js hmac.js ripemd.js sha.js sha 1.js 224.js 256.js 384.js 512.js common.js utils.js package.json test hash-test.js hmac-test.js hmac-drbg .travis.yml README.md lib hmac-drbg.js package.json test drbg-test.js fixtures hmac-drbg-nist.json hoist-non-react-statics CHANGELOG.md LICENSE.md README.md dist hoist-non-react-statics.cjs.js hoist-non-react-statics.js hoist-non-react-statics.min.js package.json src index.js homedir-polyfill README.md index.js package.json polyfill.js hosted-git-info CHANGELOG.md README.md git-host-info.js git-host.js index.js package.json hpack.js .travis.yml README.md lib hpack.js hpack compressor.js decoder.js decompressor.js encoder.js huffman.js static-table.js table.js utils.js package.json test compressor-test.js decoder-test.js decompressor-test.js encoder-test.js fixtures.js tools gen-huffman.js gen-static-table.js utils.js html-entities README.md index.js lib html4-entities.js html5-entities.js xml-entities.js package.json http-deceiver .travis.yml README.md lib deceiver.js package.json test api-test.js http-errors HISTORY.md README.md index.js package.json http-parser-js CHANGELOG.md LICENSE.md README.md http-parser.js package.json http-proxy-middleware CHANGELOG.md README.md index.js lib config-factory.js context-matcher.js errors.js handlers.js index.js logger.js path-rewriter.js router.js package.json http-proxy .nyc_output 964792f65a1be0c07a24aa0ccfb5d038.json a290d7f5908ec7d06d33ee34e792483c.json bb60b90ed8ee70af09b130b7e0e44671.json CODE_OF_CONDUCT.md README.md codecov.yml coverage lcov-report base.css block-navigation.js http-proxy common.js.html index.html passes index.html web-incoming.js.html web-outgoing.js.html index.html lib http-proxy.js.html http-proxy common.js.html index.html index.js.html passes index.html web-incoming.js.html web-outgoing.js.html ws-incoming.js.html index.html prettify.css prettify.js sorter.js index.js lib http-proxy.js http-proxy common.js index.js passes web-incoming.js web-outgoing.js ws-incoming.js package.json http-signature CHANGES.md README.md http_signing.md lib index.js parser.js signer.js utils.js verify.js package.json https-browserify index.js package.json iconv-lite .travis.yml Changelog.md README.md encodings dbcs-codec.js dbcs-data.js index.js internal.js sbcs-codec.js sbcs-data-generated.js sbcs-data.js tables big5-added.json cp936.json cp949.json cp950.json eucjp.json gb18030-ranges.json gbk-added.json shiftjis.json utf16.js utf7.js lib bom-handling.js extend-node.js index.d.ts index.js streams.js package.json icss-replace-symbols README.md lib index.js package.json icss-utils LICENSE.md README.md lib createICSSRules.js extractICSS.js index.js replaceSymbols.js replaceValueSymbols.js package.json ieee754 README.md index.js package.json iferr README.md index.coffee index.js package.json test index.coffee import-local fixtures cli.js index.js package.json readme.md imurmurhash README.md imurmurhash.js imurmurhash.min.js package.json in-publish README.md in-install.js in-publish.js index.js not-in-install.js not-in-publish.js package.json test package.json indent-string index.js package.json readme.md indexes-of README.md index.js package.json test.js indexof Readme.md component.json index.js package.json inflight README.md inflight.js package.json inherits README.md inherits.js inherits_browser.js package.json ini README.md ini.js package.json internal-ip index.d.ts index.js node_modules ipaddr.js README.md ipaddr.min.js lib ipaddr.js ipaddr.js.d.ts package.json package.json readme.md interpret README.md index.js package.json invariant CHANGELOG.md README.md browser.js invariant.js package.json invert-kv index.js package.json readme.md ip-regex index.js package.json readme.md ip .travis.yml README.md lib ip.js package.json test api-test.js ipaddr.js README.md ipaddr.min.js lib ipaddr.js ipaddr.js.d.ts package.json is-accessor-descriptor README.md index.js node_modules kind-of README.md index.js package.json package.json is-arrayish .istanbul.yml .travis.yml README.md index.js package.json is-binary-path index.js package.json readme.md is-buffer README.md index.js package.json test basic.js is-callable .istanbul.yml .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test.js is-data-descriptor README.md index.js node_modules kind-of README.md index.js package.json package.json is-date-object .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test.js is-descriptor README.md index.js node_modules kind-of README.md index.js package.json package.json is-extendable README.md index.js package.json is-extglob README.md index.js package.json is-finite index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md is-glob README.md index.js package.json is-number README.md index.js node_modules kind-of README.md index.js package.json package.json is-path-cwd index.js package.json readme.md is-path-in-cwd index.js package.json readme.md is-path-inside index.js package.json readme.md is-plain-object README.md index.d.ts index.js package.json is-regex .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test.js is-stream index.js package.json readme.md is-symbol .jscs.json .travis.yml CHANGELOG.md README.md index.js package.json test index.js is-typedarray LICENSE.md README.md index.js package.json test.js is-utf8 README.md is-utf8.js package.json is-windows README.md index.js package.json is-wsl index.js package.json readme.md isarray .travis.yml README.md component.json index.js package.json test.js isexe README.md index.js mode.js package.json test basic.js windows.js isobject README.md index.d.ts index.js package.json isstream .travis.yml LICENSE.md README.md isstream.js package.json test.js js-base64 .attic test-moment dankogai.js es5.js es6.js index.html large.js moment.js yoshinoya.js LICENSE.md README.md base64.html base64.js base64.min.js bower.json package.js package.json test atob.js dankogai.js es5.js es6.js index.html large.js yoshinoya.js js-levenshtein README.md index.js package.json js-tokens CHANGELOG.md README.md index.js package.json jsbn README.md example.html example.js index.js package.json jsesc LICENSE-MIT.txt README.md jsesc.js package.json json-parse-better-errors CHANGELOG.md LICENSE.md README.md index.js package.json json-schema-traverse .eslintrc.yml .travis.yml README.md index.js package.json spec .eslintrc.yml fixtures schema.js index.spec.js json-schema README.md draft-zyp-json-schema-03.xml draft-zyp-json-schema-04.xml lib links.js validate.js package.json test tests.js json-stringify-safe CHANGELOG.md README.md package.json stringify.js test stringify_test.js json3 README.md lib json3.js json3.min.js package.json json5 CHANGELOG.md LICENSE.md README.md dist index.js lib cli.js index.js parse.js register.js require.js stringify.js unicode.js util.js package.json jsprim CHANGES.md CONTRIBUTING.md README.md lib jsprim.js package.json killable README.md index.js package.json kind-of CHANGELOG.md README.md index.js package.json lcid index.js lcid.json package.json readme.md load-json-file index.js node_modules pify index.js package.json readme.md package.json readme.md loader-runner README.md lib LoaderLoadingError.js LoaderRunner.js loadLoader.js package.json loader-utils CHANGELOG.md README.md lib getCurrentRequest.js getHashDigest.js getOptions.js getRemainingRequest.js index.js interpolateName.js isUrlRequest.js parseQuery.js parseString.js stringifyRequest.js urlToRequest.js package.json locate-path index.js package.json readme.md lodash.assign README.md index.js package.json lodash.clonedeep README.md index.js package.json lodash.mergewith README.md index.js package.json lodash.tail README.md index.js package.json lodash README.md _DataView.js _Hash.js _LazyWrapper.js _ListCache.js _LodashWrapper.js _Map.js _MapCache.js _Promise.js _Set.js _SetCache.js _Stack.js _Symbol.js _Uint8Array.js _WeakMap.js _apply.js _arrayAggregator.js _arrayEach.js _arrayEachRight.js _arrayEvery.js _arrayFilter.js _arrayIncludes.js _arrayIncludesWith.js _arrayLikeKeys.js _arrayMap.js _arrayPush.js _arrayReduce.js _arrayReduceRight.js _arraySample.js _arraySampleSize.js _arrayShuffle.js _arraySome.js _asciiSize.js _asciiToArray.js _asciiWords.js _assignMergeValue.js _assignValue.js _assocIndexOf.js _baseAggregator.js _baseAssign.js _baseAssignIn.js _baseAssignValue.js _baseAt.js _baseClamp.js _baseClone.js _baseConforms.js _baseConformsTo.js _baseCreate.js _baseDelay.js _baseDifference.js _baseEach.js _baseEachRight.js _baseEvery.js _baseExtremum.js _baseFill.js _baseFilter.js _baseFindIndex.js _baseFindKey.js _baseFlatten.js _baseFor.js _baseForOwn.js _baseForOwnRight.js _baseForRight.js _baseFunctions.js _baseGet.js _baseGetAllKeys.js _baseGetTag.js _baseGt.js _baseHas.js _baseHasIn.js _baseInRange.js _baseIndexOf.js _baseIndexOfWith.js _baseIntersection.js _baseInverter.js _baseInvoke.js _baseIsArguments.js _baseIsArrayBuffer.js _baseIsDate.js _baseIsEqual.js _baseIsEqualDeep.js _baseIsMap.js _baseIsMatch.js _baseIsNaN.js _baseIsNative.js _baseIsRegExp.js _baseIsSet.js _baseIsTypedArray.js _baseIteratee.js _baseKeys.js _baseKeysIn.js _baseLodash.js _baseLt.js _baseMap.js _baseMatches.js _baseMatchesProperty.js _baseMean.js _baseMerge.js _baseMergeDeep.js _baseNth.js _baseOrderBy.js _basePick.js _basePickBy.js _baseProperty.js _basePropertyDeep.js _basePropertyOf.js _basePullAll.js _basePullAt.js _baseRandom.js _baseRange.js _baseReduce.js _baseRepeat.js _baseRest.js _baseSample.js _baseSampleSize.js _baseSet.js _baseSetData.js _baseSetToString.js _baseShuffle.js _baseSlice.js _baseSome.js _baseSortBy.js _baseSortedIndex.js _baseSortedIndexBy.js _baseSortedUniq.js _baseSum.js _baseTimes.js _baseToNumber.js _baseToPairs.js _baseToString.js _baseUnary.js _baseUniq.js _baseUnset.js _baseUpdate.js _baseValues.js _baseWhile.js _baseWrapperValue.js _baseXor.js _baseZipObject.js _cacheHas.js _castArrayLikeObject.js _castFunction.js _castPath.js _castRest.js _castSlice.js _charsEndIndex.js _charsStartIndex.js _cloneArrayBuffer.js _cloneBuffer.js _cloneDataView.js _cloneRegExp.js _cloneSymbol.js _cloneTypedArray.js _compareAscending.js _compareMultiple.js _composeArgs.js _composeArgsRight.js _copyArray.js _copyObject.js _copySymbols.js _copySymbolsIn.js _coreJsData.js _countHolders.js _createAggregator.js _createAssigner.js _createBaseEach.js _createBaseFor.js _createBind.js _createCaseFirst.js _createCompounder.js _createCtor.js _createCurry.js _createFind.js _createFlow.js _createHybrid.js _createInverter.js _createMathOperation.js _createOver.js _createPadding.js _createPartial.js _createRange.js _createRecurry.js _createRelationalOperation.js _createRound.js _createSet.js _createToPairs.js _createWrap.js _customDefaultsAssignIn.js _customDefaultsMerge.js _customOmitClone.js _deburrLetter.js _defineProperty.js _equalArrays.js _equalByTag.js _equalObjects.js _escapeHtmlChar.js _escapeStringChar.js _flatRest.js _freeGlobal.js _getAllKeys.js _getAllKeysIn.js _getData.js _getFuncName.js _getHolder.js _getMapData.js _getMatchData.js _getNative.js _getPrototype.js _getRawTag.js _getSymbols.js _getSymbolsIn.js _getTag.js _getValue.js _getView.js _getWrapDetails.js _hasPath.js _hasUnicode.js _hasUnicodeWord.js _hashClear.js _hashDelete.js _hashGet.js _hashHas.js _hashSet.js _initCloneArray.js _initCloneByTag.js _initCloneObject.js _insertWrapDetails.js _isFlattenable.js _isIndex.js _isIterateeCall.js _isKey.js _isKeyable.js _isLaziable.js _isMaskable.js _isMasked.js _isPrototype.js _isStrictComparable.js _iteratorToArray.js _lazyClone.js _lazyReverse.js _lazyValue.js _listCacheClear.js _listCacheDelete.js _listCacheGet.js _listCacheHas.js _listCacheSet.js _mapCacheClear.js _mapCacheDelete.js _mapCacheGet.js _mapCacheHas.js _mapCacheSet.js _mapToArray.js _matchesStrictComparable.js _memoizeCapped.js _mergeData.js _metaMap.js _nativeCreate.js _nativeKeys.js _nativeKeysIn.js _nodeUtil.js _objectToString.js _overArg.js _overRest.js _parent.js _reEscape.js _reEvaluate.js _reInterpolate.js _realNames.js _reorder.js _replaceHolders.js _root.js _safeGet.js _setCacheAdd.js _setCacheHas.js _setData.js _setToArray.js _setToPairs.js _setToString.js _setWrapToString.js _shortOut.js _shuffleSelf.js _stackClear.js _stackDelete.js _stackGet.js _stackHas.js _stackSet.js _strictIndexOf.js _strictLastIndexOf.js _stringSize.js _stringToArray.js _stringToPath.js _toKey.js _toSource.js _unescapeHtmlChar.js _unicodeSize.js _unicodeToArray.js _unicodeWords.js _updateWrapDetails.js _wrapperClone.js add.js after.js array.js ary.js assign.js assignIn.js assignInWith.js assignWith.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js concat.js cond.js conforms.js conformsTo.js constant.js core.js core.min.js countBy.js create.js curry.js curryRight.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsDeep.js defer.js delay.js difference.js differenceBy.js differenceWith.js divide.js drop.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js escape.js escapeRegExp.js every.js extend.js extendWith.js fill.js filter.js find.js findIndex.js findKey.js findLast.js findLastIndex.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fp.js fp F.js T.js __.js _baseConvert.js _convertBrowser.js _falseOptions.js _mapping.js _util.js add.js after.js all.js allPass.js always.js any.js anyPass.js apply.js array.js ary.js assign.js assignAll.js assignAllWith.js assignIn.js assignInAll.js assignInAllWith.js assignInWith.js assignWith.js assoc.js assocPath.js at.js attempt.js before.js bind.js bindAll.js bindKey.js camelCase.js capitalize.js castArray.js ceil.js chain.js chunk.js clamp.js clone.js cloneDeep.js cloneDeepWith.js cloneWith.js collection.js commit.js compact.js complement.js compose.js concat.js cond.js conforms.js conformsTo.js constant.js contains.js convert.js countBy.js create.js curry.js curryN.js curryRight.js curryRightN.js date.js debounce.js deburr.js defaultTo.js defaults.js defaultsAll.js defaultsDeep.js defaultsDeepAll.js defer.js delay.js difference.js differenceBy.js differenceWith.js dissoc.js dissocPath.js divide.js drop.js dropLast.js dropLastWhile.js dropRight.js dropRightWhile.js dropWhile.js each.js eachRight.js endsWith.js entries.js entriesIn.js eq.js equals.js escape.js escapeRegExp.js every.js extend.js extendAll.js extendAllWith.js extendWith.js fill.js filter.js find.js findFrom.js findIndex.js findIndexFrom.js findKey.js findLast.js findLastFrom.js findLastIndex.js findLastIndexFrom.js findLastKey.js first.js flatMap.js flatMapDeep.js flatMapDepth.js flatten.js flattenDeep.js flattenDepth.js flip.js floor.js flow.js flowRight.js forEach.js forEachRight.js forIn.js forInRight.js forOwn.js forOwnRight.js fromPairs.js function.js functions.js functionsIn.js get.js getOr.js groupBy.js gt.js gte.js has.js hasIn.js head.js identical.js identity.js inRange.js includes.js includesFrom.js indexBy.js indexOf.js indexOfFrom.js init.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invertObj.js invoke.js invokeArgs.js invokeArgsMap.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js juxt.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lastIndexOfFrom.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeAll.js mergeAllWith.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js nAry.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitAll.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js pad.js padChars.js padCharsEnd.js padCharsStart.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js path.js pathEq.js pathOr.js paths.js pick.js pickAll.js pickBy.js pipe.js placeholder.js plant.js pluck.js prop.js propEq.js propOr.js property.js propertyOf.js props.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rangeStep.js rangeStepRight.js rearg.js reduce.js reduceRight.js reject.js remove.js repeat.js replace.js rest.js restFrom.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js spreadFrom.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js symmetricDifference.js symmetricDifferenceBy.js symmetricDifferenceWith.js tail.js take.js takeLast.js takeLastWhile.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimChars.js trimCharsEnd.js trimCharsStart.js trimEnd.js trimStart.js truncate.js unapply.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unnest.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js useWith.js util.js value.js valueOf.js values.js valuesIn.js where.js whereEq.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipAll.js zipObj.js zipObject.js zipObjectDeep.js zipWith.js fromPairs.js function.js functions.js functionsIn.js get.js groupBy.js gt.js gte.js has.js hasIn.js head.js identity.js inRange.js includes.js index.js indexOf.js initial.js intersection.js intersectionBy.js intersectionWith.js invert.js invertBy.js invoke.js invokeMap.js isArguments.js isArray.js isArrayBuffer.js isArrayLike.js isArrayLikeObject.js isBoolean.js isBuffer.js isDate.js isElement.js isEmpty.js isEqual.js isEqualWith.js isError.js isFinite.js isFunction.js isInteger.js isLength.js isMap.js isMatch.js isMatchWith.js isNaN.js isNative.js isNil.js isNull.js isNumber.js isObject.js isObjectLike.js isPlainObject.js isRegExp.js isSafeInteger.js isSet.js isString.js isSymbol.js isTypedArray.js isUndefined.js isWeakMap.js isWeakSet.js iteratee.js join.js kebabCase.js keyBy.js keys.js keysIn.js lang.js last.js lastIndexOf.js lodash.js lodash.min.js lowerCase.js lowerFirst.js lt.js lte.js map.js mapKeys.js mapValues.js matches.js matchesProperty.js math.js max.js maxBy.js mean.js meanBy.js memoize.js merge.js mergeWith.js method.js methodOf.js min.js minBy.js mixin.js multiply.js negate.js next.js noop.js now.js nth.js nthArg.js number.js object.js omit.js omitBy.js once.js orderBy.js over.js overArgs.js overEvery.js overSome.js package.json pad.js padEnd.js padStart.js parseInt.js partial.js partialRight.js partition.js pick.js pickBy.js plant.js property.js propertyOf.js pull.js pullAll.js pullAllBy.js pullAllWith.js pullAt.js random.js range.js rangeRight.js rearg.js reduce.js reduceRight.js reject.js remove.js repeat.js replace.js rest.js result.js reverse.js round.js sample.js sampleSize.js seq.js set.js setWith.js shuffle.js size.js slice.js snakeCase.js some.js sortBy.js sortedIndex.js sortedIndexBy.js sortedIndexOf.js sortedLastIndex.js sortedLastIndexBy.js sortedLastIndexOf.js sortedUniq.js sortedUniqBy.js split.js spread.js startCase.js startsWith.js string.js stubArray.js stubFalse.js stubObject.js stubString.js stubTrue.js subtract.js sum.js sumBy.js tail.js take.js takeRight.js takeRightWhile.js takeWhile.js tap.js template.js templateSettings.js throttle.js thru.js times.js toArray.js toFinite.js toInteger.js toIterator.js toJSON.js toLength.js toLower.js toNumber.js toPairs.js toPairsIn.js toPath.js toPlainObject.js toSafeInteger.js toString.js toUpper.js transform.js trim.js trimEnd.js trimStart.js truncate.js unary.js unescape.js union.js unionBy.js unionWith.js uniq.js uniqBy.js uniqWith.js uniqueId.js unset.js unzip.js unzipWith.js update.js updateWith.js upperCase.js upperFirst.js util.js value.js valueOf.js values.js valuesIn.js without.js words.js wrap.js wrapperAt.js wrapperChain.js wrapperLodash.js wrapperReverse.js wrapperValue.js xor.js xorBy.js xorWith.js zip.js zipObject.js zipObjectDeep.js zipWith.js loglevel .travis.yml CONTRIBUTING.md Gruntfile.js README.md _config.yml bower.json dist loglevel.js loglevel.min.js lib loglevel.js package.json test console-fallback-test.js cookie-test.js default-level-test.js get-current-level-test.js global-integration-with-new-context.js global-integration.js integration-smoke-test.js level-setting-test.js local-storage-test.js manual-test.html method-factory-test.js multiple-logger-test.js node-integration.js test-context-using-apply.js test-helpers.js test-qunit.html test-qunit.js vendor json2.js loose-envify README.md cli.js custom.js index.js loose-envify.js package.json replace.js loud-rejection api.js index.js package.json readme.md register.js lru-cache README.md index.js package.json make-dir index.d.ts index.js package.json readme.md mamacro index.js package.json map-age-cleaner dist index.d.ts index.js package.json readme.md map-cache README.md index.js package.json map-obj index.js package.json readme.md map-visit README.md index.js package.json md5.js README.md index.js package.json media-typer HISTORY.md README.md index.js package.json mem index.d.ts index.js package.json readme.md memory-fs README.md lib MemoryFileSystem.js join.js normalize.js package.json meow index.js package.json readme.md merge-descriptors HISTORY.md README.md index.js package.json methods HISTORY.md README.md index.js package.json micromatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json miller-rabin 1.js README.md lib mr.js package.json test.js test api-test.js mime-db HISTORY.md README.md db.json index.js package.json mime-types HISTORY.md README.md index.js package.json mime README.md build build.js test.js cli.js mime.js package.json types.json mimic-fn index.d.ts index.js package.json readme.md min-document .testem.json .travis.yml CONTRIBUTION.md README.md document.js dom-comment.js dom-element.js dom-fragment.js dom-text.js event.js event add-event-listener.js dispatch-event.js remove-event-listener.js index.js package.json serialize.js test cleanup.js index.js static index.html test-adapter.js test-document.js test-dom-comment.js test-dom-element.js minimalistic-assert index.js package.json readme.md minimalistic-crypto-utils .travis.yml README.md lib utils.js package.json test utils-test.js minimatch README.md minimatch.js package.json minimist .travis.yml example parse.js index.js package.json test all_bool.js bool.js dash.js default_bool.js dotted.js kv_short.js long.js num.js parse.js parse_modified.js short.js stop_early.js unknown.js whitespace.js mississippi changelog.md index.js package.json readme.md mixin-deep README.md index.js node_modules is-extendable README.md index.d.ts index.js package.json package.json mixin-object README.md index.js node_modules for-in README.md index.js package.json package.json mkdirp .travis.yml bin cmd.js usage.txt examples pow.js index.js node_modules minimist .travis.yml example parse.js index.js package.json test dash.js default_bool.js dotted.js long.js parse.js parse_modified.js short.js whitespace.js package.json test chmod.js clobber.js mkdirp.js opts_fs.js opts_fs_sync.js perm.js perm_sync.js race.js rel.js return.js return_sync.js root.js sync.js umask.js umask_sync.js move-concurrently README.md move.js package.json ms index.js license.md package.json readme.md multicast-dns-service-types .travis.yml README.md index.js package.json test.js multicast-dns .travis.yml README.md cli.js example.js index.js package.json test.js nan CHANGELOG.md LICENSE.md README.md doc asyncworker.md buffers.md callback.md converters.md errors.md json.md maybe_types.md methods.md new.md node_misc.md object_wrappers.md persistent.md scopes.md script.md string_bytes.md v8_internals.md v8_misc.md include_dirs.js nan.h nan_callbacks.h nan_callbacks_12_inl.h nan_callbacks_pre_12_inl.h nan_converters.h nan_converters_43_inl.h nan_converters_pre_43_inl.h nan_define_own_property_helper.h nan_implementation_12_inl.h nan_implementation_pre_12_inl.h nan_json.h nan_maybe_43_inl.h nan_maybe_pre_43_inl.h nan_new.h nan_object_wrap.h nan_persistent_12_inl.h nan_persistent_pre_12_inl.h nan_private.h nan_string_bytes.h nan_typedarray_contents.h nan_weak.h package.json tools 1to2.js README.md package.json nanomatch CHANGELOG.md README.md index.js lib cache.js compilers.js parsers.js utils.js package.json negotiator HISTORY.md README.md index.js lib charset.js encoding.js language.js mediaType.js package.json neo-async README.md all.js allLimit.js allSeries.js angelFall.js any.js anyLimit.js anySeries.js apply.js applyEach.js applyEachSeries.js async.js async.min.js asyncify.js auto.js autoInject.js cargo.js compose.js concat.js concatLimit.js concatSeries.js constant.js createLogger.js detect.js detectLimit.js detectSeries.js dir.js doDuring.js doUntil.js doWhilst.js during.js each.js eachLimit.js eachOf.js eachOfLimit.js eachOfSeries.js eachSeries.js ensureAsync.js every.js everyLimit.js everySeries.js fast.js filter.js filterLimit.js filterSeries.js find.js findLimit.js findSeries.js foldl.js foldr.js forEach.js forEachLimit.js forEachOf.js forEachOfLimit.js forEachOfSeries.js forEachSeries.js forever.js groupBy.js groupByLimit.js groupBySeries.js inject.js iterator.js log.js map.js mapLimit.js mapSeries.js mapValues.js mapValuesLimit.js mapValuesSeries.js memoize.js nextTick.js omit.js omitLimit.js omitSeries.js package.json parallel.js parallelLimit.js pick.js pickLimit.js pickSeries.js priorityQueue.js queue.js race.js reduce.js reduceRight.js reflect.js reflectAll.js reject.js rejectLimit.js rejectSeries.js retry.js retryable.js safe.js select.js selectLimit.js selectSeries.js seq.js series.js setImmediate.js some.js someLimit.js someSeries.js sortBy.js sortByLimit.js sortBySeries.js timeout.js times.js timesLimit.js timesSeries.js transform.js transformLimit.js transformSeries.js tryEach.js unmemoize.js until.js waterfall.js whilst.js wrapSync.js nice-try CHANGELOG.md README.md package.json src index.js node-forge CHANGELOG.md README.md dist forge.all.min.js forge.min.js prime.worker.min.js flash README.md lib aes.js aesCipherSuites.js asn1.js baseN.js cipher.js cipherModes.js debug.js des.js ed25519.js forge.js form.js hmac.js http.js index.all.js index.js jsbn.js kem.js log.js md.all.js md.js md5.js mgf.js mgf1.js oids.js pbe.js pbkdf2.js pem.js pkcs1.js pkcs12.js pkcs7.js pkcs7asn1.js pki.js prime.js prime.worker.js prng.js pss.js random.js rc2.js rsa.js sha1.js sha256.js sha512.js socket.js ssh.js task.js tls.js tlssocket.js util.js x509.js xhr.js package.json node-gyp .github ISSUE_TEMPLATE.md PULL_REQUEST_TEMPLATE.md CHANGELOG.md CONTRIBUTING.md README.md bin node-gyp.js gyp PRESUBMIT.py gyp.bat gyp_main.py pylib gyp MSVSNew.py MSVSProject.py MSVSSettings.py MSVSSettings_test.py MSVSToolFile.py MSVSUserFile.py MSVSUtil.py MSVSVersion.py __init__.py common.py common_test.py easy_xml.py easy_xml_test.py flock_tool.py generator __init__.py analyzer.py android.py cmake.py dump_dependency_json.py eclipse.py gypd.py gypsh.py make.py msvs.py msvs_test.py ninja.py ninja_test.py xcode.py xcode_test.py input.py input_test.py mac_tool.py msvs_emulation.py ninja_syntax.py ordered_dict.py simple_copy.py win_tool.py xcode_emulation.py xcode_ninja.py xcodeproj_file.py xml_fix.py samples samples.bat setup.py tools emacs run-unit-tests.sh graphviz.py pretty_gyp.py pretty_sln.py pretty_vcproj.py lib Find-VS2017.cs build.js clean.js configure.js find-node-directory.js find-vs2017.js install.js list.js node-gyp.js process-release.js rebuild.js remove.js node_modules semver README.md package.json semver.js package.json test docker.sh fixtures test-charmap.py process-exec-sync.js simple-proxy.js test-addon.js test-configure-python.js test-download.js test-find-accessible-sync.js test-find-node-directory.js test-find-python.js test-install.js test-options.js test-process-release.js tools gyp pylib gyp generator compile_commands_json.py node-libs-browser README.md index.js mock buffer.js console.js dns.js empty.js net.js process.js punycode.js tls.js tty.js node_modules punycode LICENSE-MIT.txt README.md package.json punycode.js package.json node-releases .idea encodings.xml inspectionProfiles Project_Default.xml misc.xml modules.xml vcs.xml workspace.xml README.md data processed envs.json raw iojs.json nodejs.json release-schedule release-schedule.json package.json node-sass CHANGELOG.md README.md lib binding.js errors.js extensions.js index.js render.js watcher.js node_modules ansi-regex index.js package.json readme.md ansi-styles index.js package.json readme.md chalk index.js package.json readme.md cross-spawn .travis.yml README.md appveyor.yml index.js lib enoent.js parse.js resolveCommand.js package.json strip-ansi index.js package.json readme.md supports-color index.js package.json readme.md package.json scripts build.js coverage.js install.js prepublish.js util downloadoptions.js proxy.js useragent.js src binding.cpp callback_bridge.h create_string.cpp create_string.h custom_function_bridge.cpp custom_function_bridge.h custom_importer_bridge.cpp custom_importer_bridge.h libsass .github CONTRIBUTING.md ISSUE_TEMPLATE.md .travis.yml Readme.md SECURITY.md appveyor.yml contrib plugin.cpp docs README.md api-context-example.md api-context-internal.md api-context.md api-doc.md api-function-example.md api-function-internal.md api-function.md api-importer-example.md api-importer-internal.md api-importer.md api-value-example.md api-value-internal.md api-value.md build-on-darwin.md build-on-gentoo.md build-on-windows.md build-shared-library.md build-with-autotools.md build-with-makefiles.md build-with-mingw.md build-with-visual-studio.md build.md compatibility-plan.md contributing.md custom-functions-internal.md dev-ast-memory.md implementations.md plugins.md setup-environment.md source-map-internals.md trace.md triage.md unicode.md extconf.rb include sass.h sass base.h context.h functions.h values.h version.h sass2scss.h script test-leaks.pl src ast.cpp ast_fwd_decl.cpp b64 cencode.h encode.h backtrace.cpp base64vlq.cpp bind.cpp c99func.c cencode.c check_nesting.cpp color_maps.cpp constants.cpp context.cpp cssize.cpp emitter.cpp environment.cpp error_handling.cpp eval.cpp expand.cpp extend.cpp file.cpp functions.cpp inspect.cpp json.cpp lexer.cpp listize.cpp memory SharedPtr.cpp node.cpp operators.cpp output.cpp parser.cpp plugins.cpp position.cpp prelexer.cpp remove_placeholders.cpp sass.cpp sass2scss.cpp sass_context.cpp sass_functions.cpp sass_util.cpp sass_values.cpp source_map.cpp subset_map.cpp to_c.cpp to_value.cpp units.cpp utf8.h utf8 checked.h core.h unchecked.h utf8_string.cpp util.cpp values.cpp test test_node.cpp test_paths.cpp test_selector_difference.cpp test_specificity.cpp test_subset_map.cpp test_superselector.cpp test_unification.cpp version.sh win libsass.sln sass_context_wrapper.cpp sass_context_wrapper.h sass_types boolean.cpp boolean.h color.cpp color.h error.cpp error.h factory.cpp factory.h list.cpp list.h map.cpp map.h null.cpp null.h number.cpp number.h sass_value_wrapper.h string.cpp string.h value.h test api.js binding.js cli.js downloadoptions.js errors.js fixtures compressed expected.css custom-functions setter-expected.css string-conversion-expected.css cwd-include-path expected.css depth-first expected.css extras my_custom_arrays_of_importers.js my_custom_functions_setter.js my_custom_functions_string_conversion.js my_custom_importer_data.js my_custom_importer_data_cb.js my_custom_importer_error.js my_custom_importer_file.js my_custom_importer_file_and_data.js my_custom_importer_file_and_data_cb.js my_custom_importer_file_cb.js include-files expected-importer.css include-path expected.css indent expected.css precision expected.css sass-path expected-orange.css expected-red.css simple expected.css source-comments expected.css source-map-embed expected.css source-map expected.css lowlevel.js runtime.js scripts util proxy.js spec.js types.js useragent.js watcher.js nopt .travis.yml README.md bin nopt.js examples my-program.js lib nopt.js package.json test basic.js normalize-package-data README.md lib extract_description.js fixer.js make_warning.js normalize.js safe_format.js typos.json warning_messages.json package.json normalize-path README.md index.js package.json npm-run-path index.js package.json readme.md npmlog CHANGELOG.md README.md log.js package.json number-is-nan index.js package.json readme.md oauth-sign README.md index.js package.json object-assign index.js package.json readme.md object-copy index.js node_modules define-property README.md index.js package.json kind-of README.md index.js package.json package.json object-keys .travis.yml CHANGELOG.md README.md implementation.js index.js isArguments.js package.json test index.js object-visit README.md index.js package.json object.getownpropertydescriptors .jscs.json .travis.yml CHANGELOG.md README.md implementation.js index.js package.json polyfill.js shim.js test index.js shimmed.js tests.js object.pick README.md index.js package.json obuf README.md index.js package.json test buffer-test.js on-finished HISTORY.md README.md index.js package.json on-headers HISTORY.md README.md index.js package.json once README.md once.js package.json opn index.js package.json readme.md original README.md index.js package.json os-browserify README.md browser.js main.js package.json os-homedir index.js package.json readme.md os-locale index.js package.json readme.md os-tmpdir index.js package.json readme.md osenv README.md osenv.js package.json p-defer index.js package.json readme.md p-finally index.js package.json readme.md p-is-promise index.d.ts index.js package.json readme.md p-limit index.d.ts index.js package.json readme.md p-locate index.js package.json readme.md p-map index.d.ts index.js package.json readme.md p-try index.d.ts index.js package.json readme.md pako CHANGELOG.md README.md dist pako.js pako.min.js pako_deflate.js pako_deflate.min.js pako_inflate.js pako_inflate.min.js index.js lib deflate.js inflate.js utils common.js strings.js zlib adler32.js constants.js crc32.js deflate.js gzheader.js inffast.js inflate.js inftrees.js messages.js trees.js zstream.js package.json parallel-transform README.md index.js package.json parse-asn1 .travis.yml README.md aesid.json asn1.js certificate.js fixProc.js index.js package.json test index.js vector.js parse-json index.js package.json readme.md vendor parse.js unicode.js parse-passwd README.md index.js package.json parseurl HISTORY.md README.md index.js package.json pascalcase README.md index.js package.json path-browserify index.js package.json path-dirname index.js package.json readme.md path-exists index.js package.json readme.md path-is-absolute index.js package.json readme.md path-is-inside LICENSE.txt lib path-is-inside.js package.json path-key index.js package.json readme.md path-parse .travis.yml README.md index.js package.json test.js path-to-regexp History.md Readme.md index.js package.json path-type index.js node_modules pify index.js package.json readme.md package.json readme.md pbkdf2 README.md browser.js index.js lib async.js default-encoding.js precondition.js sync-browser.js sync.js package.json performance-now .travis.yml README.md lib performance-now.js license.txt package.json src index.d.ts performance-now.coffee test performance-now.coffee scripts.coffee scripts delayed-call.coffee delayed-require.coffee difference.coffee initial-value.coffee pify index.js package.json readme.md pinkie-promise index.js package.json readme.md pinkie index.js package.json readme.md pkg-dir index.js package.json readme.md portfinder README.md lib portfinder.d.ts portfinder.js package.json posix-character-classes README.md index.js package.json postcss-modules-extract-imports README.md package.json src index.js topologicalSort.js postcss-modules-local-by-default CHANGELOG.md README.md index.js package.json postcss-modules-scope CHANGELOG.md README.md package.json src index.js postcss-modules-values README.md package.json src index.js postcss-selector-parser API.md CHANGELOG.md README.md dist __tests__ attributes.js classes.js combinators.js comments.js container.js escapes.js exceptions.js guards.js id.js lossy.js namespaces.js nesting.js node.js nonstandard.js parser.js postcss.js pseudos.js sourceIndex.js stripComments.js tags.js universal.js util helpers.js index.js parser.js processor.js selectors attribute.js className.js combinator.js comment.js constructors.js container.js guards.js id.js index.js namespace.js nesting.js node.js pseudo.js root.js selector.js string.js tag.js types.js universal.js sortAscending.js tokenTypes.js tokenize.js util ensureObject.js getProp.js index.js stripComments.js unesc.js package.json postcss-selector-parser.d.ts postcss-value-parser README.md lib index.js parse.js stringify.js unit.js walk.js package.json postcss CHANGELOG.md README.md docs architecture.md guidelines plugin.md runner.md source-maps.md syntax.md lib at-rule.js comment.js container.js css-syntax-error.js declaration.js input.js lazy-result.js list.js map-generator.js node.js parse.js parser.js postcss.d.ts postcss.js previous-map.js processor.js result.js root.js rule.js stringifier.js stringify.js terminal-highlight.js tokenize.js vendor.js warn-once.js warning.js node_modules source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.d.ts source-map.js supports-color browser.js index.js package.json readme.md package.json private README.md package.json private.js process-nextick-args index.js license.md package.json readme.md process README.md browser.js index.js package.json test.js promise-inflight README.md inflight.js package.json prop-types CHANGELOG.md README.md checkPropTypes.js factory.js factoryWithThrowingShims.js factoryWithTypeCheckers.js index.js lib ReactPropTypesSecret.js package.json prop-types.js prop-types.min.js proxy-addr HISTORY.md README.md index.js package.json prr .travis.yml LICENSE.md README.md package.json prr.js test.js pseudomap README.md map.js package.json pseudomap.js test basic.js psl .travis.yml README.md data rules.json dist psl.js psl.min.js index.js karma.conf.js package.json public-encrypt .travis.yml browser.js index.js mgf.js package.json privateDecrypt.js publicEncrypt.js readme.md test index.js nodeTests.js withPublic.js xor.js pump .travis.yml README.md index.js package.json test-browser.js test-node.js pumpify .travis.yml README.md index.js node_modules pump .travis.yml README.md index.js package.json test-browser.js test-node.js package.json test.js punycode LICENSE-MIT.txt README.md package.json punycode.es6.js punycode.js qs CHANGELOG.md README.md dist qs.js lib formats.js index.js parse.js stringify.js utils.js package.json test index.js parse.js stringify.js utils.js querystring-es3 .travis.yml History.md License.md Readme.md decode.js encode.js index.js package.json test common-index.js index.js tap-index.js querystring .travis.yml History.md License.md Readme.md decode.js encode.js index.js package.json test common-index.js index.js tap-index.js querystringify README.md index.js package.json randombytes .travis.yml .zuul.yml README.md browser.js index.js package.json test.js randomfill .travis.yml .zuul.yml README.md browser.js index.js package.json test.js range-parser HISTORY.md README.md index.js package.json raw-body HISTORY.md README.md index.d.ts index.js package.json react-dom README.md build-info.json cjs react-dom-server.browser.development.js react-dom-server.browser.production.min.js react-dom-server.node.development.js react-dom-server.node.production.min.js react-dom-test-utils.development.js react-dom-test-utils.production.min.js react-dom-unstable-fire.development.js react-dom-unstable-fire.production.min.js react-dom-unstable-fire.profiling.min.js react-dom-unstable-fizz.browser.development.js react-dom-unstable-fizz.browser.production.min.js react-dom-unstable-fizz.node.development.js react-dom-unstable-fizz.node.production.min.js react-dom-unstable-native-dependencies.development.js react-dom-unstable-native-dependencies.production.min.js react-dom.development.js react-dom.production.min.js react-dom.profiling.min.js index.js package.json profiling.js server.browser.js server.js server.node.js test-utils.js umd react-dom-server.browser.development.js react-dom-server.browser.production.min.js react-dom-test-utils.development.js react-dom-test-utils.production.min.js react-dom-unstable-fire.development.js react-dom-unstable-fire.production.min.js react-dom-unstable-fire.profiling.min.js react-dom-unstable-fizz.browser.development.js react-dom-unstable-fizz.browser.production.min.js react-dom-unstable-native-dependencies.development.js react-dom-unstable-native-dependencies.production.min.js react-dom.development.js react-dom.production.min.js react-dom.profiling.min.js unstable-fizz.browser.js unstable-fizz.js unstable-fizz.node.js unstable-native-dependencies.js react-hot-loader CHANGELOG.md README.md babel.js dist babel.development.js babel.production.min.js react-hot-loader.development.js react-hot-loader.production.min.js webpack.development.js webpack.production.min.js webpackTagCommonJSExports.js index.d.ts index.js node_modules source-map CHANGELOG.md README.md dist source-map.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js read-wasm.js source-map-consumer.js source-map-generator.js source-node.js util.js wasm.js package.json source-map.d.ts source-map.js package.json patch.js root.d.ts root.js webpack.js react-is README.md build-info.json cjs react-is.development.js react-is.production.min.js index.js package.json umd react-is.development.js react-is.production.min.js react-lifecycles-compat CHANGELOG.md LICENSE.md README.md package.json react-lifecycles-compat.cjs.js react-lifecycles-compat.es.js react-lifecycles-compat.js react-lifecycles-compat.min.js react README.md build-info.json cjs react.development.js react.production.min.js index.js package.json umd react.development.js react.production.min.js react.profiling.min.js read-pkg-up index.js node_modules find-up index.js package.json readme.md path-exists index.js package.json readme.md package.json readme.md read-pkg index.js package.json readme.md readable-stream .travis.yml CONTRIBUTING.md GOVERNANCE.md README.md doc wg-meetings 2015-01-30.md duplex-browser.js duplex.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams BufferList.js destroy.js stream-browser.js stream.js package.json passthrough.js readable-browser.js readable.js transform.js writable-browser.js writable.js readdirp README.md package.json readdirp.js stream-api.js redent index.js package.json readme.md regenerate-unicode-properties Binary_Property ASCII.js ASCII_Hex_Digit.js Alphabetic.js Any.js Assigned.js Bidi_Control.js Bidi_Mirrored.js Case_Ignorable.js Cased.js Changes_When_Casefolded.js Changes_When_Casemapped.js Changes_When_Lowercased.js Changes_When_NFKC_Casefolded.js Changes_When_Titlecased.js Changes_When_Uppercased.js Dash.js Default_Ignorable_Code_Point.js Deprecated.js Diacritic.js Emoji.js Emoji_Component.js Emoji_Modifier.js Emoji_Modifier_Base.js Emoji_Presentation.js Extended_Pictographic.js Extender.js Grapheme_Base.js Grapheme_Extend.js Hex_Digit.js IDS_Binary_Operator.js IDS_Trinary_Operator.js ID_Continue.js ID_Start.js Ideographic.js Join_Control.js Logical_Order_Exception.js Lowercase.js Math.js Noncharacter_Code_Point.js Pattern_Syntax.js Pattern_White_Space.js Quotation_Mark.js Radical.js Regional_Indicator.js Sentence_Terminal.js Soft_Dotted.js Terminal_Punctuation.js Unified_Ideograph.js Uppercase.js Variation_Selector.js White_Space.js XID_Continue.js XID_Start.js General_Category Cased_Letter.js Close_Punctuation.js Connector_Punctuation.js Control.js Currency_Symbol.js Dash_Punctuation.js Decimal_Number.js Enclosing_Mark.js Final_Punctuation.js Format.js Initial_Punctuation.js Letter.js Letter_Number.js Line_Separator.js Lowercase_Letter.js Mark.js Math_Symbol.js Modifier_Letter.js Modifier_Symbol.js Nonspacing_Mark.js Number.js Open_Punctuation.js Other.js Other_Letter.js Other_Number.js Other_Punctuation.js Other_Symbol.js Paragraph_Separator.js Private_Use.js Punctuation.js Separator.js Space_Separator.js Spacing_Mark.js Surrogate.js Symbol.js Titlecase_Letter.js Unassigned.js Uppercase_Letter.js LICENSE-MIT.txt README.md Script Adlam.js Ahom.js Anatolian_Hieroglyphs.js Arabic.js Armenian.js Avestan.js Balinese.js Bamum.js Bassa_Vah.js Batak.js Bengali.js Bhaiksuki.js Bopomofo.js Brahmi.js Braille.js Buginese.js Buhid.js Canadian_Aboriginal.js Carian.js Caucasian_Albanian.js Chakma.js Cham.js Cherokee.js Common.js Coptic.js Cuneiform.js Cypriot.js Cyrillic.js Deseret.js Devanagari.js Dogra.js Duployan.js Egyptian_Hieroglyphs.js Elbasan.js Elymaic.js Ethiopic.js Georgian.js Glagolitic.js Gothic.js Grantha.js Greek.js Gujarati.js Gunjala_Gondi.js Gurmukhi.js Han.js Hangul.js Hanifi_Rohingya.js Hanunoo.js Hatran.js Hebrew.js Hiragana.js Imperial_Aramaic.js Inherited.js Inscriptional_Pahlavi.js Inscriptional_Parthian.js Javanese.js Kaithi.js Kannada.js Katakana.js Kayah_Li.js Kharoshthi.js Khmer.js Khojki.js Khudawadi.js Lao.js Latin.js Lepcha.js Limbu.js Linear_A.js Linear_B.js Lisu.js Lycian.js Lydian.js Mahajani.js Makasar.js Malayalam.js Mandaic.js Manichaean.js Marchen.js Masaram_Gondi.js Medefaidrin.js Meetei_Mayek.js Mende_Kikakui.js Meroitic_Cursive.js Meroitic_Hieroglyphs.js Miao.js Modi.js Mongolian.js Mro.js Multani.js Myanmar.js Nabataean.js Nandinagari.js New_Tai_Lue.js Newa.js Nko.js Nushu.js Nyiakeng_Puachue_Hmong.js Ogham.js Ol_Chiki.js Old_Hungarian.js Old_Italic.js Old_North_Arabian.js Old_Permic.js Old_Persian.js Old_Sogdian.js Old_South_Arabian.js Old_Turkic.js Oriya.js Osage.js Osmanya.js Pahawh_Hmong.js Palmyrene.js Pau_Cin_Hau.js Phags_Pa.js Phoenician.js Psalter_Pahlavi.js Rejang.js Runic.js Samaritan.js Saurashtra.js Sharada.js Shavian.js Siddham.js SignWriting.js Sinhala.js Sogdian.js Sora_Sompeng.js Soyombo.js Sundanese.js Syloti_Nagri.js Syriac.js Tagalog.js Tagbanwa.js Tai_Le.js Tai_Tham.js Tai_Viet.js Takri.js Tamil.js Tangut.js Telugu.js Thaana.js Thai.js Tibetan.js Tifinagh.js Tirhuta.js Ugaritic.js Vai.js Wancho.js Warang_Citi.js Yi.js Zanabazar_Square.js Script_Extensions Adlam.js Ahom.js Anatolian_Hieroglyphs.js Arabic.js Armenian.js Avestan.js Balinese.js Bamum.js Bassa_Vah.js Batak.js Bengali.js Bhaiksuki.js Bopomofo.js Brahmi.js Braille.js Buginese.js Buhid.js Canadian_Aboriginal.js Carian.js Caucasian_Albanian.js Chakma.js Cham.js Cherokee.js Common.js Coptic.js Cuneiform.js Cypriot.js Cyrillic.js Deseret.js Devanagari.js Dogra.js Duployan.js Egyptian_Hieroglyphs.js Elbasan.js Elymaic.js Ethiopic.js Georgian.js Glagolitic.js Gothic.js Grantha.js Greek.js Gujarati.js Gunjala_Gondi.js Gurmukhi.js Han.js Hangul.js Hanifi_Rohingya.js Hanunoo.js Hatran.js Hebrew.js Hiragana.js Imperial_Aramaic.js Inherited.js Inscriptional_Pahlavi.js Inscriptional_Parthian.js Javanese.js Kaithi.js Kannada.js Katakana.js Kayah_Li.js Kharoshthi.js Khmer.js Khojki.js Khudawadi.js Lao.js Latin.js Lepcha.js Limbu.js Linear_A.js Linear_B.js Lisu.js Lycian.js Lydian.js Mahajani.js Makasar.js Malayalam.js Mandaic.js Manichaean.js Marchen.js Masaram_Gondi.js Medefaidrin.js Meetei_Mayek.js Mende_Kikakui.js Meroitic_Cursive.js Meroitic_Hieroglyphs.js Miao.js Modi.js Mongolian.js Mro.js Multani.js Myanmar.js Nabataean.js Nandinagari.js New_Tai_Lue.js Newa.js Nko.js Nushu.js Nyiakeng_Puachue_Hmong.js Ogham.js Ol_Chiki.js Old_Hungarian.js Old_Italic.js Old_North_Arabian.js Old_Permic.js Old_Persian.js Old_Sogdian.js Old_South_Arabian.js Old_Turkic.js Oriya.js Osage.js Osmanya.js Pahawh_Hmong.js Palmyrene.js Pau_Cin_Hau.js Phags_Pa.js Phoenician.js Psalter_Pahlavi.js Rejang.js Runic.js Samaritan.js Saurashtra.js Sharada.js Shavian.js Siddham.js SignWriting.js Sinhala.js Sogdian.js Sora_Sompeng.js Soyombo.js Sundanese.js Syloti_Nagri.js Syriac.js Tagalog.js Tagbanwa.js Tai_Le.js Tai_Tham.js Tai_Viet.js Takri.js Tamil.js Tangut.js Telugu.js Thaana.js Thai.js Tibetan.js Tifinagh.js Tirhuta.js Ugaritic.js Vai.js Wancho.js Warang_Citi.js Yi.js Zanabazar_Square.js index.js package.json unicode-version.js regenerate LICENSE-MIT.txt README.md package.json regenerate.js regenerator-transform README.md lib emit.js hoist.js index.js leap.js meta.js replaceShorthandObjectMethod.js util.js visit.js package.json src emit.js hoist.js index.js leap.js meta.js replaceShorthandObjectMethod.js util.js visit.js regex-not README.md index.js package.json regexp-tree README.md dist bin regexp-tree.js compat-transpiler index.js runtime index.js transforms compat-dotall-s-transform.js compat-named-capturing-groups-transform.js compat-x-flag-transform.js index.js generator index.js interpreter finite-automaton dfa dfa-minimizer.js dfa.js index.js nfa builders.js nfa-from-regexp.js nfa-state.js nfa.js special-symbols.js state.js table-printer.js transforms char-plus-to-star-transform.js index.js optimizer index.js transforms char-case-insensitive-lowercase-transform.js char-class-classranges-merge-transform.js char-class-classranges-to-chars-transform.js char-class-remove-duplicates-transform.js char-class-to-meta-transform.js char-class-to-single-char-transform.js char-code-to-simple-char-transform.js char-escape-unescape-transform.js char-surrogate-pair-to-single-unicode-transform.js combine-repeating-patterns-transform.js disjunction-remove-duplicates-transform.js group-single-chars-to-char-class.js index.js quantifier-range-to-symbol-transform.js quantifiers-merge-transform.js remove-empty-group-transform.js ungroup-transform.js parser generated regexp-tree.js index.js regexp-tree.js transform index.js utils.js traverse index.js node-path.js utils clone.js index.d.ts index.js package.json regexpu-core LICENSE-MIT.txt README.md data character-class-escape-sets.js iu-mappings.js package.json rewrite-pattern.js regjsgen README.md package.json regjsgen.js regjsparser README.md node_modules jsesc LICENSE-MIT.txt README.md jsesc.js package.json package.json parser.js remove-trailing-separator history.md index.js package.json readme.md repeat-element README.md index.js package.json repeat-string README.md index.js package.json repeating index.js package.json readme.md request CHANGELOG.md README.md index.js lib auth.js cookies.js getProxyFromURI.js har.js hawk.js helpers.js multipart.js oauth.js querystring.js redirect.js tunnel.js package.json request.js require-directory .travis.yml index.js package.json require-main-filename .travis.yml LICENSE.txt README.md index.js package.json test.js requires-port .travis.yml README.md index.js package.json test.js resolve-cwd index.js package.json readme.md resolve-dir README.md index.js package.json resolve-from index.js package.json readme.md resolve-url bower.json changelog.md component.json package.json readme.md resolve-url.js test resolve-url.js resolve .travis.yml CHANGELOG.md appveyor.yml example async.js sync.js index.js lib async.js caller.js core.js core.json node-modules-paths.js normalize-options.js sync.js package.json test core.js dotdot.js dotdot abc index.js index.js faulty_basedir.js filter.js filter_sync.js mock.js mock_sync.js module_dir.js module_dir xmodules aaa index.js ymodules aaa index.js zmodules bbb main.js package.json node-modules-paths.js node_path.js node_path x aaa index.js ccc index.js y bbb index.js ccc index.js nonstring.js pathfilter.js pathfilter deep_ref main.js precedence.js precedence aaa.js aaa index.js main.js bbb.js bbb main.js resolver.js resolver baz doom.js package.json quux.js browser_field a.js b.js package.json cup.coffee dot_main index.js package.json dot_slash_main index.js package.json foo.js incorrect_main index.js package.json invalid_main package.json mug.coffee mug.js multirepo lerna.json package.json packages package-a index.js package.json package-b index.js package.json other_path lib other-lib.js root.js quux foo index.js same_names foo.js foo index.js symlinked _ node_modules foo.js without_basedir main.js resolver_sync.js subdirs.js symlinks.js ret README.md lib index.js positions.js sets.js types.js util.js package.json rimraf README.md bin.js package.json rimraf.js ripemd160 CHANGELOG.md README.md index.js package.json run-queue README.md package.json queue.js safe-buffer README.md index.d.ts index.js package.json safe-regex .travis.yml example safe.js index.js package.json test regex.js safer-buffer Porting-Buffer.md Readme.md dangerous.js package.json safer.js tests.js sass-graph CHANGELOG.md node_modules ansi-regex index.js package.json readme.md camelcase index.js package.json readme.md cliui CHANGELOG.md LICENSE.txt README.md index.js package.json invert-kv index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md lcid index.js lcid.json package.json readme.md os-locale index.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.js package.json readme.md which-module CHANGELOG.md README.md index.js package.json y18n README.md index.js package.json yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md index.js lib apply-extends.js argsert.js assign.js command.js completion.js levenshtein.js obj-filter.js usage.js validation.js yerror.js locales be.json de.json en.json es.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js package.json parse-imports.js readme.md sass-graph.js sass-loader CHANGELOG.md README.md lib formatSassError.js importsToResolve.js loader.js normalizeOptions.js proxyCustomImporters.js webpackImporter.js node_modules pify index.js package.json readme.md package.json scheduler README.md build-info.json cjs scheduler-tracing.development.js scheduler-tracing.production.min.js scheduler-tracing.profiling.min.js scheduler.development.js scheduler.production.min.js index.js package.json tracing-profiling.js tracing.js umd scheduler-tracing.development.js scheduler-tracing.production.min.js scheduler-tracing.profiling.min.js scheduler.development.js scheduler.production.min.js scheduler.profiling.min.js schema-utils CHANGELOG.md README.md package.json src ValidationError.js index.js validateOptions.js scss-tokenizer README.md index.js lib entry.js input.js previous-map.js tokenize-comment.js tokenize-interpolant.js tokenize-string.js tokenize.js node_modules source-map README.md build assert-shim.js mini-require.js suffix-browser.js test-prefix.js test-suffix.js lib source-map.js source-map array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json package.json select-hose .travis.yml README.md lib hose.js package.json test api-test.js fixtures.js selfsigned .travis.yml README.md index.js package.json test tests.js semver CHANGELOG.md README.md package.json semver.js send HISTORY.md README.md index.js package.json serialize-javascript README.md index.js package.json serve-index HISTORY.md README.md index.js package.json public directory.html style.css serve-static HISTORY.md README.md index.js package.json set-blocking CHANGELOG.md LICENSE.txt README.md index.js package.json set-value README.md index.js node_modules extend-shallow README.md index.js package.json package.json setimmediate LICENSE.txt package.json setImmediate.js setprototypeof README.md index.d.ts index.js package.json sha.js .travis.yml README.md bin.js hash.js index.js package.json sha.js sha1.js sha224.js sha256.js sha384.js sha512.js test hash.js test.js vectors.js shallow-clone README.md index.js node_modules kind-of README.md index.js package.json package.json shallowequal README.md index.js index.original.js package.json shebang-command index.js package.json readme.md shebang-regex index.js package.json readme.md signal-exit CHANGELOG.md LICENSE.txt README.md index.js package.json signals.js snapdragon-node README.md index.js node_modules define-property README.md index.js package.json is-accessor-descriptor README.md index.js package.json is-data-descriptor README.md index.js package.json is-descriptor README.md index.js package.json package.json snapdragon-util README.md index.js node_modules kind-of README.md index.js package.json package.json snapdragon README.md index.js lib compiler.js parser.js position.js source-maps.js utils.js node_modules define-property README.md index.js package.json extend-shallow README.md index.js package.json package.json sockjs-client Changelog.md README.md dist sockjs.js sockjs.min.js lib entry.js event close.js emitter.js event.js eventtarget.js trans-message.js facade.js iframe-bootstrap.js info-ajax.js info-iframe-receiver.js info-iframe.js info-receiver.js location.js main.js shims.js transport-list.js transport browser abstract-xhr.js eventsource.js websocket.js driver websocket.js xhr.js eventsource.js htmlfile.js iframe.js jsonp-polling.js lib ajax-based.js buffered-sender.js iframe-wrap.js polling.js sender-receiver.js receiver eventsource.js htmlfile.js jsonp.js xhr.js sender jsonp.js xdr.js xhr-cors.js xhr-fake.js xhr-local.js websocket.js xdr-polling.js xdr-streaming.js xhr-polling.js xhr-streaming.js utils browser-crypto.js browser.js escape.js event.js iframe.js log.js object.js random.js transport.js url.js version.js node_modules debug CHANGELOG.md README.md dist debug.js node.js package.json src browser.js common.js index.js node.js faye-websocket CHANGELOG.md CODE_OF_CONDUCT.md README.md examples autobahn_client.js client.js proxy_server.js server.js sse.html ws.html lib faye eventsource.js websocket.js websocket api.js api event.js event_target.js client.js package.json ms index.js license.md package.json readme.md package.json sockjs README.md examples echo README.md index.html package.json server.js express-3.x index.html package.json server.js express index.html package.json server.js hapi html index.html package.json server.js koa index.html package.json server.js multiplex README.md index.html package.json server.js index.js lib chunking-test.js iframe.js sockjs.js trans-eventsource.js trans-htmlfile.js trans-jsonp.js trans-websocket.js trans-xhr.js transport.js utils.js webjs.js package.json source-list-map README.md lib CodeNode.js MappingsContext.js SingleLineNode.js SourceListMap.js SourceNode.js base64-vlq.js fromStringWithSourceMap.js helpers.js index.js package.json source-map-resolve .travis.yml bower.json changelog.md component.json generate-source-map-resolve.js lib decode-uri-component.js resolve-url.js source-map-resolve-node.js package.json readme.md source-map-resolve.js test common.js read.js source-map-resolve.js windows.js source-map-support LICENSE.md README.md browser-source-map-support.js node_modules source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.d.ts source-map.js package.json register.js source-map-support.js source-map-url bower.json changelog.md component.json package.json readme.md source-map-url.js test source-map-url.js source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.js spdx-correct README.md index.js package.json spdx-exceptions README.md index.json package.json spdx-expression-parse README.md index.js package.json parse.js scan.js spdx-license-ids README.md deprecated.json index.json package.json spdy-transport .travis.yml README.md lib spdy-transport.js spdy-transport connection.js priority.js protocol base constants.js framer.js index.js parser.js scheduler.js utils.js http2 constants.js framer.js hpack-pool.js index.js parser.js spdy constants.js dictionary.js framer.js index.js parser.js zlib-pool.js stream.js utils.js window.js node_modules debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md readable-stream CONTRIBUTING.md GOVERNANCE.md README.md errors-browser.js errors.js experimentalWarning.js lib _stream_duplex.js _stream_passthrough.js _stream_readable.js _stream_transform.js _stream_writable.js internal streams async_iterator.js buffer_list.js destroy.js end-of-stream.js pipeline.js state.js stream-browser.js stream.js package.json readable-browser.js readable.js package.json spdy .travis.yml README.md lib spdy.js spdy agent.js handle.js request.js response.js server.js socket.js node_modules debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md package.json test client-test.js fixtures.js server-test.js split-string README.md index.js package.json sshpk .travis.yml README.md lib algs.js certificate.js dhe.js ed-compat.js errors.js fingerprint.js formats auto.js dnssec.js openssh-cert.js pem.js pkcs1.js pkcs8.js putty.js rfc4253.js ssh-private.js ssh.js x509-pem.js x509.js identity.js index.js key.js private-key.js signature.js ssh-buffer.js utils.js package.json ssri CHANGELOG.md LICENSE.md README.md index.js package.json static-extend index.js node_modules define-property README.md index.js package.json package.json statuses HISTORY.md README.md codes.json index.js package.json stdout-stream .travis.yml README.md index.js package.json test fixtures end.js hello-world.js index.js stream-browserify .travis.yml index.js package.json test buf.js stream-each .travis.yml README.md collaborators.md index.js package.json test.js stream-http .airtap.yml .travis.yml README.md ie8-polyfill.js index.js lib capability.js request.js response.js package.json test browser abort.js auth.js binary-streaming.js binary.js body-empty.js cookie.js disable-fetch.js headers.js lib webworker-worker.js package.json post-binary.js post-text.js text-streaming.js text.js timeout.js webworker.js node http-browserify.js server index.js static basic.txt test-polyfill.js stream-shift .travis.yml README.md index.js package.json test.js string-width index.js package.json readme.md string_decoder .travis.yml README.md lib string_decoder.js package.json strip-ansi index.js package.json readme.md strip-bom index.js package.json readme.md strip-eof index.js package.json readme.md strip-indent cli.js index.js package.json readme.md style-loader CHANGELOG.md README.md index.js lib addStyleUrl.js addStyles.js urls.js options.json package.json url.js useable.js supports-color browser.js index.js package.json readme.md tapable README.md lib AsyncParallelBailHook.js AsyncParallelHook.js AsyncSeriesBailHook.js AsyncSeriesHook.js AsyncSeriesLoopHook.js AsyncSeriesWaterfallHook.js Hook.js HookCodeFactory.js HookMap.js MultiHook.js SyncBailHook.js SyncHook.js SyncLoopHook.js SyncWaterfallHook.js Tapable.js index.js package.json tar .travis.yml README.md examples extracter.js packer.js reader.js lib buffer-entry.js entry-writer.js entry.js extended-header-writer.js extended-header.js extract.js global-header-writer.js header.js pack.js parse.js package.json tar.js test 00-setup-fixtures.js dir-normalization.js error-on-broken.js extract-move.js extract.js header.js pack-no-proprietary.js pack.js parse-discard.js parse.js zz-cleanup.js terser-webpack-plugin CHANGELOG.md README.md dist TaskRunner.js cjs.js index.js minify.js options.json worker.js node_modules source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.d.ts source-map.js package.json terser CHANGELOG.md PATRONS.md README.md dist bundle.js bundle.min.js node_modules source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.d.ts source-map.js package.json tools colorless-console.js domprops.js exit.js node.js props.html terser.d.ts through2 LICENSE.md README.md package.json through2.js thunky .travis.yml README.md index.js package.json test.js timers-browserify CHANGELOG.md LICENSE.md README.md main.js package.json to-arraybuffer .travis.yml .zuul.yml README.md index.js package.json test.js to-fast-properties index.js package.json readme.md to-object-path README.md index.js node_modules kind-of README.md index.js package.json package.json to-regex-range README.md index.js package.json to-regex README.md index.js package.json tough-cookie README.md lib cookie.js memstore.js pathMatch.js permuteDomain.js pubsuffix-psl.js store.js node_modules punycode LICENSE-MIT.txt README.md package.json punycode.js package.json trim-newlines index.js package.json readme.md trim-right index.js package.json readme.md true-case-path README.md index.js package.json tslib CopyrightNotice.txt LICENSE.txt README.md bower.json docs generator.md package.json tslib.d.ts tslib.es6.html tslib.es6.js tslib.html tslib.js tty-browserify index.js package.json tunnel-agent README.md index.js package.json tweetnacl AUTHORS.md CHANGELOG.md PULL_REQUEST_TEMPLATE.md README.md nacl-fast.js nacl-fast.min.js nacl.d.ts nacl.js nacl.min.js package.json type-is HISTORY.md README.md index.js package.json typedarray .travis.yml example tarray.js index.js package.json test server undef_globals.js tarray.js unicode-canonical-property-names-ecmascript LICENSE-MIT.txt README.md index.js package.json unicode-match-property-ecmascript LICENSE-MIT.txt README.md index.js package.json unicode-match-property-value-ecmascript LICENSE-MIT.txt README.md data mappings.js index.js package.json unicode-property-aliases-ecmascript LICENSE-MIT.txt README.md index.js package.json union-value README.md index.js node_modules extend-shallow README.md index.js package.json set-value README.md index.js package.json package.json uniq README.md package.json test test.js uniq.js unique-filename .nyc_output 54942.json 54944.json README.md coverage __root__ index.html index.js.html base.css index.html prettify.css prettify.js sorter.js index.js package.json test index.js unique-slug .travis.yml README.md index.js package.json test index.js unpipe HISTORY.md README.md index.js package.json unset-value README.md index.js node_modules has-value README.md index.js node_modules isobject README.md index.js package.json package.json has-values README.md index.js package.json package.json upath build code upath.js package.json readme.md upath.d.ts uri-js README.md bower.json dist es5 uri.all.d.ts uri.all.js uri.all.min.d.ts uri.all.min.js esnext index.d.ts index.js regexps-iri.d.ts regexps-iri.js regexps-uri.d.ts regexps-uri.js schemes http.d.ts http.js https.d.ts https.js mailto.d.ts mailto.js urn-uuid.d.ts urn-uuid.js urn.d.ts urn.js uri.d.ts uri.js util.d.ts util.js package.json rollup.config.js src index.ts punycode.d.ts regexps-iri.ts regexps-uri.ts schemes http.ts https.ts mailto.ts urn-uuid.ts urn.ts uri.ts util.ts tests qunit.css qunit.js test-es5-min.html test-es5.html tests.js tsconfig.json urix index.js package.json readme.md test index.js url-parse README.md dist url-parse.js url-parse.min.js index.js package.json url .travis.yml .zuul.yml README.md node_modules punycode LICENSE-MIT.txt README.md package.json punycode.js package.json test.js url.js util.js use README.md index.js package.json util-deprecate History.md README.md browser.js node.js package.json util.promisify .travis.yml CHANGELOG.md README.md implementation.js index.js package.json polyfill.js shim.js util CHANGELOG.md README.md package.json support isBuffer.js isBufferBrowser.js util.js utils-merge README.md index.js package.json uuid .eslintrc.json CHANGELOG.md LICENSE.md README.md README_js.md index.js lib bytesToUuid.js md5-browser.js md5.js rng-browser.js rng.js sha1-browser.js sha1.js v35.js package.json v1.js v3.js v4.js v5.js v8-compile-cache CHANGELOG.md README.md package.json v8-compile-cache.js validate-npm-package-license README.md index.js package.json vary HISTORY.md README.md index.js package.json verror CHANGES.md CONTRIBUTING.md README.md lib verror.js package.json vm-browserify example run bundle.js entry.js index.html server.js index.js package.json test vm.js watchpack README.md lib DirectoryWatcher.js watcherManager.js watchpack.js package.json wbuf README.md index.js package.json test wbuf-test.js webpack-cli CHANGELOG.md README.md bin cli.js config-yargs.js convert-argv.js errorHelpers.js optionsSchema.json prepareOptions.js prompt-command.js webpackConfigurationSchema.json package.json webpack-dev-middleware CHANGELOG.md README.md index.js lib DevMiddlewareError.js context.js fs.js middleware.js reporter.js util.js node_modules mime .eslintrc.json .github ISSUE_TEMPLATE.md PULL_REQUEST_TEMPLATE.md .travis.yml CHANGELOG.md CONTRIBUTING.md Mime.js README.md cli.js index.js lite.js package.json src README_js.md benchmark.js build.js test.js types other.json standard.json package.json webpack-dev-server CHANGELOG.md README.md bin options.js webpack-dev-server.js client index.bundle.js index.js live.bundle.js live.html overlay.js socket.js sockjs.bundle.js webpack.config.js lib Server.js options.json utils addEntries.js colors.js createCertificate.js createConfig.js createDomain.js createLogger.js defaultTo.js findPort.js getVersions.js runBonjour.js status.js tryParseInt.js updateCompiler.js node_modules ansi-regex index.js package.json readme.md debug CHANGELOG.md README.md dist debug.js package.json src browser.js common.js index.js node.js ms index.js license.md package.json readme.md semver CHANGELOG.md README.md package.json semver.js strip-ansi index.js package.json readme.md supports-color browser.js index.js package.json readme.md package.json webpack-log CHANGELOG.md README.md package.json src index.js loglevel LogLevel.js MethodFactory.js PrefixFactory.js index.js webpack-sources README.md lib CachedSource.js ConcatSource.js LineToLineMappedSource.js OriginalSource.js PrefixSource.js RawSource.js ReplaceSource.js Source.js SourceAndMapMixin.js SourceMapSource.js index.js node_modules source-map CHANGELOG.md README.md dist source-map.debug.js source-map.js source-map.min.js lib array-set.js base64-vlq.js base64.js binary-search.js mapping-list.js quick-sort.js source-map-consumer.js source-map-generator.js source-node.js util.js package.json source-map.d.ts source-map.js package.json webpack README.md SECURITY.md bin webpack.js buildin amd-define.js amd-options.js global.js harmony-module.js module.js system.js declarations WebpackOptions.d.ts plugins BannerPlugin.d.ts DllPlugin.d.ts DllReferencePlugin.d.ts HashedModuleIdsPlugin.d.ts IgnorePlugin.d.ts LoaderOptionsPlugin.d.ts ProgressPlugin.d.ts SourceMapDevToolPlugin.d.ts WatchIgnorePlugin.d.ts debug ProfilingPlugin.d.ts optimize AggressiveSplittingPlugin.d.ts LimitChunkCountPlugin.d.ts MinChunkSizePlugin.d.ts OccurrenceOrderChunkIdsPlugin.d.ts OccurrenceOrderModuleIdsPlugin.d.ts hot dev-server.js emitter.js log-apply-result.js log.js only-dev-server.js poll.js signal.js lib APIPlugin.js AmdMainTemplatePlugin.js AsyncDependenciesBlock.js AsyncDependencyToInitialChunkError.js AutomaticPrefetchPlugin.js BannerPlugin.js BasicEvaluatedExpression.js CachePlugin.js CaseSensitiveModulesWarning.js Chunk.js ChunkGroup.js ChunkRenderError.js ChunkTemplate.js CommentCompilationWarning.js CompatibilityPlugin.js Compilation.js Compiler.js ConcurrentCompilationError.js ConstPlugin.js ContextExclusionPlugin.js ContextModule.js ContextModuleFactory.js ContextReplacementPlugin.js DefinePlugin.js DelegatedModule.js DelegatedModuleFactoryPlugin.js DelegatedPlugin.js DependenciesBlock.js DependenciesBlockVariable.js Dependency.js DllEntryPlugin.js DllModule.js DllModuleFactory.js DllPlugin.js DllReferencePlugin.js DynamicEntryPlugin.js EntryModuleNotFoundError.js EntryOptionPlugin.js Entrypoint.js EnvironmentPlugin.js ErrorHelpers.js EvalDevToolModulePlugin.js EvalDevToolModuleTemplatePlugin.js EvalSourceMapDevToolModuleTemplatePlugin.js EvalSourceMapDevToolPlugin.js ExportPropertyMainTemplatePlugin.js ExtendedAPIPlugin.js ExternalModule.js ExternalModuleFactoryPlugin.js ExternalsPlugin.js FlagDependencyExportsPlugin.js FlagDependencyUsagePlugin.js FlagInitialModulesAsUsedPlugin.js FunctionModulePlugin.js FunctionModuleTemplatePlugin.js Generator.js GraphHelpers.js HarmonyLinkingError.js HashedModuleIdsPlugin.js HotModuleReplacement.runtime.js HotModuleReplacementPlugin.js HotUpdateChunk.js HotUpdateChunkTemplate.js IgnorePlugin.js JavascriptGenerator.js JavascriptModulesPlugin.js JsonGenerator.js JsonModulesPlugin.js JsonParser.js LibManifestPlugin.js LibraryTemplatePlugin.js LoaderOptionsPlugin.js LoaderTargetPlugin.js MainTemplate.js MemoryOutputFileSystem.js Module.js ModuleBuildError.js ModuleDependencyError.js ModuleDependencyWarning.js ModuleError.js ModuleFilenameHelpers.js ModuleNotFoundError.js ModuleParseError.js ModuleReason.js ModuleTemplate.js ModuleWarning.js MultiCompiler.js MultiEntryPlugin.js MultiModule.js MultiModuleFactory.js MultiStats.js MultiWatching.js NamedChunksPlugin.js NamedModulesPlugin.js NoEmitOnErrorsPlugin.js NoModeWarning.js NodeStuffPlugin.js NormalModule.js NormalModuleFactory.js NormalModuleReplacementPlugin.js NullFactory.js OptionsApply.js OptionsDefaulter.js Parser.js ParserHelpers.js PrefetchPlugin.js ProgressPlugin.js ProvidePlugin.js RawModule.js RecordIdsPlugin.js RemovedPluginError.js RequestShortener.js RequireJsStuffPlugin.js ResolverFactory.js RuleSet.js RuntimeTemplate.js SetVarMainTemplatePlugin.js SingleEntryPlugin.js SizeFormatHelpers.js SourceMapDevToolModuleOptionsPlugin.js SourceMapDevToolPlugin.js Stats.js SystemMainTemplatePlugin.js Template.js TemplatedPathPlugin.js UmdMainTemplatePlugin.js UnsupportedFeatureWarning.js UseStrictPlugin.js WarnCaseSensitiveModulesPlugin.js WarnNoModeSetPlugin.js WatchIgnorePlugin.js Watching.js WebpackError.js WebpackOptionsApply.js WebpackOptionsDefaulter.js WebpackOptionsValidationError.js compareLocations.js debug ProfilingPlugin.js dependencies AMDDefineDependency.js AMDDefineDependencyParserPlugin.js AMDPlugin.js AMDRequireArrayDependency.js AMDRequireContextDependency.js AMDRequireDependenciesBlock.js AMDRequireDependenciesBlockParserPlugin.js AMDRequireDependency.js AMDRequireItemDependency.js CommonJsPlugin.js CommonJsRequireContextDependency.js CommonJsRequireDependency.js CommonJsRequireDependencyParserPlugin.js ConstDependency.js ContextDependency.js ContextDependencyHelpers.js ContextDependencyTemplateAsId.js ContextDependencyTemplateAsRequireCall.js ContextElementDependency.js CriticalDependencyWarning.js DelegatedExportsDependency.js DelegatedSourceDependency.js DependencyReference.js DllEntryDependency.js HarmonyAcceptDependency.js HarmonyAcceptImportDependency.js HarmonyCompatibilityDependency.js HarmonyDetectionParserPlugin.js HarmonyExportDependencyParserPlugin.js HarmonyExportExpressionDependency.js HarmonyExportHeaderDependency.js HarmonyExportImportedSpecifierDependency.js HarmonyExportSpecifierDependency.js HarmonyImportDependency.js HarmonyImportDependencyParserPlugin.js HarmonyImportSideEffectDependency.js HarmonyImportSpecifierDependency.js HarmonyInitDependency.js HarmonyModulesPlugin.js HarmonyTopLevelThisParserPlugin.js ImportContextDependency.js ImportDependenciesBlock.js ImportDependency.js ImportEagerDependency.js ImportParserPlugin.js ImportPlugin.js ImportWeakDependency.js JsonExportsDependency.js LoaderDependency.js LoaderPlugin.js LocalModule.js LocalModuleDependency.js LocalModulesHelpers.js ModuleDependency.js ModuleDependencyTemplateAsId.js ModuleDependencyTemplateAsRequireId.js ModuleHotAcceptDependency.js ModuleHotDeclineDependency.js MultiEntryDependency.js NullDependency.js PrefetchDependency.js RequireContextDependency.js RequireContextDependencyParserPlugin.js RequireContextPlugin.js RequireEnsureDependenciesBlock.js RequireEnsureDependenciesBlockParserPlugin.js RequireEnsureDependency.js RequireEnsureItemDependency.js RequireEnsurePlugin.js RequireHeaderDependency.js RequireIncludeDependency.js RequireIncludeDependencyParserPlugin.js RequireIncludePlugin.js RequireResolveContextDependency.js RequireResolveDependency.js RequireResolveDependencyParserPlugin.js RequireResolveHeaderDependency.js SingleEntryDependency.js SystemPlugin.js UnsupportedDependency.js WebAssemblyExportImportedDependency.js WebAssemblyImportDependency.js WebpackMissingModule.js getFunctionExpression.js formatLocation.js node NodeChunkTemplatePlugin.js NodeEnvironmentPlugin.js NodeHotUpdateChunkTemplatePlugin.js NodeMainTemplate.runtime.js NodeMainTemplateAsync.runtime.js NodeMainTemplatePlugin.js NodeOutputFileSystem.js NodeSourcePlugin.js NodeTargetPlugin.js NodeTemplatePlugin.js NodeWatchFileSystem.js ReadFileCompileWasmTemplatePlugin.js optimize AggressiveMergingPlugin.js AggressiveSplittingPlugin.js ChunkModuleIdRangePlugin.js ConcatenatedModule.js EnsureChunkConditionsPlugin.js FlagIncludedChunksPlugin.js LimitChunkCountPlugin.js MergeDuplicateChunksPlugin.js MinChunkSizePlugin.js MinMaxSizeWarning.js ModuleConcatenationPlugin.js NaturalChunkOrderPlugin.js OccurrenceChunkOrderPlugin.js OccurrenceModuleOrderPlugin.js OccurrenceOrderPlugin.js RemoveEmptyChunksPlugin.js RemoveParentModulesPlugin.js RuntimeChunkPlugin.js SideEffectsFlagPlugin.js SplitChunksPlugin.js performance AssetsOverSizeLimitWarning.js EntrypointsOverSizeLimitWarning.js NoAsyncChunksWarning.js SizeLimitsPlugin.js util Queue.js Semaphore.js SetHelpers.js SortableSet.js StackedSetMap.js TrackingSet.js cachedMerge.js createHash.js deterministicGrouping.js identifier.js objectToMap.js validateSchema.js wasm UnsupportedWebAssemblyFeatureError.js WasmFinalizeExportsPlugin.js WasmMainTemplatePlugin.js WebAssemblyGenerator.js WebAssemblyInInitialChunkError.js WebAssemblyJavascriptGenerator.js WebAssemblyModulesPlugin.js WebAssemblyParser.js WebAssemblyUtils.js web FetchCompileWasmTemplatePlugin.js JsonpChunkTemplatePlugin.js JsonpExportMainTemplatePlugin.js JsonpHotUpdateChunkTemplatePlugin.js JsonpMainTemplate.runtime.js JsonpMainTemplatePlugin.js JsonpTemplatePlugin.js WebEnvironmentPlugin.js webpack.js webpack.web.js webworker WebWorkerChunkTemplatePlugin.js WebWorkerHotUpdateChunkTemplatePlugin.js WebWorkerMainTemplate.runtime.js WebWorkerMainTemplatePlugin.js WebWorkerTemplatePlugin.js package.json schemas WebpackOptions.json ajv.absolutePath.js plugins BannerPlugin.json DllPlugin.json DllReferencePlugin.json HashedModuleIdsPlugin.json IgnorePlugin.json LoaderOptionsPlugin.json ProgressPlugin.json SourceMapDevToolPlugin.json WatchIgnorePlugin.json debug ProfilingPlugin.json optimize AggressiveSplittingPlugin.json LimitChunkCountPlugin.json MinChunkSizePlugin.json OccurrenceOrderChunkIdsPlugin.json OccurrenceOrderModuleIdsPlugin.json web_modules node-libs-browser.js websocket-driver CHANGELOG.md LICENSE.md README.md lib websocket driver.js driver base.js client.js draft75.js draft76.js headers.js hybi.js hybi frame.js message.js proxy.js server.js stream_reader.js http_parser.js streams.js package.json websocket-extensions CHANGELOG.md LICENSE.md README.md lib parser.js pipeline README.md cell.js functor.js index.js pledge.js ring_buffer.js websocket_extensions.js package.json which-module CHANGELOG.md README.md index.js package.json which CHANGELOG.md README.md package.json which.js wide-align README.md align.js package.json worker-farm .travis.yml LICENSE.md README.md examples basic child.js index.js pi calc.js index.js index.d.ts lib child index.js farm.js fork.js index.js package.json tests child.js debug.js index.js wrap-ansi index.js node_modules ansi-regex index.js package.json readme.md is-fullwidth-code-point index.js package.json readme.md string-width index.js package.json readme.md strip-ansi index.js package.json readme.md package.json readme.md wrappy README.md package.json wrappy.js xtend README.md immutable.js mutable.js package.json test.js y18n CHANGELOG.md README.md index.js package.json yallist README.md iterator.js package.json yallist.js yargs-parser CHANGELOG.md LICENSE.txt README.md index.js lib tokenize-arg-string.js package.json yargs CHANGELOG.md README.md index.js lib apply-extends.js argsert.js command.js completion.js levenshtein.js middleware.js obj-filter.js usage.js validation.js yerror.js locales be.json de.json en.json es.json fr.json hi.json hu.json id.json it.json ja.json ko.json nb.json nl.json nn.json pirate.json pl.json pt.json pt_BR.json ru.json th.json tr.json zh_CN.json zh_TW.json package.json yargs.js | | :----------: | nested-env-vars LOAD() DROPBITS(4) RESTORE() BYTEBITS() DROPBITS(1) DROPBITS(2) zmemcpy(put, next, copy); DROPBITS(5) DROPBITS(3) PULLBYTE() DROPBITS(here.bits) DROPBITS(7) DROPBITS(last.bits) DROPBITS(state.extra) Welcome to debugging React (C) package-lock.json package.json public index.html src index.js utils connector.js countries.js webpack.config.js
# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic) [![Coverage Status](https://coveralls.io/repos/indutny/elliptic/badge.svg?branch=master&service=github)](https://coveralls.io/github/indutny/elliptic?branch=master) [![Code Climate](https://codeclimate.com/github/indutny/elliptic/badges/gpa.svg)](https://codeclimate.com/github/indutny/elliptic) [![Saucelabs Test Status](https://saucelabs.com/browser-matrix/gh-indutny-elliptic.svg)](https://saucelabs.com/u/gh-indutny-elliptic) Fast elliptic-curve cryptography in a plain javascript implementation. NOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve for your cryptography operations. ## Incentive ECC is much slower than regular RSA cryptography, the JS implementations are even more slower. ## Benchmarks ```bash $ node benchmarks/index.js Benchmarking: sign elliptic#sign x 262 ops/sec ±0.51% (177 runs sampled) eccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled) ------------------------ Fastest is elliptic#sign ======================== Benchmarking: verify elliptic#verify x 113 ops/sec ±0.50% (166 runs sampled) eccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled) ------------------------ Fastest is elliptic#verify ======================== Benchmarking: gen elliptic#gen x 294 ops/sec ±0.43% (176 runs sampled) eccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled) ------------------------ Fastest is elliptic#gen ======================== Benchmarking: ecdh elliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled) ------------------------ Fastest is elliptic#ecdh ======================== ``` ## API ### ECDSA ```javascript var EC = require('elliptic').ec; // Create and initialize EC context // (better do it once and reuse it) var ec = new EC('secp256k1'); // Generate keys var key = ec.genKeyPair(); // Sign the message's hash (input must be an array, or a hex-string) var msgHash = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var signature = key.sign(msgHash); // Export DER encoded signature in Array var derSign = signature.toDER(); // Verify signature console.log(key.verify(msgHash, derSign)); // CHECK WITH NO PRIVATE KEY var pubPoint = key.getPublic(); var x = pubPoint.getX(); var y = pubPoint.getY(); // Public Key MUST be either: // 1) '04' + hex string of x + hex string of y; or // 2) object with two hex string properties (x and y); or // 3) object with two buffer properties (x and y) var pub = pubPoint.encode('hex'); // case 1 var pub = { x: x.toString('hex'), y: y.toString('hex') }; // case 2 var pub = { x: x.toBuffer(), y: y.toBuffer() }; // case 3 var pub = { x: x.toArrayLike(Buffer), y: y.toArrayLike(Buffer) }; // case 3 // Import public key var key = ec.keyFromPublic(pub, 'hex'); // Signature MUST be either: // 1) DER-encoded signature as hex-string; or // 2) DER-encoded signature as buffer; or // 3) object with two hex-string properties (r and s); or // 4) object with two buffer properties (r and s) var signature = '3046022100...'; // case 1 var signature = new Buffer('...'); // case 2 var signature = { r: 'b1fc...', s: '9c42...' }; // case 3 // Verify signature console.log(key.verify(msgHash, signature)); ``` ### EdDSA ```javascript var EdDSA = require('elliptic').eddsa; // Create and initialize EdDSA context // (better do it once and reuse it) var ec = new EdDSA('ed25519'); // Create key pair from secret var key = ec.keyFromSecret('693e3c...'); // hex string, array or Buffer // Sign the message's hash (input must be an array, or a hex-string) var msgHash = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var signature = key.sign(msgHash).toHex(); // Verify signature console.log(key.verify(msgHash, signature)); // CHECK WITH NO PRIVATE KEY // Import public key var pub = '0a1af638...'; var key = ec.keyFromPublic(pub, 'hex'); // Verify signature var signature = '70bed1...'; console.log(key.verify(msgHash, signature)); ``` ### ECDH ```javascript var EC = require('elliptic').ec; var ec = new EC('curve25519'); // Generate keys var key1 = ec.genKeyPair(); var key2 = ec.genKeyPair(); var shared1 = key1.derive(key2.getPublic()); var shared2 = key2.derive(key1.getPublic()); console.log('Both shared secrets are BN instances'); console.log(shared1.toString(16)); console.log(shared2.toString(16)); ``` three and more members: ```javascript var EC = require('elliptic').ec; var ec = new EC('curve25519'); var A = ec.genKeyPair(); var B = ec.genKeyPair(); var C = ec.genKeyPair(); var AB = A.getPublic().mul(B.getPrivate()) var BC = B.getPublic().mul(C.getPrivate()) var CA = C.getPublic().mul(A.getPrivate()) var ABC = AB.mul(C.getPrivate()) var BCA = BC.mul(A.getPrivate()) var CAB = CA.mul(B.getPrivate()) console.log(ABC.getX().toString(16)) console.log(BCA.getX().toString(16)) console.log(CAB.getX().toString(16)) ``` NOTE: `.derive()` returns a [BN][1] instance. ## Supported curves Elliptic.js support following curve types: * Short Weierstrass * Montgomery * Edwards * Twisted Edwards Following curve 'presets' are embedded into the library: * `secp256k1` * `p192` * `p224` * `p256` * `p384` * `p521` * `curve25519` * `ed25519` NOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead. ### Implementation details ECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of the curve operations are performed on non-affine coordinates (either projective or extended), various windowing techniques are used for different cases. All operations are performed in reduction context using [bn.js][1], hashing is provided by [hash.js][2] ### Related projects * [eccrypto][3]: isomorphic implementation of ECDSA, ECDH and ECIES for both browserify and node (uses `elliptic` for browser and [secp256k1-node][4] for node) #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2014. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: http://tools.ietf.org/html/rfc6979 [1]: https://github.com/indutny/bn.js [2]: https://github.com/indutny/hash.js [3]: https://github.com/bitchan/eccrypto [4]: https://github.com/wanderer/secp256k1-node # mime Comprehensive MIME type mapping API based on mime-db module. ## Install Install with [npm](http://github.com/isaacs/npm): npm install mime ## Contributing / Testing npm run test ## Command Line mime [path_string] E.g. > mime scripts/jquery.js application/javascript ## API - Queries ### mime.lookup(path) Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. ```js var mime = require('mime'); mime.lookup('/path/to/file.txt'); // => 'text/plain' mime.lookup('file.txt'); // => 'text/plain' mime.lookup('.TXT'); // => 'text/plain' mime.lookup('htm'); // => 'text/html' ``` ### mime.default_type Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) ### mime.extension(type) Get the default extension for `type` ```js mime.extension('text/html'); // => 'html' mime.extension('application/octet-stream'); // => 'bin' ``` ### mime.charsets.lookup() Map mime-type to charset ```js mime.charsets.lookup('text/plain'); // => 'UTF-8' ``` (The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) ## API - Defining Custom Types Custom type mappings can be added on a per-project basis via the following APIs. ### mime.define() Add custom mime/extension mappings ```js mime.define({ 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], 'application/x-my-type': ['x-mt', 'x-mtt'], // etc ... }); mime.lookup('x-sft'); // => 'text/x-some-format' ``` The first entry in the extensions array is returned by `mime.extension()`. E.g. ```js mime.extension('text/x-some-format'); // => 'x-sf' ``` ### mime.load(filepath) Load mappings from an Apache ".types" format file ```js mime.load('./my_project.types'); ``` The .types file format is simple - See the `types` dir for examples. This folder contains entry points for features from [WHATWG / W3C](https://github.com/zloirock/core-js/tree/v3#web-standards) with dependencies. # webpack-sources Contains multiple classes which represent a `Source`. A `Source` can be asked for source code, size, source map and hash. ## `Source` Base class for all sources. ### Public methods All methods should be considered as expensive as they may need to do computations. #### `source` ``` js Source.prototype.source() -> String ``` Returns the represented source code as string. #### `size` ``` js Source.prototype.size() -> Number ``` Returns the size in chars of the represented source code. #### `map` ``` js Source.prototype.map(options: Object) -> Object | null ``` Returns the SourceMap of the represented source code as JSON. May return `null` if no SourceMap is available. The `options` object can contain the following keys: * `columns: Boolean` (default `true`): If set to false the implementation may omit mappings for columns. * `module: Boolean` (default `true`): If set to false the implementation may omit inner mappings for modules. #### `sourceAndMap` ``` js Source.prototype.sourceAndMap(options: Object) -> { code: String, map: Object } ``` Returns both, source code (like `Source.prototype.source()` and SourceMap (like `Source.prototype.map()`). This method could have better performance than calling `source()` and `map()` separately. See `map()` for `options`. #### `updateHash` ``` js Source.prototype.updateHash(hash: Hash) -> void ``` Updates the provided `Hash` object with the content of the represented source code. (`Hash` is an object with an `update` method, which is called with string values) #### `node` (optional) ``` js Source.prototype.node(options: Object) -> SourceNode ``` This is an optional method. It may be `null` if not implemented. Returns a `SourceNode` (see source-map library) for the represented source code. See `map()` for `options`. #### `listNode` (optional) ``` js Source.prototype.listNode(options: Object) -> SourceNode ``` This is an optional method. It may be `null` if not implemented. Returns a `SourceListMap` (see source-list-map library) for the represented source code. See `map()` for `options`. ## `RawSource` Represents source code without SourceMap. ``` js new RawSource(sourceCode: String) ``` ## `OriginalSource` Represents source code, which is a copy of the original file. ``` js new OriginalSource( sourceCode: String, name: String ) ``` * `sourceCode`: The source code. * `name`: The filename of the original source code. OriginalSource tries to create column mappings if requested, by splitting the source code at typical statement borders (`;`, `{`, `}`). ## `SourceMapSource` Represents source code with SourceMap, optionally having an additional SourceMap for the original source. ``` js new SourceMapSource( sourceCode: String, name: String, sourceMap: Object | String, originalSource?: String, innerSourceMap?: Object | String ) ``` * `sourceCode`: The source code. * `name`: The filename of the original source code. * `sourceMap`: The SourceMap for the source code. * `originalSource`: The source code of the original file. Can be omitted if the `sourceMap` already contains the original source code. * `innerSourceMap`: The SourceMap for the `originalSource`/`name`. ## `LineToLineMappedSource` Represents source code, which is mapped line by line to the original file. ``` js new LineToLineMappedSource( sourceCode: String, name: String, originalSource: String ) ``` * `sourceCode`: The source code. * `name`: The filename of the original source code. * `originalSource`: The original source code. ## `CachedSource` Decorates a `Source` and caches returned results of `map`, `source`, `size` and `sourceAndMap` in memory. Every other operation is delegated to the wrapped `Source`. ``` js new CachedSource(source: Source) ``` ## `PrefixSource` Prefix every line of the decorated `Source` with a provided string. ``` js new PrefixSource( prefix: String, source: Source ) ``` ## `ConcatSource` Concatenate mulitple `Source`s or strings to a single source. ``` js new ConcatSource( ...items?: Source | String ) ``` ### Public methods #### `add` ``` js ConcatSource.prototype.add(item: Source | String) ``` Adds an item to the source. ## `ReplaceSource` Decorates a `Source` with replacements and insertions of source code. ### Public methods #### `replace` ``` js ReplaceSource.prototype.replace( start: Number, end: Number, replacement: String ) ``` Replaces chars from `start` (0-indexed, inclusive) to `end` (0-indexed, inclusive) with `replacement`. Locations represents locations in the original source and are not influenced by other replacements or insertions. #### `insert` ``` js ReplaceSource.prototype.insert( pos: Number, insertion: String ) ``` Inserts the `insertion` before char `pos` (0-indexed). Location represents location in the original source and is not influenced by other replacements or insertions. #### `original` Get decorated `Source`. pako ========================================== [![Build Status](https://travis-ci.org/nodeca/pako.svg?branch=master)](https://travis-ci.org/nodeca/pako) [![NPM version](https://img.shields.io/npm/v/pako.svg)](https://www.npmjs.org/package/pako) > zlib port to javascript, very fast! __Why pako is cool:__ - Almost as fast in modern JS engines as C implementation (see benchmarks). - Works in browsers, you can browserify any separate component. - Chunking support for big blobs. - Results are binary equal to well known [zlib](http://www.zlib.net/) (now contains ported zlib v1.2.8). This project was done to understand how fast JS can be and is it necessary to develop native C modules for CPU-intensive tasks. Enjoy the result! __Famous projects, using pako:__ - [browserify](http://browserify.org/) (via [browserify-zlib](https://github.com/devongovett/browserify-zlib)) - [JSZip](http://stuk.github.io/jszip/) - [mincer](https://github.com/nodeca/mincer) - [JS-Git](https://github.com/creationix/js-git) and [Tedit](https://chrome.google.com/webstore/detail/tedit-development-environ/ooekdijbnbbjdfjocaiflnjgoohnblgf) by [@creationix](https://github.com/creationix) __Benchmarks:__ ``` node v0.10.26, 1mb sample: deflate-dankogai x 4.73 ops/sec ±0.82% (15 runs sampled) deflate-gildas x 4.58 ops/sec ±2.33% (15 runs sampled) deflate-imaya x 3.22 ops/sec ±3.95% (12 runs sampled) ! deflate-pako x 6.99 ops/sec ±0.51% (21 runs sampled) deflate-pako-string x 5.89 ops/sec ±0.77% (18 runs sampled) deflate-pako-untyped x 4.39 ops/sec ±1.58% (14 runs sampled) * deflate-zlib x 14.71 ops/sec ±4.23% (59 runs sampled) inflate-dankogai x 32.16 ops/sec ±0.13% (56 runs sampled) inflate-imaya x 30.35 ops/sec ±0.92% (53 runs sampled) ! inflate-pako x 69.89 ops/sec ±1.46% (71 runs sampled) inflate-pako-string x 19.22 ops/sec ±1.86% (49 runs sampled) inflate-pako-untyped x 17.19 ops/sec ±0.85% (32 runs sampled) * inflate-zlib x 70.03 ops/sec ±1.64% (81 runs sampled) node v0.11.12, 1mb sample: deflate-dankogai x 5.60 ops/sec ±0.49% (17 runs sampled) deflate-gildas x 5.06 ops/sec ±6.00% (16 runs sampled) deflate-imaya x 3.52 ops/sec ±3.71% (13 runs sampled) ! deflate-pako x 11.52 ops/sec ±0.22% (32 runs sampled) deflate-pako-string x 9.53 ops/sec ±1.12% (27 runs sampled) deflate-pako-untyped x 5.44 ops/sec ±0.72% (17 runs sampled) * deflate-zlib x 14.05 ops/sec ±3.34% (63 runs sampled) inflate-dankogai x 42.19 ops/sec ±0.09% (56 runs sampled) inflate-imaya x 79.68 ops/sec ±1.07% (68 runs sampled) ! inflate-pako x 97.52 ops/sec ±0.83% (80 runs sampled) inflate-pako-string x 45.19 ops/sec ±1.69% (57 runs sampled) inflate-pako-untyped x 24.35 ops/sec ±2.59% (40 runs sampled) * inflate-zlib x 60.32 ops/sec ±1.36% (69 runs sampled) ``` zlib's test is partially affected by marshalling (that make sense for inflate only). You can change deflate level to 0 in benchmark source, to investigate details. For deflate level 6 results can be considered as correct. __Install:__ node.js: ``` npm install pako ``` browser: ``` bower install pako ``` Example & API ------------- Full docs - http://nodeca.github.io/pako/ ```javascript var pako = require('pako'); // Deflate // var input = new Uint8Array(); //... fill input data here var output = pako.deflate(input); // Inflate (simple wrapper can throw exception on broken stream) // var compressed = new Uint8Array(); //... fill data to uncompress here try { var result = pako.inflate(compressed); } catch (err) { console.log(err); } // // Alternate interface for chunking & without exceptions // var inflator = new pako.Inflate(); inflator.push(chunk1, false); inflator.push(chunk2, false); ... inflator.push(chunkN, true); // true -> last chunk if (inflator.err) { console.log(inflator.msg); } var output = inflator.result; ``` Sometime you can wish to work with strings. For example, to send big objects as json to server. Pako detects input data type. You can force output to be string with option `{ to: 'string' }`. ```javascript var pako = require('pako'); var test = { my: 'super', puper: [456, 567], awesome: 'pako' }; var binaryString = pako.deflate(JSON.stringify(test), { to: 'string' }); // // Here you can do base64 encode, make xhr requests and so on. // var restored = JSON.parse(pako.inflate(binaryString, { to: 'string' })); ``` Notes ----- Pako does not contain some specific zlib functions: - __deflate__ - methods `deflateCopy`, `deflateBound`, `deflateParams`, `deflatePending`, `deflatePrime`, `deflateTune`. - __inflate__ - methods `inflateCopy`, `inflateMark`, `inflatePrime`, `inflateGetDictionary`, `inflateSync`, `inflateSyncPoint`, `inflateUndermine`. - High level inflate/deflate wrappers (classes) may not support some flush modes. Those should work: Z_NO_FLUSH, Z_FINISH, Z_SYNC_FLUSH. Authors ------- - Andrey Tupitsin [@anrd83](https://github.com/andr83) - Vitaly Puzrin [@puzrin](https://github.com/puzrin) Personal thanks to: - Vyacheslav Egorov ([@mraleph](https://github.com/mraleph)) for his awesome tutorials about optimising JS code for v8, [IRHydra](http://mrale.ph/irhydra/) tool and his advices. - David Duponchel ([@dduponchel](https://github.com/dduponchel)) for help with testing. Original implementation (in C): - [zlib](http://zlib.net/) by Jean-loup Gailly and Mark Adler. License ------- - MIT - all files, except `/lib/zlib` folder - ZLIB - `/lib/zlib` content This folder contains entry points for [stable ECMAScript features](https://github.com/zloirock/core-js/tree/v3#ecmascript) with dependencies. # Statuses [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP status utility for node. This module provides a list of status codes and messages sourced from a few different projects: * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) * The [Node.js project](https://nodejs.org/) * The [NGINX project](https://www.nginx.com/) * The [Apache HTTP Server project](https://httpd.apache.org/) ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install statuses ``` ## API <!-- eslint-disable no-unused-vars --> ```js var status = require('statuses') ``` ### var code = status(Integer || String) If `Integer` or `String` is a valid HTTP code or status message, then the appropriate `code` will be returned. Otherwise, an error will be thrown. <!-- eslint-disable no-undef --> ```js status(403) // => 403 status('403') // => 403 status('forbidden') // => 403 status('Forbidden') // => 403 status(306) // throws, as it's not supported by node.js ``` ### status.STATUS_CODES Returns an object which maps status codes to status messages, in the same format as the [Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). ### status.codes Returns an array of all the status codes as `Integer`s. ### var msg = status[code] Map of `code` to `status message`. `undefined` for invalid `code`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status[404] // => 'Not Found' ``` ### var code = status[msg] Map of `status message` to `code`. `msg` can either be title-cased or lower-cased. `undefined` for invalid `status message`s. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status['not found'] // => 404 status['Not Found'] // => 404 ``` ### status.redirect[code] Returns `true` if a status code is a valid redirect status. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.redirect[200] // => undefined status.redirect[301] // => true ``` ### status.empty[code] Returns `true` if a status code expects an empty body. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.empty[200] // => undefined status.empty[204] // => true status.empty[304] // => true ``` ### status.retry[code] Returns `true` if you should retry the rest. <!-- eslint-disable no-undef, no-unused-expressions --> ```js status.retry[501] // => undefined status.retry[503] // => true ``` [npm-image]: https://img.shields.io/npm/v/statuses.svg [npm-url]: https://npmjs.org/package/statuses [node-version-image]: https://img.shields.io/node/v/statuses.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/statuses.svg [travis-url]: https://travis-ci.org/jshttp/statuses [coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg [coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master [downloads-image]: https://img.shields.io/npm/dm/statuses.svg [downloads-url]: https://npmjs.org/package/statuses # core-util-is The `util.is*` functions introduced in Node v0.12. # unpipe [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-image]][node-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Unpipe a stream from all destinations. ## Installation ```sh $ npm install unpipe ``` ## API ```js var unpipe = require('unpipe') ``` ### unpipe(stream) Unpipes all destinations from a given stream. With stream 2+, this is equivalent to `stream.unpipe()`. When used with streams 1 style streams (typically Node.js 0.8 and below), this module attempts to undo the actions done in `stream.pipe(dest)`. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/unpipe.svg [npm-url]: https://npmjs.org/package/unpipe [node-image]: https://img.shields.io/node/v/unpipe.svg [node-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg [travis-url]: https://travis-ci.org/stream-utils/unpipe [coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg [coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master [downloads-image]: https://img.shields.io/npm/dm/unpipe.svg [downloads-url]: https://npmjs.org/package/unpipe # send [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Linux Build][travis-image]][travis-url] [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url] Send is a library for streaming files from the file system as a http response supporting partial responses (Ranges), conditional-GET negotiation (If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework. Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install send ``` ## API <!-- eslint-disable no-unused-vars --> ```js var send = require('send') ``` ### send(req, path, [options]) Create a new `SendStream` for the given path to send to a `res`. The `req` is the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, not the actual file-system path). #### Options ##### acceptRanges Enable or disable accepting ranged requests, defaults to true. Disabling this will not send `Accept-Ranges` and ignore the contents of the `Range` request header. ##### cacheControl Enable or disable setting `Cache-Control` response header, defaults to true. Disabling this will ignore the `immutable` and `maxAge` options. ##### dotfiles Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If `root` is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny"). - `'allow'` No special treatment for dotfiles. - `'deny'` Send a 403 for any request for a dotfile. - `'ignore'` Pretend like the dotfile does not exist and 404. The default value is _similar_ to `'ignore'`, with the exception that this default will not ignore the files within a directory that begins with a dot, for backward-compatibility. ##### end Byte offset at which the stream ends, defaults to the length of the file minus 1. The end is inclusive in the stream, meaning `end: 3` will include the 4th byte in the stream. ##### etag Enable or disable etag generation, defaults to true. ##### extensions If a given file doesn't exist, try appending one of the given extensions, in the given order. By default, this is disabled (set to `false`). An example value that will serve extension-less HTML files: `['html', 'htm']`. This is skipped if the requested file already has an extension. ##### immutable Enable or diable the `immutable` directive in the `Cache-Control` response header, defaults to `false`. If set to `true`, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. ##### index By default send supports "index.html" files, to disable this set `false` or to supply a new index pass a string or an array in preferred order. ##### lastModified Enable or disable `Last-Modified` header, defaults to true. Uses the file system's last modified value. ##### maxAge Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ##### root Serve files relative to `path`. ##### start Byte offset at which the stream starts, defaults to 0. The start is inclusive, meaning `start: 2` will include the 3rd byte in the stream. #### Events The `SendStream` is an event emitter and will emit the following events: - `error` an error occurred `(err)` - `directory` a directory was requested `(res, path)` - `file` a file was requested `(path, stat)` - `headers` the headers are about to be set on a file `(res, path, stat)` - `stream` file streaming has started `(stream)` - `end` streaming has completed #### .pipe The `pipe` method is used to pipe the response into the Node.js HTTP response object, typically `send(req, path, options).pipe(res)`. ### .mime The `mime` export is the global instance of of the [`mime` npm module](https://www.npmjs.com/package/mime). This is used to configure the MIME types that are associated with file extensions as well as other options for how to resolve the MIME type of a file (like the default type to use for an unknown file extension). ## Error-handling By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc. ## Caching It does _not_ perform internal caching, you should use a reverse proxy cache such as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;). ## Debugging To enable `debug()` instrumentation output export __DEBUG__: ``` $ DEBUG=send node app ``` ## Running tests ``` $ npm install $ npm test ``` ## Examples ### Small example ```js var http = require('http') var parseUrl = require('parseurl') var send = require('send') var server = http.createServer(function onRequest (req, res) { send(req, parseUrl(req).pathname).pipe(res) }) server.listen(3000) ``` ### Custom file types ```js var http = require('http') var parseUrl = require('parseurl') var send = require('send') // Default unknown types to text/plain send.mime.default_type = 'text/plain' // Add a custom type send.mime.define({ 'application/x-my-type': ['x-mt', 'x-mtt'] }) var server = http.createServer(function onRequest (req, res) { send(req, parseUrl(req).pathname).pipe(res) }) server.listen(3000) ``` ### Custom directory index view This is a example of serving up a structure of directories with a custom function to render a listing of a directory. ```js var http = require('http') var fs = require('fs') var parseUrl = require('parseurl') var send = require('send') // Transfer arbitrary files from within /www/example.com/public/* // with a custom handler for directory listing var server = http.createServer(function onRequest (req, res) { send(req, parseUrl(req).pathname, {index: false, root: '/www/example.com/public'}) .once('directory', directory) .pipe(res) }) server.listen(3000) // Custom directory handler function directory (res, path) { var stream = this // redirect to trailing slash for consistent url if (!stream.hasTrailingSlash()) { return stream.redirect(path) } // get directory list fs.readdir(path, function onReaddir (err, list) { if (err) return stream.error(err) // render an index for the directory res.setHeader('Content-Type', 'text/plain; charset=UTF-8') res.end(list.join('\n') + '\n') }) } ``` ### Serving from a root directory with custom error-handling ```js var http = require('http') var parseUrl = require('parseurl') var send = require('send') var server = http.createServer(function onRequest (req, res) { // your custom error-handling logic: function error (err) { res.statusCode = err.status || 500 res.end(err.message) } // your custom headers function headers (res, path, stat) { // serve all files for download res.setHeader('Content-Disposition', 'attachment') } // your custom directory handling logic: function redirect () { res.statusCode = 301 res.setHeader('Location', req.url + '/') res.end('Redirecting to ' + req.url + '/') } // transfer arbitrary files from within // /www/example.com/public/* send(req, parseUrl(req).pathname, {root: '/www/example.com/public'}) .on('error', error) .on('directory', redirect) .on('headers', headers) .pipe(res) }) server.listen(3000) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/send.svg [npm-url]: https://npmjs.org/package/send [travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux [travis-url]: https://travis-ci.org/pillarjs/send [appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows [appveyor-url]: https://ci.appveyor.com/project/dougwilson/send [coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg [coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master [downloads-image]: https://img.shields.io/npm/dm/send.svg [downloads-url]: https://npmjs.org/package/send # for-in [![NPM version](https://img.shields.io/npm/v/for-in.svg?style=flat)](https://www.npmjs.com/package/for-in) [![NPM monthly downloads](https://img.shields.io/npm/dm/for-in.svg?style=flat)](https://npmjs.org/package/for-in) [![NPM total downloads](https://img.shields.io/npm/dt/for-in.svg?style=flat)](https://npmjs.org/package/for-in) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/for-in.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/for-in) > Iterate over the own and inherited enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save for-in ``` ## Usage ```js var forIn = require('for-in'); var obj = {a: 'foo', b: 'bar', c: 'baz'}; var values = []; var keys = []; forIn(obj, function (value, key, o) { keys.push(key); values.push(value); }); console.log(keys); //=> ['a', 'b', 'c']; console.log(values); //=> ['foo', 'bar', 'baz']; ``` ## About ### Related projects * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten "Recursively flatten an array or arrays. This is the fastest implementation of array flatten.") * [collection-map](https://www.npmjs.com/package/collection-map): Returns an array of mapped values from an array or object. | [homepage](https://github.com/jonschlinkert/collection-map "Returns an array of mapped values from an array or object.") * [for-own](https://www.npmjs.com/package/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) | [homepage](https://github.com/jonschlinkert/for-own "Iterate over the own enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 16 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [paulirish](https://github.com/paulirish) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 28, 2017._ randomfill === [![Version](http://img.shields.io/npm/v/randomfill.svg)](https://www.npmjs.org/package/randomfill) randomfill from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues ```js var randomFill = require('randomfill'); var buf randomFill.randomFillSync(16);//get 16 random bytes randomFill.randomFill(16, function (err, resp) { // resp is 16 random bytes }); ``` # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ <img align="right" alt="Ajv logo" width="160" src="http://epoberezkin.github.io/ajv/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/epoberezkin/ajv.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) ### _Ajv and [related repositories](#related-packages) will be transfered to [ajv-validator](https://github.com/ajv-validator) org_ ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/epoberezkin/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, History, License](#tests) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-8.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript). ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript var Ajv = require('ajv'); var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/epoberezkin/ajv/issues/234)). ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/jessedc/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/epoberezkin/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-07): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats The following formats are supported for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, `email`, and `hostname`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema/json-schema/wiki/$data-(v5-proposal)) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/epoberezkin/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/epoberezkin/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/epoberezkin/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - use `maxLength` to mitigate - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate - `patternProperties` for large property names - use `propertyNames` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/epoberezkin/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: 256}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/epoberezkin/ajv/issues/129), [#134](https://github.com/epoberezkin/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/epoberezkin/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/epoberezkin/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/epoberezkin/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/epoberezkin/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/epoberezkin/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass `require('js-beautify').js_beautify`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/epoberezkin/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/epoberezkin/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/epoberezkin/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/epoberezkin/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/epoberezkin/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/epoberezkin/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/epoberezkin/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/epoberezkin/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/epoberezkin/ajv/releases __Please note__: [Changes in version 6.0.0](https://github.com/epoberezkin/ajv/releases/tag/v6.0.0). [Version 5.0.0](https://github.com/epoberezkin/ajv/releases/tag/5.0.0). [Version 4.0.0](https://github.com/epoberezkin/ajv/releases/tag/4.0.0). [Version 3.0.0](https://github.com/epoberezkin/ajv/releases/tag/3.0.0). [Version 2.0.0](https://github.com/epoberezkin/ajv/releases/tag/2.0.0). ## License [MIT](https://github.com/epoberezkin/ajv/blob/master/LICENSE) # DES.js ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # shallowequal [![Build Status](https://travis-ci.org/dashed/shallowequal.svg)](https://travis-ci.org/dashed/shallowequal) [![Downloads](https://img.shields.io/npm/dm/shallowequal.svg)](https://npmjs.com/shallowequal) [![npm version](https://img.shields.io/npm/v/shallowequal.svg?style=flat)](https://www.npmjs.com/package/shallowequal) [![Greenkeeper badge](https://badges.greenkeeper.io/dashed/shallowequal.svg)](https://greenkeeper.io/) > `shallowequal` is like lodash's [`isEqualWith`](https://lodash.com/docs/4.17.4#isEqualWith) but for shallow (strict) equal. `shallowequal(value, other, [customizer], [thisArg])` Performs a ***shallow equality*** comparison between two values (i.e. `value` and `other`) to determine if they are equivalent. The equality is performed by iterating through keys on the given `value`, and returning `false` whenever any key has values which are not **strictly equal** between `value` and `other`. Otherwise, return `true` whenever the values of all keys are strictly equal. If `customizer` (expected to be a function) is provided it is invoked to compare values. If `customizer` returns `undefined` (i.e. `void 0`), then comparisons are handled by the `shallowequal` function instead. The `customizer` is bound to `thisArg` and invoked with three arguments: `(value, other, key)`. **NOTE:** Docs are (shamelessly) adapted from [lodash's v3.x docs](https://lodash.com/docs/3.10.1#isEqualWith) ## Install ```sh $ yarn add shallowequal # npm v5+ $ npm install shallowequal # before npm v5 $ npm install --save shallowequal ``` ## Usage ```js const shallowequal = require('shallowequal'); const object = { 'user': 'fred' }; const other = { 'user': 'fred' }; object == other; // → false shallowequal(object, other); // → true ``` ## Credit Code for `shallowEqual` originated from https://github.com/gaearon/react-pure-render/ and has since been refactored to have the exact same API as `lodash.isEqualWith` (as of `v4.17.4`). ## Development - `node.js` and `npm`. See: https://github.com/creationix/nvm#installation - `yarn`. See: https://yarnpkg.com/en/docs/install - `npm` dependencies. Run: `yarn install` ### Chores - Lint: `yarn lint` - Test: `yarn test` - Pretty: `yarn pretty` - Pre-publish: `yarn prepublish` ## License MIT. # is-accessor-descriptor [![NPM version](https://img.shields.io/npm/v/is-accessor-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-accessor-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-accessor-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-accessor-descriptor) > Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-accessor-descriptor ``` ## Usage ```js var isAccessor = require('is-accessor-descriptor'); isAccessor({get: function() {}}); //=> true ``` You may also pass an object and property name to check if the property is an accessor: ```js isAccessor(foo, 'bar'); ``` ## Examples `false` when not an object ```js isAccessor('a') isAccessor(null) isAccessor([]) //=> false ``` `true` when the object has valid properties and the properties all have the correct JavaScript types: ```js isAccessor({get: noop, set: noop}) isAccessor({get: noop}) isAccessor({set: noop}) //=> true ``` `false` when the object has invalid properties ```js isAccessor({get: noop, set: noop, bar: 'baz'}) isAccessor({get: noop, writable: true}) isAccessor({get: noop, value: true}) //=> false ``` `false` when an accessor is not a function ```js isAccessor({get: noop, set: 'baz'}) isAccessor({get: 'foo', set: noop}) isAccessor({get: 'foo', bar: 'baz'}) isAccessor({get: 'foo', set: 'baz'}) //=> false ``` `false` when a value is not the correct type ```js isAccessor({get: noop, set: noop, enumerable: 'foo'}) isAccessor({set: noop, configurable: 'foo'}) isAccessor({get: noop, configurable: 'foo'}) //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 22 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # osenv Look up environment settings specific to different operating systems. ## Usage ```javascript var osenv = require('osenv') var path = osenv.path() var user = osenv.user() // etc. // Some things are not reliably in the env, and have a fallback command: var h = osenv.hostname(function (er, hostname) { h = hostname }) // This will still cause it to be memoized, so calling osenv.hostname() // is now an immediate operation. // You can always send a cb, which will get called in the nextTick // if it's been memoized, or wait for the fallback data if it wasn't // found in the environment. osenv.hostname(function (er, hostname) { if (er) console.error('error looking up hostname') else console.log('this machine calls itself %s', hostname) }) ``` ## osenv.hostname() The machine name. Calls `hostname` if not found. ## osenv.user() The currently logged-in user. Calls `whoami` if not found. ## osenv.prompt() Either PS1 on unix, or PROMPT on Windows. ## osenv.tmpdir() The place where temporary files should be created. ## osenv.home() No place like it. ## osenv.path() An array of the places that the operating system will search for executables. ## osenv.editor() Return the executable name of the editor program. This uses the EDITOR and VISUAL environment variables, and falls back to `vi` on Unix, or `notepad.exe` on Windows. ## osenv.shell() The SHELL on Unix, which Windows calls the ComSpec. Defaults to 'bash' or 'cmd'. # CSS Modules: Values Pass arbitrary values between your module files ### Usage ```css /* colors.css */ @value primary: #BF4040; @value secondary: #1F4F7F; .text-primary { color: primary; } .text-secondary { color: secondary; } ``` ```css /* breakpoints.css */ @value small: (max-width: 599px); @value medium: (min-width: 600px) and (max-width: 959px); @value large: (min-width: 960px); ``` ```css /* my-component.css */ /* alias paths for other values or composition */ @value colors: "./colors.css"; /* import multiple from a single file */ @value primary, secondary from colors; /* make local aliases to imported values */ @value small as bp-small, large as bp-large from "./breakpoints.css"; .header { composes: text-primary from colors; box-shadow: 0 0 10px secondary; } @media bp-small { .header { box-shadow: 0 0 4px secondary; } } @media bp-large { .header { box-shadow: 0 0 20px secondary; } } ``` **If you are using Sass** along with this PostCSS plugin, do not use the colon `:` in your `@value` definitions. It will cause Sass to crash. Note also you can _import_ multiple values at once but can only _define_ one value per line. ```css @value a: b, c: d; /* defines a as "b, c: d" */ ``` ### Justification See [this PR](https://github.com/css-modules/css-modules-loader-core/pull/28) for more background ## License ISC ## With thanks - Mark Dalgleish - Tobias Koppers - Josh Johnston --- Glen Maddern, 2015. # graceful-fs graceful-fs functions as a drop-in replacement for the fs module, making various improvements. The improvements are meant to normalize behavior across different platforms and environments, and to make filesystem access more resilient to errors. ## Improvements over [fs module](https://nodejs.org/api/fs.html) * Queues up `open` and `readdir` calls, and retries them once something closes if there is an EMFILE error from too many file descriptors. * fixes `lchmod` for Node versions prior to 0.6.2. * implements `fs.lutimes` if possible. Otherwise it becomes a noop. * ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or `lchown` if the user isn't root. * makes `lchmod` and `lchown` become noops, if not available. * retries reading a file if `read` results in EAGAIN error. On Windows, it retries renaming a file for up to one second if `EACCESS` or `EPERM` error occurs, likely because antivirus software has locked the directory. ## USAGE ```javascript // use just like fs var fs = require('graceful-fs') // now go and do stuff with it... fs.readFileSync('some-file-or-whatever') ``` ## Global Patching If you want to patch the global fs module (or any other fs-like module) you can do this: ```javascript // Make sure to read the caveat below. var realFs = require('fs') var gracefulFs = require('graceful-fs') gracefulFs.gracefulify(realFs) ``` This should only ever be done at the top-level application layer, in order to delay on EMFILE errors from any fs-using dependencies. You should **not** do this in a library, because it can cause unexpected delays in other parts of the program. ## Changes This module is fairly stable at this point, and used by a lot of things. That being said, because it implements a subtle behavior change in a core part of the node API, even modest changes can be extremely breaking, and the versioning is thus biased towards bumping the major when in doubt. The main change between major versions has been switching between providing a fully-patched `fs` module vs monkey-patching the node core builtin, and the approach by which a non-monkey-patched `fs` was created. The goal is to trade `EMFILE` errors for slower fs operations. So, if you try to open a zillion files, rather than crashing, `open` operations will be queued up and wait for something else to `close`. There are advantages to each approach. Monkey-patching the fs means that no `EMFILE` errors can possibly occur anywhere in your application, because everything is using the same core `fs` module, which is patched. However, it can also obviously cause undesirable side-effects, especially if the module is loaded multiple times. Implementing a separate-but-identical patched `fs` module is more surgical (and doesn't run the risk of patching multiple times), but also imposes the challenge of keeping in sync with the core module. The current approach loads the `fs` module, and then creates a lookalike object that has all the same methods, except a few that are patched. It is safe to use in all versions of Node from 0.8 through 7.0. ### v4 * Do not monkey-patch the fs module. This module may now be used as a drop-in dep, and users can opt into monkey-patching the fs builtin if their app requires it. ### v3 * Monkey-patch fs, because the eval approach no longer works on recent node. * fixed possible type-error throw if rename fails on windows * verify that we *never* get EMFILE errors * Ignore ENOSYS from chmod/chown * clarify that graceful-fs must be used as a drop-in ### v2.1.0 * Use eval rather than monkey-patching fs. * readdir: Always sort the results * win32: requeue a file if error has an OK status ### v2.0 * A return to monkey patching * wrap process.cwd ### v1.1 * wrap readFile * Wrap fs.writeFile. * readdir protection * Don't clobber the fs builtin * Handle fs.read EAGAIN errors by trying again * Expose the curOpen counter * No-op lchown/lchmod if not implemented * fs.rename patch only for win32 * Patch fs.rename to handle AV software on Windows * Close #4 Chown should not fail on einval or eperm if non-root * Fix isaacs/fstream#1 Only wrap fs one time * Fix #3 Start at 1024 max files, then back off on EMFILE * lutimes that doens't blow up on Linux * A full on-rewrite using a queue instead of just swallowing the EMFILE error * Wrap Read/Write streams as well ### 1.0 * Update engines for node 0.6 * Be lstat-graceful on Windows * first # node-pre-gyp #### node-pre-gyp makes it easy to publish and install Node.js C++ addons from binaries [![NPM](https://nodei.co/npm/node-pre-gyp.png?downloads=true&downloadRank=true)](https://nodei.co/npm/node-pre-gyp/) [![Build Status](https://api.travis-ci.org/mapbox/node-pre-gyp.svg)](https://travis-ci.org/mapbox/node-pre-gyp) [![Build status](https://ci.appveyor.com/api/projects/status/3nxewb425y83c0gv)](https://ci.appveyor.com/project/Mapbox/node-pre-gyp) [![Dependencies](https://david-dm.org/mapbox/node-pre-gyp.svg)](https://david-dm.org/mapbox/node-pre-gyp) `node-pre-gyp` stands between [npm](https://github.com/npm/npm) and [node-gyp](https://github.com/Tootallnate/node-gyp) and offers a cross-platform method of binary deployment. ### Features - A command line tool called `node-pre-gyp` that can install your package's C++ module from a binary. - A variety of developer targeted commands for packaging, testing, and publishing binaries. - A JavaScript module that can dynamically require your installed binary: `require('node-pre-gyp').find` For a hello world example of a module packaged with `node-pre-gyp` see <https://github.com/springmeyer/node-addon-example> and [the wiki ](https://github.com/mapbox/node-pre-gyp/wiki/Modules-using-node-pre-gyp) for real world examples. ## Credits - The module is modeled after [node-gyp](https://github.com/Tootallnate/node-gyp) by [@Tootallnate](https://github.com/Tootallnate) - Motivation for initial development came from [@ErisDS](https://github.com/ErisDS) and the [Ghost Project](https://github.com/TryGhost/Ghost). - Development is sponsored by [Mapbox](https://www.mapbox.com/) ## FAQ See the [Frequently Ask Questions](https://github.com/mapbox/node-pre-gyp/wiki/FAQ). ## Depends - Node.js >= node v6.x ## Install `node-pre-gyp` is designed to be installed as a local dependency of your Node.js C++ addon and accessed like: ./node_modules/.bin/node-pre-gyp --help But you can also install it globally: npm install node-pre-gyp -g ## Usage ### Commands View all possible commands: node-pre-gyp --help - clean - Remove the entire folder containing the compiled .node module - install - Install pre-built binary for module - reinstall - Run "clean" and "install" at once - build - Compile the module by dispatching to node-gyp or nw-gyp - rebuild - Run "clean" and "build" at once - package - Pack binary into tarball - testpackage - Test that the staged package is valid - publish - Publish pre-built binary - unpublish - Unpublish pre-built binary - info - Fetch info on published binaries You can also chain commands: node-pre-gyp clean build unpublish publish info ### Options Options include: - `-C/--directory`: run the command in this directory - `--build-from-source`: build from source instead of using pre-built binary - `--update-binary`: reinstall by replacing previously installed local binary with remote binary - `--runtime=node-webkit`: customize the runtime: `node`, `electron` and `node-webkit` are the valid options - `--fallback-to-build`: fallback to building from source if pre-built binary is not available - `--target=0.4.0`: Pass the target node or node-webkit version to compile against - `--target_arch=ia32`: Pass the target arch and override the host `arch`. Valid values are 'ia32','x64', or `arm`. - `--target_platform=win32`: Pass the target platform and override the host `platform`. Valid values are `linux`, `darwin`, `win32`, `sunos`, `freebsd`, `openbsd`, and `aix`. Both `--build-from-source` and `--fallback-to-build` can be passed alone or they can provide values. You can pass `--fallback-to-build=false` to override the option as declared in package.json. In addition to being able to pass `--build-from-source` you can also pass `--build-from-source=myapp` where `myapp` is the name of your module. For example: `npm install --build-from-source=myapp`. This is useful if: - `myapp` is referenced in the package.json of a larger app and therefore `myapp` is being installed as a dependency with `npm install`. - The larger app also depends on other modules installed with `node-pre-gyp` - You only want to trigger a source compile for `myapp` and the other modules. ### Configuring This is a guide to configuring your module to use node-pre-gyp. #### 1) Add new entries to your `package.json` - Add `node-pre-gyp` to `dependencies` - Add `aws-sdk` as a `devDependency` - Add a custom `install` script - Declare a `binary` object This looks like: ```js "dependencies" : { "node-pre-gyp": "0.6.x" }, "devDependencies": { "aws-sdk": "2.x" } "scripts": { "install": "node-pre-gyp install --fallback-to-build" }, "binary": { "module_name": "your_module", "module_path": "./lib/binding/", "host": "https://your_module.s3-us-west-1.amazonaws.com" } ``` For a full example see [node-addon-examples's package.json](https://github.com/springmeyer/node-addon-example/blob/master/package.json). Let's break this down: - Dependencies need to list `node-pre-gyp` - Your devDependencies should list `aws-sdk` so that you can run `node-pre-gyp publish` locally or a CI system. We recommend using `devDependencies` only since `aws-sdk` is large and not needed for `node-pre-gyp install` since it only uses http to fetch binaries - Your `scripts` section should override the `install` target with `"install": "node-pre-gyp install --fallback-to-build"`. This allows node-pre-gyp to be used instead of the default npm behavior of always source compiling with `node-gyp` directly. - Your package.json should contain a `binary` section describing key properties you provide to allow node-pre-gyp to package optimally. They are detailed below. NOte: in the past we recommended putting `node-pre-gyp` in the `bundledDependencies`, but we no longer recommend this. In the past there were npm bugs (with node versions 0.10.x) that could lead to node-pre-gyp not being available at the right time during install (unless we bundled). This should no longer be the case. Also, for a time we recommended using `"preinstall": "npm install node-pre-gyp"` as an alternative method to avoid needing to bundle. But this did not behave predictably across all npm versions - see https://github.com/mapbox/node-pre-gyp/issues/260 for the details. So we do not recommend using `preinstall` to install `node-pre-gyp`. More history on this at https://github.com/strongloop/fsevents/issues/157#issuecomment-265545908. ##### The `binary` object has three required properties ###### module_name The name of your native node module. This value must: - Match the name passed to [the NODE_MODULE macro](http://nodejs.org/api/addons.html#addons_hello_world) - Must be a valid C variable name (e.g. it cannot contain `-`) - Should not include the `.node` extension. ###### module_path The location your native module is placed after a build. This should be an empty directory without other Javascript files. This entire directory will be packaged in the binary tarball. When installing from a remote package this directory will be overwritten with the contents of the tarball. Note: This property supports variables based on [Versioning](#versioning). ###### host A url to the remote location where you've published tarball binaries (must be `https` not `http`). It is highly recommended that you use Amazon S3. The reasons are: - Various node-pre-gyp commands like `publish` and `info` only work with an S3 host. - S3 is a very solid hosting platform for distributing large files. - We provide detail documentation for using [S3 hosting](#s3-hosting) with node-pre-gyp. Why then not require S3? Because while some applications using node-pre-gyp need to distribute binaries as large as 20-30 MB, others might have very small binaries and might wish to store them in a GitHub repo. This is not recommended, but if an author really wants to host in a non-S3 location then it should be possible. It should also be mentioned that there is an optional and entirely separate npm module called [node-pre-gyp-github](https://github.com/bchr02/node-pre-gyp-github) which is intended to complement node-pre-gyp and be installed along with it. It provides the ability to store and publish your binaries within your repositories GitHub Releases if you would rather not use S3 directly. Installation and usage instructions can be found [here](https://github.com/bchr02/node-pre-gyp-github), but the basic premise is that instead of using the ```node-pre-gyp publish``` command you would use ```node-pre-gyp-github publish```. ##### The `binary` object has two optional properties ###### remote_path It **is recommended** that you customize this property. This is an extra path to use for publishing and finding remote tarballs. The default value for `remote_path` is `""` meaning that if you do not provide it then all packages will be published at the base of the `host`. It is recommended to provide a value like `./{name}/v{version}` to help organize remote packages in the case that you choose to publish multiple node addons to the same `host`. Note: This property supports variables based on [Versioning](#versioning). ###### package_name It is **not recommended** to override this property unless you are also overriding the `remote_path`. This is the versioned name of the remote tarball containing the binary `.node` module and any supporting files you've placed inside the `module_path` directory. Unless you specify `package_name` in your `package.json` then it defaults to `{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz` which allows your binary to work across node versions, platforms, and architectures. If you are using `remote_path` that is also versioned by `./{module_name}/v{version}` then you could remove these variables from the `package_name` and just use: `{node_abi}-{platform}-{arch}.tar.gz`. Then your remote tarball will be looked up at, for example, `https://example.com/your-module/v0.1.0/node-v11-linux-x64.tar.gz`. Avoiding the version of your module in the `package_name` and instead only embedding in a directory name can be useful when you want to make a quick tag of your module that does not change any C++ code. In this case you can just copy binaries to the new version behind the scenes like: ```sh aws s3 sync --acl public-read s3://mapbox-node-binary/sqlite3/v3.0.3/ s3://mapbox-node-binary/sqlite3/v3.0.4/ ``` Note: This property supports variables based on [Versioning](#versioning). #### 2) Add a new target to binding.gyp `node-pre-gyp` calls out to `node-gyp` to compile the module and passes variables along like [module_name](#module_name) and [module_path](#module_path). A new target must be added to `binding.gyp` that moves the compiled `.node` module from `./build/Release/module_name.node` into the directory specified by `module_path`. Add a target like this at the end of your `targets` list: ```js { "target_name": "action_after_build", "type": "none", "dependencies": [ "<(module_name)" ], "copies": [ { "files": [ "<(PRODUCT_DIR)/<(module_name).node" ], "destination": "<(module_path)" } ] } ``` For a full example see [node-addon-example's binding.gyp](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/binding.gyp). #### 3) Dynamically require your `.node` Inside the main js file that requires your addon module you are likely currently doing: ```js var binding = require('../build/Release/binding.node'); ``` or: ```js var bindings = require('./bindings') ``` Change those lines to: ```js var binary = require('node-pre-gyp'); var path = require('path'); var binding_path = binary.find(path.resolve(path.join(__dirname,'./package.json'))); var binding = require(binding_path); ``` For a full example see [node-addon-example's index.js](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/index.js#L1-L4) #### 4) Build and package your app Now build your module from source: npm install --build-from-source The `--build-from-source` tells `node-pre-gyp` to not look for a remote package and instead dispatch to node-gyp to build. Now `node-pre-gyp` should now also be installed as a local dependency so the command line tool it offers can be found at `./node_modules/.bin/node-pre-gyp`. #### 5) Test Now `npm test` should work just as it did before. #### 6) Publish the tarball Then package your app: ./node_modules/.bin/node-pre-gyp package Once packaged, now you can publish: ./node_modules/.bin/node-pre-gyp publish Currently the `publish` command pushes your binary to S3. This requires: - You have installed `aws-sdk` with `npm install aws-sdk` - You have created a bucket already. - The `host` points to an S3 http or https endpoint. - You have configured node-pre-gyp to read your S3 credentials (see [S3 hosting](#s3-hosting) for details). You can also host your binaries elsewhere. To do this requires: - You manually publish the binary created by the `package` command to an `https` endpoint - Ensure that the `host` value points to your custom `https` endpoint. #### 7) Automate builds Now you need to publish builds for all the platforms and node versions you wish to support. This is best automated. - See [Appveyor Automation](#appveyor-automation) for how to auto-publish builds on Windows. - See [Travis Automation](#travis-automation) for how to auto-publish builds on OS X and Linux. #### 8) You're done! Now publish your module to the npm registry. Users will now be able to install your module from a binary. What will happen is this: 1. `npm install <your package>` will pull from the npm registry 2. npm will run the `install` script which will call out to `node-pre-gyp` 3. `node-pre-gyp` will fetch the binary `.node` module and unpack in the right place 4. Assuming that all worked, you are done If a a binary was not available for a given platform and `--fallback-to-build` was used then `node-gyp rebuild` will be called to try to source compile the module. ## N-API Considerations [N-API](https://nodejs.org/api/n-api.html#n_api_n_api) is an ABI-stable alternative to previous technologies such as [nan](https://github.com/nodejs/nan) which are tied to a specific Node runtime engine. N-API is Node runtime engine agnostic and guarantees modules created today will continue to run, without changes, into the future. Using `node-pre-gyp` with N-API projects requires a handful of additional configuration values and imposes some additional requirements. The most significant difference is that an N-API module can be coded to target multiple N-API versions. Therefore, an N-API module must declare in its `package.json` file which N-API versions the module is designed to run against. In addition, since multiple builds may be required for a single module, path and file names must be specified in way that avoids naming conflicts. ### The `napi_versions` array property An N-API modules must declare in its `package.json` file, the N-API versions the module is intended to support. This is accomplished by including an `napi-versions` array property in the `binary` object. For example: ```js "binary": { "module_name": "your_module", "module_path": "your_module_path", "host": "https://your_bucket.s3-us-west-1.amazonaws.com", "napi_versions": [1,3] } ``` If the `napi_versions` array property is *not* present, `node-pre-gyp` operates as it always has. Including the `napi_versions` array property instructs `node-pre-gyp` that this is a N-API module build. When the `napi_versions` array property is present, `node-pre-gyp` fires off multiple operations, one for each of the N-API versions in the array. In the example above, two operations are initiated, one for N-API version 1 and second for N-API version 3. How this version number is communicated is described next. ### The `napi_build_version` value For each of the N-API module operations `node-pre-gyp` initiates, it ensures that the `napi_build_version` is set appropriately. This value is of importance in two areas: 1. The C/C++ code which needs to know against which N-API version it should compile. 2. `node-pre-gyp` itself which must assign appropriate path and file names to avoid collisions. ### Defining `NAPI_BUILD_VERSION` for the C/C++ code The `napi_build_version` value is communicated to the C/C++ code by adding this code to the `binding.gyp` file: ``` "defines": [ "NAPI_BUILD_VERSION=<(napi_build_version)", ] ``` This ensures that `NAPI_BUILD_VERSION`, an integer value, is declared appropriately to the C/C++ code for each build. ### Path and file naming requirements in `package.json` Since `node-pre-gyp` fires off multiple operations for each request, it is essential that path and file names be created in such a way as to avoid collisions. This is accomplished by imposing additional path and file naming requirements. Specifically, when performing N-API builds, the `{napi_build_version}` text substitution string *must* be present in the `module_path` property. In addition, the `{napi_build_version}` text substitution string *must* be present in either the `remote_path` or `package_name` property. (No problem if it's in both.) Here's an example: ```js "binary": { "module_name": "your_module", "module_path": "./lib/binding/napi-v{napi_build_version}", "remote_path": "./{module_name}/v{version}/{configuration}/", "package_name": "{platform}-{arch}-napi-v{napi_build_version}.tar.gz", "host": "https://your_bucket.s3-us-west-1.amazonaws.com", "napi_versions": [1,3] } ``` ### Two additional configuration values For those who need them in legacy projects, two additional configuration values are available for all builds. 1. `napi_version` If N-API is supported by the currently executing Node instance, this value is the N-API version number supported by Node. If N-API is not supported, this value is an empty string. 2. `node_abi_napi` If the value returned for `napi_version` is non empty, this value is `'napi'`. If the value returned for `napi_version` is empty, this value is the value returned for `node_abi`. These values are present for use in the `binding.gyp` file and may be used as `{napi_version}` and `{node_abi_napi}` for text substituion in the `binary` properties of the `package.json` file. ## S3 Hosting You can host wherever you choose but S3 is cheap, `node-pre-gyp publish` expects it, and S3 can be integrated well with [Travis.ci](http://travis-ci.org) to automate builds for OS X and Ubuntu, and with [Appveyor](http://appveyor.com) to automate builds for Windows. Here is an approach to do this: First, get setup locally and test the workflow: #### 1) Create an S3 bucket And have your **key** and **secret key** ready for writing to the bucket. It is recommended to create a IAM user with a policy that only gives permissions to the specific bucket you plan to publish to. This can be done in the [IAM console](https://console.aws.amazon.com/iam/) by: 1) adding a new user, 2) choosing `Attach User Policy`, 3) Using the `Policy Generator`, 4) selecting `Amazon S3` for the service, 5) adding the actions: `DeleteObject`, `GetObject`, `GetObjectAcl`, `ListBucket`, `PutObject`, `PutObjectAcl`, 6) adding an ARN of `arn:aws:s3:::bucket/*` (replacing `bucket` with your bucket name), and finally 7) clicking `Add Statement` and saving the policy. It should generate a policy like: ```js { "Version": "2012-10-17", "Statement": [ { "Sid": "Stmt1394587197000", "Effect": "Allow", "Action": [ "s3:DeleteObject", "s3:GetObject", "s3:GetObjectAcl", "s3:ListBucket", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "arn:aws:s3:::node-pre-gyp-tests/*" ] } ] } ``` #### 2) Install node-pre-gyp Either install it globally: npm install node-pre-gyp -g Or put the local version on your PATH export PATH=`pwd`/node_modules/.bin/:$PATH #### 3) Configure AWS credentials There are several ways to do this. You can use any of the methods described at http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html. Or you can create a `~/.node_pre_gyprc` Or pass options in any way supported by [RC](https://github.com/dominictarr/rc#standards) A `~/.node_pre_gyprc` looks like: ```js { "accessKeyId": "xxx", "secretAccessKey": "xxx" } ``` Another way is to use your environment: export node_pre_gyp_accessKeyId=xxx export node_pre_gyp_secretAccessKey=xxx You may also need to specify the `region` if it is not explicit in the `host` value you use. The `bucket` can also be specified but it is optional because `node-pre-gyp` will detect it from the `host` value. #### 4) Package and publish your build Install the `aws-sdk`: npm install aws-sdk Then publish: node-pre-gyp package publish Note: if you hit an error like `Hostname/IP doesn't match certificate's altnames` it may mean that you need to provide the `region` option in your config. ## Appveyor Automation [Appveyor](http://www.appveyor.com/) can build binaries and publish the results per commit and supports: - Windows Visual Studio 2013 and related compilers - Both 64 bit (x64) and 32 bit (x86) build configurations - Multiple Node.js versions For an example of doing this see [node-sqlite3's appveyor.yml](https://github.com/mapbox/node-sqlite3/blob/master/appveyor.yml). Below is a guide to getting set up: #### 1) Create a free Appveyor account Go to https://ci.appveyor.com/signup/free and sign in with your GitHub account. #### 2) Create a new project Go to https://ci.appveyor.com/projects/new and select the GitHub repo for your module #### 3) Add appveyor.yml and push it Once you have committed an `appveyor.yml` ([appveyor.yml reference](http://www.appveyor.com/docs/appveyor-yml)) to your GitHub repo and pushed it AppVeyor should automatically start building your project. #### 4) Create secure variables Encrypt your S3 AWS keys by going to <https://ci.appveyor.com/tools/encrypt> and hitting the `encrypt` button. Then paste the result into your `appveyor.yml` ```yml environment: node_pre_gyp_accessKeyId: secure: Dn9HKdLNYvDgPdQOzRq/DqZ/MPhjknRHB1o+/lVU8MA= node_pre_gyp_secretAccessKey: secure: W1rwNoSnOku1r+28gnoufO8UA8iWADmL1LiiwH9IOkIVhDTNGdGPJqAlLjNqwLnL ``` NOTE: keys are per account but not per repo (this is difference than Travis where keys are per repo but not related to the account used to encrypt them). #### 5) Hook up publishing Just put `node-pre-gyp package publish` in your `appveyor.yml` after `npm install`. #### 6) Publish when you want You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: SET CM=%APPVEYOR_REPO_COMMIT_MESSAGE% if not "%CM%" == "%CM:[publish binary]=%" node-pre-gyp --msvs_version=2013 publish If your commit message contains special characters (e.g. `&`) this method might fail. An alternative is to use PowerShell, which gives you additional possibilities, like ignoring case by using `ToLower()`: ps: if($env:APPVEYOR_REPO_COMMIT_MESSAGE.ToLower().Contains('[publish binary]')) { node-pre-gyp --msvs_version=2013 publish } Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. ## Travis Automation [Travis](https://travis-ci.org/) can push to S3 after a successful build and supports both: - Ubuntu Precise and OS X (64 bit) - Multiple Node.js versions For an example of doing this see [node-add-example's .travis.yml](https://github.com/springmeyer/node-addon-example/blob/2ff60a8ded7f042864ad21db00c3a5a06cf47075/.travis.yml). Note: if you need 32 bit binaries, this can be done from a 64 bit Travis machine. See [the node-sqlite3 scripts for an example of doing this](https://github.com/mapbox/node-sqlite3/blob/bae122aa6a2b8a45f6b717fab24e207740e32b5d/scripts/build_against_node.sh#L54-L74). Below is a guide to getting set up: #### 1) Install the Travis gem gem install travis #### 2) Create secure variables Make sure you run this command from within the directory of your module. Use `travis-encrypt` like: travis encrypt node_pre_gyp_accessKeyId=${node_pre_gyp_accessKeyId} travis encrypt node_pre_gyp_secretAccessKey=${node_pre_gyp_secretAccessKey} Then put those values in your `.travis.yml` like: ```yaml env: global: - secure: F+sEL/v56CzHqmCSSES4pEyC9NeQlkoR0Gs/ZuZxX1ytrj8SKtp3MKqBj7zhIclSdXBz4Ev966Da5ctmcTd410p0b240MV6BVOkLUtkjZJyErMBOkeb8n8yVfSoeMx8RiIhBmIvEn+rlQq+bSFis61/JkE9rxsjkGRZi14hHr4M= - secure: o2nkUQIiABD139XS6L8pxq3XO5gch27hvm/gOdV+dzNKc/s2KomVPWcOyXNxtJGhtecAkABzaW8KHDDi5QL1kNEFx6BxFVMLO8rjFPsMVaBG9Ks6JiDQkkmrGNcnVdxI/6EKTLHTH5WLsz8+J7caDBzvKbEfTux5EamEhxIWgrI= ``` More details on Travis encryption at http://about.travis-ci.org/docs/user/encryption-keys/. #### 3) Hook up publishing Just put `node-pre-gyp package publish` in your `.travis.yml` after `npm install`. ##### OS X publishing If you want binaries for OS X in addition to linux you can enable [multi-os for Travis](http://docs.travis-ci.com/user/multi-os/#Setting-.travis.yml) Use a configuration like: ```yml language: cpp os: - linux - osx env: matrix: - NODE_VERSION="4" - NODE_VERSION="6" before_install: - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm - source ~/.nvm/nvm.sh - nvm install $NODE_VERSION - nvm use $NODE_VERSION ``` See [Travis OS X Gotchas](#travis-os-x-gotchas) for why we replace `language: node_js` and `node_js:` sections with `language: cpp` and a custom matrix. Also create platform specific sections for any deps that need install. For example if you need libpng: ```yml - if [ $(uname -s) == 'Linux' ]; then apt-get install libpng-dev; fi; - if [ $(uname -s) == 'Darwin' ]; then brew install libpng; fi; ``` For detailed multi-OS examples see [node-mapnik](https://github.com/mapnik/node-mapnik/blob/master/.travis.yml) and [node-sqlite3](https://github.com/mapbox/node-sqlite3/blob/master/.travis.yml). ##### Travis OS X Gotchas First, unlike the Travis Linux machines, the OS X machines do not put `node-pre-gyp` on PATH by default. To do so you will need to: ```sh export PATH=$(pwd)/node_modules/.bin:${PATH} ``` Second, the OS X machines do not support using a matrix for installing different Node.js versions. So you need to bootstrap the installation of Node.js in a cross platform way. By doing: ```yml env: matrix: - NODE_VERSION="4" - NODE_VERSION="6" before_install: - rm -rf ~/.nvm/ && git clone --depth 1 https://github.com/creationix/nvm.git ~/.nvm - source ~/.nvm/nvm.sh - nvm install $NODE_VERSION - nvm use $NODE_VERSION ``` You can easily recreate the previous behavior of this matrix: ```yml node_js: - "4" - "6" ``` #### 4) Publish when you want You might wish to publish binaries only on a specific commit. To do this you could borrow from the [Travis CI idea of commit keywords](http://about.travis-ci.org/docs/user/how-to-skip-a-build/) and add special handling for commit messages with `[publish binary]`: COMMIT_MESSAGE=$(git log --format=%B --no-merges -n 1 | tr -d '\n') if [[ ${COMMIT_MESSAGE} =~ "[publish binary]" ]]; then node-pre-gyp publish; fi; Then you can trigger new binaries to be built like: git commit -a -m "[publish binary]" Or, if you don't have any changes to make simply run: git commit --allow-empty -m "[publish binary]" WARNING: if you are working in a pull request and publishing binaries from there then you will want to avoid double publishing when Travis CI builds both the `push` and `pr`. You only want to run the publish on the `push` commit. See https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/is_pr_merge.sh which is called from https://github.com/Project-OSRM/node-osrm/blob/8eb837abe2e2e30e595093d16e5354bc5c573575/scripts/publish.sh for an example of how to do this. Remember this publishing is not the same as `npm publish`. We're just talking about the binary module here and not your entire npm package. To automate the publishing of your entire package to npm on Travis see http://about.travis-ci.org/docs/user/deployment/npm/ # Versioning The `binary` properties of `module_path`, `remote_path`, and `package_name` support variable substitution. The strings are evaluated by `node-pre-gyp` depending on your system and any custom build flags you passed. - `node_abi`: The node C++ `ABI` number. This value is available in Javascript as `process.versions.modules` as of [`>= v0.10.4 >= v0.11.7`](https://github.com/joyent/node/commit/ccabd4a6fa8a6eb79d29bc3bbe9fe2b6531c2d8e) and in C++ as the `NODE_MODULE_VERSION` define much earlier. For versions of Node before this was available we fallback to the V8 major and minor version. - `platform` matches node's `process.platform` like `linux`, `darwin`, and `win32` unless the user passed the `--target_platform` option to override. - `arch` matches node's `process.arch` like `x64` or `ia32` unless the user passes the `--target_arch` option to override. - `libc` matches `require('detect-libc').family` like `glibc` or `musl` unless the user passes the `--target_libc` option to override. - `configuration` - Either 'Release' or 'Debug' depending on if `--debug` is passed during the build. - `module_name` - the `binary.module_name` attribute from `package.json`. - `version` - the semver `version` value for your module from `package.json` (NOTE: ignores the `semver.build` property). - `major`, `minor`, `patch`, and `prelease` match the individual semver values for your module's `version` - `build` - the sevmer `build` value. For example it would be `this.that` if your package.json `version` was `v1.0.0+this.that` - `prerelease` - the semver `prerelease` value. For example it would be `alpha.beta` if your package.json `version` was `v1.0.0-alpha.beta` The options are visible in the code at <https://github.com/mapbox/node-pre-gyp/blob/612b7bca2604508d881e1187614870ba19a7f0c5/lib/util/versioning.js#L114-L127> # Download binary files from a mirror S3 is broken in China for the well known reason. Using the `npm` config argument: `--{module_name}_binary_host_mirror` can download binary files through a mirror. e.g.: Install [v8-profiler](https://www.npmjs.com/package/v8-profiler) from `npm`. ```bash $ npm install v8-profiler --profiler_binary_host_mirror=https://npm.taobao.org/mirrors/node-inspector/ ``` #is-regex <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] [![browser support][9]][10] Is this value a JS regex? This module works cross-realm/iframe, and despite ES6 @@toStringTag. ## Example ```js var isRegex = require('is-regex'); var assert = require('assert'); assert.notOk(isRegex(undefined)); assert.notOk(isRegex(null)); assert.notOk(isRegex(false)); assert.notOk(isRegex(true)); assert.notOk(isRegex(42)); assert.notOk(isRegex('foo')); assert.notOk(isRegex(function () {})); assert.notOk(isRegex([])); assert.notOk(isRegex({})); assert.ok(isRegex(/a/g)); assert.ok(isRegex(new RegExp('a', 'g'))); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-regex [2]: http://versionbadg.es/ljharb/is-regex.svg [3]: https://travis-ci.org/ljharb/is-regex.svg [4]: https://travis-ci.org/ljharb/is-regex [5]: https://david-dm.org/ljharb/is-regex.svg [6]: https://david-dm.org/ljharb/is-regex [7]: https://david-dm.org/ljharb/is-regex/dev-status.svg [8]: https://david-dm.org/ljharb/is-regex#info=devDependencies [9]: https://ci.testling.com/ljharb/is-regex.png [10]: https://ci.testling.com/ljharb/is-regex [11]: https://nodei.co/npm/is-regex.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/is-regex.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/is-regex.svg [downloads-url]: http://npm-stat.com/charts.html?package=is-regex ## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). * Intuitive encode/decode API * Streaming support for Node v0.10+ * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). * License: MIT. [![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) ## Usage ### Basic API ```javascript var iconv = require('iconv-lite'); // Convert from an encoded buffer to js string. str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); // Convert from js string to an encoded buffer. buf = iconv.encode("Sample input string", 'win1251'); // Check if encoding is supported iconv.encodingExists("us-ascii") ``` ### Streaming API (Node v0.10+) ```javascript // Decode stream (from binary stream to js strings) http.createServer(function(req, res) { var converterStream = iconv.decodeStream('win1251'); req.pipe(converterStream); converterStream.on('data', function(str) { console.log(str); // Do something with decoded strings, chunk-by-chunk. }); }); // Convert encoding streaming example fs.createReadStream('file-in-win1251.txt') .pipe(iconv.decodeStream('win1251')) .pipe(iconv.encodeStream('ucs2')) .pipe(fs.createWriteStream('file-in-ucs2.txt')); // Sugar: all encode/decode streams have .collect(cb) method to accumulate data. http.createServer(function(req, res) { req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { assert(typeof body == 'string'); console.log(body); // full request body string }); }); ``` ### [Deprecated] Extend Node.js own encodings > NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). ```javascript // After this call all Node basic primitives will understand iconv-lite encodings. iconv.extendNodeEncodings(); // Examples: buf = new Buffer(str, 'win1251'); buf.write(str, 'gbk'); str = buf.toString('latin1'); assert(Buffer.isEncoding('iso-8859-15')); Buffer.byteLength(str, 'us-ascii'); http.createServer(function(req, res) { req.setEncoding('big5'); req.collect(function(err, body) { console.log(body); }); }); fs.createReadStream("file.txt", "shift_jis"); // External modules are also supported (if they use Node primitives, which they probably do). request = require('request'); request({ url: "http://github.com/", encoding: "cp932" }); // To remove extensions iconv.undoExtendNodeEncodings(); ``` ## Supported encodings * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. Aliases like 'latin1', 'us-ascii' also supported. * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! ## Encoding/decoding speed Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). Note: your results may vary, so please always check on your hardware. operation [email protected] [email protected] ---------------------------------------------------------- encode('win1251') ~96 Mb/s ~320 Mb/s decode('win1251') ~95 Mb/s ~246 Mb/s ## BOM handling * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. * Encoding: No BOM added, unless overridden by `addBOM: true` option. ## UTF-16 Encodings This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be smart about endianness in the following ways: * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. ## Other notes When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). Untranslatable characters are set to � or ?. No transliteration is currently supported. Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). ## Testing ```bash $ git clone [email protected]:ashtuchkin/iconv-lite.git $ cd iconv-lite $ npm install $ npm test $ # To view performance: $ node test/performance.js $ # To view test coverage: $ npm run coverage $ open coverage/lcov-report/index.html ``` # EventSource [![npm version](http://img.shields.io/npm/v/eventsource.svg?style=flat-square)](http://browsenpm.org/package/eventsource)[![Build Status](http://img.shields.io/travis/EventSource/eventsource/master.svg?style=flat-square)](https://travis-ci.org/EventSource/eventsource)[![NPM Downloads](https://img.shields.io/npm/dm/eventsource.svg?style=flat-square)](http://npm-stat.com/charts.html?package=eventsource&from=2015-09-01)[![Dependencies](https://img.shields.io/david/EventSource/eventsource.svg?style=flat-square)](https://david-dm.org/EventSource/eventsource) This library is a pure JavaScript implementation of the [EventSource](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) client. The API aims to be W3C compatible. You can use it with Node.js or as a browser polyfill for [browsers that don't have native `EventSource` support](http://caniuse.com/#feat=eventsource). ## Install npm install eventsource ## Example npm install node ./example/sse-server.js node ./example/sse-client.js # Node.js client open http://localhost:8080 # Browser client - both native and polyfill curl http://localhost:8080/sse # Enjoy the simplicity of SSE ## Browser Polyfill Just add `example/eventsource-polyfill.js` file to your web page: ```html <script src=/eventsource-polyfill.js></script> ``` Now you will have two global constructors: ```javascript window.EventSourcePolyfill window.EventSource // Unchanged if browser has defined it. Otherwise, same as window.EventSourcePolyfill ``` If you're using [webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) you can of course build your own. (The `example/eventsource-polyfill.js` is built with webpack). ## Extensions to the W3C API ### Setting HTTP request headers You can define custom HTTP headers for the initial HTTP request. This can be useful for e.g. sending cookies or to specify an initial `Last-Event-ID` value. HTTP headers are defined by assigning a `headers` attribute to the optional `eventSourceInitDict` argument: ```javascript var eventSourceInitDict = {headers: {'Cookie': 'test=test'}}; var es = new EventSource(url, eventSourceInitDict); ``` ### Allow unauthorized HTTPS requests By default, https requests that cannot be authorized will cause the connection to fail and an exception to be emitted. You can override this behaviour, along with other https options: ```javascript var eventSourceInitDict = {https: {rejectUnauthorized: false}}; var es = new EventSource(url, eventSourceInitDict); ``` Note that for Node.js < v0.10.x this option has no effect - unauthorized HTTPS requests are *always* allowed. ### HTTP status code on error events Unauthorized and redirect error status codes (for example 401, 403, 301, 307) are available in the `status` property in the error event. ```javascript es.onerror = function (err) { if (err) { if (err.status === 401 || err.status === 403) { console.log('not authorized'); } } }; ``` ### HTTP/HTTPS proxy You can define a `proxy` option for the HTTP request to be used. This is typically useful if you are behind a corporate firewall. ```javascript var es = new EventSource(url, {proxy: 'http://your.proxy.com'}); ``` ## License MIT-licensed. See LICENSE # Select Hose [![Build Status](https://secure.travis-ci.org/indutny/select-hose.png)](http://travis-ci.org/indutny/select-hose) [![NPM version](https://badge.fury.io/js/select-hose.svg)](http://badge.fury.io/js/select-hose) Hose the data to the handler ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. node-html-entities ================== [![Build Status](https://travis-ci.org/mdevils/node-html-entities.svg?branch=master)](https://travis-ci.org/mdevils/node-html-entities) [![Coverage Status](https://coveralls.io/repos/mdevils/node-html-entities/badge.svg?branch=master&service=github)](https://coveralls.io/github/mdevils/node-html-entities?branch=master) Fast html entities library. Installation ------------ ```bash $ npm install html-entities ``` Usage ----- **XML entities** HTML validity and XSS attack prevention you can achieve from XmlEntities class. ```javascript const Entities = require('html-entities').XmlEntities; const entities = new Entities(); console.log(entities.encode('<>"\'&©®')); // &lt;&gt;&quot;&apos;&amp;©® console.log(entities.encodeNonUTF('<>"\'&©®')); // &lt;&gt;&quot;&apos;&amp;&#169;&#174; console.log(entities.encodeNonASCII('<>"\'&©®')); // <>"\'&©® console.log(entities.decode('&lt;&gt;&quot;&apos;&amp;&copy;&reg;&#8710;')); // <>"'&&copy;&reg;∆ ``` **All HTML entities encoding/decoding** ```javascript const Entities = require('html-entities').AllHtmlEntities; const entities = new Entities(); console.log(entities.encode('<>"&©®∆')); // &lt;&gt;&quot;&amp;&copy;&reg;∆ console.log(entities.encodeNonUTF('<>"&©®∆')); // &lt;&gt;&quot;&amp;&copy;&reg;&#8710; console.log(entities.encodeNonASCII('<>"&©®∆')); // <>"&©®&#8710; console.log(entities.decode('&lt;&gt;&quot;&amp;&copy;&reg;')); // <>"&©® ``` **Available classes** ```javascript const XmlEntities = require('html-entities').XmlEntities, // <>"'& + &#...; decoding Html4Entities = require('html-entities').Html4Entities, // HTML4 entities. Html5Entities = require('html-entities').Html5Entities, // HTML5 entities. AllHtmlEntities = require('html-entities').AllHtmlEntities; // Synonym for HTML5 entities. ``` Supports four methods for every class: * encode — encodes, replacing characters to its entity representations. Ignores UTF characters with no entity representation. * encodeNonUTF — encodes, replacing characters to its entity representations. Inserts numeric entities for UTF characters. * encodeNonASCII — encodes, replacing only non-ASCII characters to its numeric entity representations. * decode — decodes, replacing entities to characters. Unknown entities are left as is. Forge Flash Support =================== SocketPool.swf -------------- Some special networking features can optionally use a Flash component. Building the output SWF file requires the [Flex SDK][]. A pre-built component is included: `swf/SocketPool.swf`. Building the output SWF requires the `mxmlc` tool from the [Flex SDK][]. If that tools is already installed then look in the `package.json` file for the commands to rebuild it. If you need the SDK installed, there is a npm module that installs it: npm install To build a regular component: npm run build Additional debug support can be built in with the following: npm run build-debug Policy Server ------------- Flash support requires the use of a Policy Server. ### Apache Flash Socket Policy Module [mod_fsp](./mod_fsp) provides an [Apache][] module that can serve up a Flash Socket Policy. See `mod_fsp/README` for more details. This module makes it easy to modify an [Apache][] server to allow cross domain requests to be made to it. ### Simple Python Policy Server `policyserver.py` provides a very simple test policy server. ### Simple Node.js Policy Server `policyserver.js` provides a very simple test policy server. If a server is needed for production environments, please use another option such as perhaps [nodejs_socket_policy_server][]. [Apache]: http://httpd.apache.org/ [Flex SDK]: https://flex.apache.org/ [nodejs_socket_policy_server]: https://github.com/bichinger/nodejs_socket_policy_server # prop-types [![Build Status](https://travis-ci.com/facebook/prop-types.svg?branch=master)](https://travis-ci.org/facebook/prop-types) Runtime type checking for React props and similar objects. You can use prop-types to document the intended types of properties passed to components. React (and potentially other libraries—see the checkPropTypes() reference below) will check props passed to your components against those definitions, and warn in development if they don’t match. ## Installation ```shell npm install --save prop-types ``` ## Importing ```js import PropTypes from 'prop-types'; // ES6 var PropTypes = require('prop-types'); // ES5 with npm ``` ### CDN If you prefer to exclude `prop-types` from your application and use it globally via `window.PropTypes`, the `prop-types` package provides single-file distributions, which are hosted on the following CDNs: * [**unpkg**](https://unpkg.com/prop-types/) ```html <!-- development version --> <script src="https://unpkg.com/[email protected]/prop-types.js"></script> <!-- production version --> <script src="https://unpkg.com/[email protected]/prop-types.min.js"></script> ``` * [**cdnjs**](https://cdnjs.com/libraries/prop-types) ```html <!-- development version --> <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script> <!-- production version --> <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script> ``` To load a specific version of `prop-types` replace `15.6.0` with the version number. ## Usage PropTypes was originally exposed as part of the React core module, and is commonly used with React components. Here is an example of using PropTypes with a React component, which also documents the different validators provided: ```js import React from 'react'; import PropTypes from 'prop-types'; class MyComponent extends React.Component { render() { // ... do things with the props } } MyComponent.propTypes = { // You can declare that a prop is a specific JS primitive. By default, these // are all optional. optionalArray: PropTypes.array, optionalBool: PropTypes.bool, optionalFunc: PropTypes.func, optionalNumber: PropTypes.number, optionalObject: PropTypes.object, optionalString: PropTypes.string, optionalSymbol: PropTypes.symbol, // Anything that can be rendered: numbers, strings, elements or an array // (or fragment) containing these types. optionalNode: PropTypes.node, // A React element (ie. <MyComponent />). optionalElement: PropTypes.element, // A React element type (ie. MyComponent). optionalElementType: PropTypes.elementType, // You can also declare that a prop is an instance of a class. This uses // JS's instanceof operator. optionalMessage: PropTypes.instanceOf(Message), // You can ensure that your prop is limited to specific values by treating // it as an enum. optionalEnum: PropTypes.oneOf(['News', 'Photos']), // An object that could be one of many types optionalUnion: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.instanceOf(Message) ]), // An array of a certain type optionalArrayOf: PropTypes.arrayOf(PropTypes.number), // An object with property values of a certain type optionalObjectOf: PropTypes.objectOf(PropTypes.number), // You can chain any of the above with `isRequired` to make sure a warning // is shown if the prop isn't provided. // An object taking on a particular shape optionalObjectWithShape: PropTypes.shape({ optionalProperty: PropTypes.string, requiredProperty: PropTypes.number.isRequired }), // An object with warnings on extra properties optionalObjectWithStrictShape: PropTypes.exact({ optionalProperty: PropTypes.string, requiredProperty: PropTypes.number.isRequired }), requiredFunc: PropTypes.func.isRequired, // A value of any data type requiredAny: PropTypes.any.isRequired, // You can also specify a custom validator. It should return an Error // object if the validation fails. Don't `console.warn` or throw, as this // won't work inside `oneOfType`. customProp: function(props, propName, componentName) { if (!/matchme/.test(props[propName])) { return new Error( 'Invalid prop `' + propName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } }, // You can also supply a custom validator to `arrayOf` and `objectOf`. // It should return an Error object if the validation fails. The validator // will be called for each key in the array or object. The first two // arguments of the validator are the array or object itself, and the // current item's key. customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) { if (!/matchme/.test(propValue[key])) { return new Error( 'Invalid prop `' + propFullName + '` supplied to' + ' `' + componentName + '`. Validation failed.' ); } }) }; ``` Refer to the [React documentation](https://facebook.github.io/react/docs/typechecking-with-proptypes.html) for more information. ## Migrating from React.PropTypes Check out [Migrating from React.PropTypes](https://facebook.github.io/react/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) for details on how to migrate to `prop-types` from `React.PropTypes`. Note that this blog posts **mentions a codemod script that performs the conversion automatically**. There are also important notes below. ## How to Depend on This Package? For apps, we recommend putting it in `dependencies` with a caret range. For example: ```js "dependencies": { "prop-types": "^15.5.7" } ``` For libraries, we *also* recommend leaving it in `dependencies`: ```js "dependencies": { "prop-types": "^15.5.7" }, "peerDependencies": { "react": "^15.5.0" } ``` **Note:** there are known issues in versions before 15.5.7 so we recommend using it as the minimal version. Make sure that the version range uses a caret (`^`) and thus is broad enough for npm to efficiently deduplicate packages. For UMD bundles of your components, make sure you **don’t** include `PropTypes` in the build. Usually this is done by marking it as an external (the specifics depend on your bundler), just like you do with React. ## Compatibility ### React 0.14 This package is compatible with **React 0.14.9**. Compared to 0.14.8 (which was released in March of 2016), there are no other changes in 0.14.9, so it should be a painless upgrade. ```shell # ATTENTION: Only run this if you still use React 0.14! npm install --save react@^0.14.9 react-dom@^0.14.9 ``` ### React 15+ This package is compatible with **React 15.3.0** and higher. ``` npm install --save react@^15.3.0 react-dom@^15.3.0 ``` ### What happens on other React versions? It outputs warnings with the message below even though the developer doesn’t do anything wrong. Unfortunately there is no solution for this other than updating React to either 15.3.0 or higher, or 0.14.9 if you’re using React 0.14. ## Difference from `React.PropTypes`: Don’t Call Validator Functions First of all, **which version of React are you using**? You might be seeing this message because a component library has updated to use `prop-types` package, but your version of React is incompatible with it. See the [above section](#compatibility) for more details. Are you using either React 0.14.9 or a version higher than React 15.3.0? Read on. When you migrate components to use the standalone `prop-types`, **all validator functions will start throwing an error if you call them directly**. This makes sure that nobody relies on them in production code, and it is safe to strip their implementations to optimize the bundle size. Code like this is still fine: ```js MyComponent.propTypes = { myProp: PropTypes.bool }; ``` However, code like this will not work with the `prop-types` package: ```js // Will not work with `prop-types` package! var errorOrNull = PropTypes.bool(42, 'myProp', 'MyComponent', 'prop'); ``` It will throw an error: ``` Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. ``` (If you see **a warning** rather than an error with this message, please check the [above section about compatibility](#compatibility).) This is new behavior, and you will only encounter it when you migrate from `React.PropTypes` to the `prop-types` package. For the vast majority of components, this doesn’t matter, and if you didn’t see [this warning](https://facebook.github.io/react/warnings/dont-call-proptypes.html) in your components, your code is safe to migrate. This is not a breaking change in React because you are only opting into this change for a component by explicitly changing your imports to use `prop-types`. If you temporarily need the old behavior, you can keep using `React.PropTypes` until React 16. **If you absolutely need to trigger the validation manually**, call `PropTypes.checkPropTypes()`. Unlike the validators themselves, this function is safe to call in production, as it will be replaced by an empty function: ```js // Works with standalone PropTypes PropTypes.checkPropTypes(MyComponent.propTypes, props, 'prop', 'MyComponent'); ``` See below for more info. **You might also see this error** if you’re calling a `PropTypes` validator from your own custom `PropTypes` validator. In this case, the fix is to make sure that you are passing *all* of the arguments to the inner function. There is a more in-depth explanation of how to fix it [on this page](https://facebook.github.io/react/warnings/dont-call-proptypes.html#fixing-the-false-positive-in-third-party-proptypes). Alternatively, you can temporarily keep using `React.PropTypes` until React 16, as it would still only warn in this case. If you use a bundler like Browserify or Webpack, don’t forget to [follow these instructions](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build) to correctly bundle your application in development or production mode. Otherwise you’ll ship unnecessary code to your users. ## PropTypes.checkPropTypes React will automatically check the propTypes you set on the component, but if you are using PropTypes without React then you may want to manually call `PropTypes.checkPropTypes`, like so: ```js const myPropTypes = { name: PropTypes.string, age: PropTypes.number, // ... define your prop validations }; const props = { name: 'hello', // is valid age: 'world', // not valid }; // Let's say your component is called 'MyComponent' // Works with standalone PropTypes PropTypes.checkPropTypes(myPropTypes, props, 'age', 'MyComponent'); // This will warn as follows: // Warning: Failed prop type: Invalid prop `age` of type `string` supplied to // `MyComponent`, expected `number`. ``` ## PropTypes.resetWarningCache() `PropTypes.checkPropTypes(...)` only `console.error.log(...)`s a given message once. To reset the cache while testing call `PropTypes.resetWarningCache()` ### License prop-types is [MIT licensed](./LICENSE). # core-util-is The `util.is*` functions introduced in Node v0.12. util-deprecate ============== ### The Node.js `util.deprecate()` function with browser support In Node.js, this module simply re-exports the `util.deprecate()` function. In the web browser (i.e. via browserify), a browser-specific implementation of the `util.deprecate()` function is used. ## API A `deprecate()` function is the only thing exposed by this module. ``` javascript // setup: exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); // users see: foo(); // foo() is deprecated, use bar() instead foo(); foo(); ``` ## License (The MIT License) Copyright (c) 2014 Nathan Rajlich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # collection-visit [![NPM version](https://img.shields.io/npm/v/collection-visit.svg?style=flat)](https://www.npmjs.com/package/collection-visit) [![NPM monthly downloads](https://img.shields.io/npm/dm/collection-visit.svg?style=flat)](https://npmjs.org/package/collection-visit) [![NPM total downloads](https://img.shields.io/npm/dt/collection-visit.svg?style=flat)](https://npmjs.org/package/collection-visit) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/collection-visit.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/collection-visit) > Visit a method over the items in an object, or map visit over the objects in an array. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save collection-visit ``` ## Usage ```js var visit = require('collection-visit'); var ctx = { data: {}, set: function (key, value) { if (typeof key === 'object') { visit(ctx, 'set', key); } else { ctx.data[key] = value; } } }; ctx.set('a', 'a'); ctx.set('b', 'b'); ctx.set('c', 'c'); ctx.set({d: {e: 'f'}}); console.log(ctx.data); //=> {a: 'a', b: 'b', c: 'c', d: { e: 'f' }}; ``` ## About ### Related projects * [base-methods](https://www.npmjs.com/package/base-methods): base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/jonschlinkert/base-methods) | [homepage](https://github.com/jonschlinkert/base-methods "base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [map-visit](https://www.npmjs.com/package/map-visit): Map `visit` over an array of objects. | [homepage](https://github.com/jonschlinkert/map-visit "Map `visit` over an array of objects.") * [object-visit](https://www.npmjs.com/package/object-visit): Call a specified method on each value in the given object. | [homepage](https://github.com/jonschlinkert/object-visit "Call a specified method on each value in the given object.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 13 | [jonschlinkert](https://github.com/jonschlinkert) | | 9 | [doowb](https://github.com/doowb) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 09, 2017._ # is-date-object <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] [![browser support][9]][10] Is this value a JS Date object? This module works cross-realm/iframe, and despite ES6 @@toStringTag. ## Example ```js var isDate = require('is-date-object'); var assert = require('assert'); assert.notOk(isDate(undefined)); assert.notOk(isDate(null)); assert.notOk(isDate(false)); assert.notOk(isDate(true)); assert.notOk(isDate(42)); assert.notOk(isDate('foo')); assert.notOk(isDate(function () {})); assert.notOk(isDate([])); assert.notOk(isDate({})); assert.notOk(isDate(/a/g)); assert.notOk(isDate(new RegExp('a', 'g'))); assert.ok(isDate(new Date())); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-date-object [2]: http://versionbadg.es/ljharb/is-date-object.svg [3]: https://travis-ci.org/ljharb/is-date-object.svg [4]: https://travis-ci.org/ljharb/is-date-object [5]: https://david-dm.org/ljharb/is-date-object.svg [6]: https://david-dm.org/ljharb/is-date-object [7]: https://david-dm.org/ljharb/is-date-object/dev-status.svg [8]: https://david-dm.org/ljharb/is-date-object#info=devDependencies [9]: https://ci.testling.com/ljharb/is-date-object.png [10]: https://ci.testling.com/ljharb/is-date-object [11]: https://nodei.co/npm/is-date-object.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/is-date-object.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/is-date-object.svg [downloads-url]: http://npm-stat.com/charts.html?package=is-date-object # Form-Data [![NPM Module](https://img.shields.io/npm/v/form-data.svg)](https://www.npmjs.com/package/form-data) [![Join the chat at https://gitter.im/form-data/form-data](http://form-data.github.io/images/gitterbadge.svg)](https://gitter.im/form-data/form-data) A library to create readable ```"multipart/form-data"``` streams. Can be used to submit forms and file uploads to other web applications. The API of this library is inspired by the [XMLHttpRequest-2 FormData Interface][xhr2-fd]. [xhr2-fd]: http://dev.w3.org/2006/webapi/XMLHttpRequest-2/Overview.html#the-formdata-interface [![Linux Build](https://img.shields.io/travis/form-data/form-data/v2.3.3.svg?label=linux:4.x-9.x)](https://travis-ci.org/form-data/form-data) [![MacOS Build](https://img.shields.io/travis/form-data/form-data/v2.3.3.svg?label=macos:4.x-9.x)](https://travis-ci.org/form-data/form-data) [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/form-data/v2.3.3.svg?label=windows:4.x-9.x)](https://ci.appveyor.com/project/alexindigo/form-data) [![Coverage Status](https://img.shields.io/coveralls/form-data/form-data/v2.3.3.svg?label=code+coverage)](https://coveralls.io/github/form-data/form-data?branch=master) [![Dependency Status](https://img.shields.io/david/form-data/form-data.svg)](https://david-dm.org/form-data/form-data) [![bitHound Overall Score](https://www.bithound.io/github/form-data/form-data/badges/score.svg)](https://www.bithound.io/github/form-data/form-data) ## Install ``` npm install --save form-data ``` ## Usage In this example we are constructing a form with 3 fields that contain a string, a buffer and a file stream. ``` javascript var FormData = require('form-data'); var fs = require('fs'); var form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_file', fs.createReadStream('/foo/bar.jpg')); ``` Also you can use http-response stream: ``` javascript var FormData = require('form-data'); var http = require('http'); var form = new FormData(); http.request('http://nodejs.org/images/logo.png', function(response) { form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', response); }); ``` Or @mikeal's [request](https://github.com/request/request) stream: ``` javascript var FormData = require('form-data'); var request = require('request'); var form = new FormData(); form.append('my_field', 'my value'); form.append('my_buffer', new Buffer(10)); form.append('my_logo', request('http://nodejs.org/images/logo.png')); ``` In order to submit this form to a web application, call ```submit(url, [callback])``` method: ``` javascript form.submit('http://example.org/', function(err, res) { // res – response object (http.IncomingMessage) // res.resume(); }); ``` For more advanced request manipulations ```submit()``` method returns ```http.ClientRequest``` object, or you can choose from one of the alternative submission methods. ### Custom options You can provide custom options, such as `maxDataSize`: ``` javascript var FormData = require('form-data'); var form = new FormData({ maxDataSize: 20971520 }); form.append('my_field', 'my value'); form.append('my_buffer', /* something big */); ``` List of available options could be found in [combined-stream](https://github.com/felixge/node-combined-stream/blob/master/lib/combined_stream.js#L7-L15) ### Alternative submission methods You can use node's http client interface: ``` javascript var http = require('http'); var request = http.request({ method: 'post', host: 'example.org', path: '/upload', headers: form.getHeaders() }); form.pipe(request); request.on('response', function(res) { console.log(res.statusCode); }); ``` Or if you would prefer the `'Content-Length'` header to be set for you: ``` javascript form.submit('example.org/upload', function(err, res) { console.log(res.statusCode); }); ``` To use custom headers and pre-known length in parts: ``` javascript var CRLF = '\r\n'; var form = new FormData(); var options = { header: CRLF + '--' + form.getBoundary() + CRLF + 'X-Custom-Header: 123' + CRLF + CRLF, knownLength: 1 }; form.append('my_buffer', buffer, options); form.submit('http://example.com/', function(err, res) { if (err) throw err; console.log('Done'); }); ``` Form-Data can recognize and fetch all the required information from common types of streams (```fs.readStream```, ```http.response``` and ```mikeal's request```), for some other types of streams you'd need to provide "file"-related information manually: ``` javascript someModule.stream(function(err, stdout, stderr) { if (err) throw err; var form = new FormData(); form.append('file', stdout, { filename: 'unicycle.jpg', // ... or: filepath: 'photos/toys/unicycle.jpg', contentType: 'image/jpeg', knownLength: 19806 }); form.submit('http://example.com/', function(err, res) { if (err) throw err; console.log('Done'); }); }); ``` The `filepath` property overrides `filename` and may contain a relative path. This is typically used when uploading [multiple files from a directory](https://wicg.github.io/entries-api/#dom-htmlinputelement-webkitdirectory). For edge cases, like POST request to URL with query string or to pass HTTP auth credentials, object can be passed to `form.submit()` as first parameter: ``` javascript form.submit({ host: 'example.com', path: '/probably.php?extra=params', auth: 'username:password' }, function(err, res) { console.log(res.statusCode); }); ``` In case you need to also send custom HTTP headers with the POST request, you can use the `headers` key in first parameter of `form.submit()`: ``` javascript form.submit({ host: 'example.com', path: '/surelynot.php', headers: {'x-test-header': 'test-header-value'} }, function(err, res) { console.log(res.statusCode); }); ``` ### Integration with other libraries #### Request Form submission using [request](https://github.com/request/request): ```javascript var formData = { my_field: 'my_value', my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), }; request.post({url:'http://service.com/upload', formData: formData}, function(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); ``` For more details see [request readme](https://github.com/request/request#multipartform-data-multipart-form-uploads). #### node-fetch You can also submit a form using [node-fetch](https://github.com/bitinn/node-fetch): ```javascript var form = new FormData(); form.append('a', 1); fetch('http://example.com', { method: 'POST', body: form }) .then(function(res) { return res.json(); }).then(function(json) { console.log(json); }); ``` ## Notes - ```getLengthSync()``` method DOESN'T calculate length for streams, use ```knownLength``` options as workaround. - Starting version `2.x` FormData has dropped support for `[email protected]`. ## License Form-Data is released under the [MIT](License) license. aproba ====== A ridiculously light-weight function argument validator ``` var validate = require("aproba") function myfunc(a, b, c) { // `a` must be a string, `b` a number, `c` a function validate('SNF', arguments) // [a,b,c] is also valid } myfunc('test', 23, function () {}) // ok myfunc(123, 23, function () {}) // type error myfunc('test', 23) // missing arg error myfunc('test', 23, function () {}, true) // too many args error ``` Valid types are: | type | description | :--: | :---------- | * | matches any type | A | `Array.isArray` OR an `arguments` object | S | typeof == string | N | typeof == number | F | typeof == function | O | typeof == object and not type A and not type E | B | typeof == boolean | E | `instanceof Error` OR `null` **(special: see below)** | Z | == `null` Validation failures throw one of three exception types, distinguished by a `code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`. If you pass in an invalid type then it will throw with a code of `EUNKNOWNTYPE`. If an **error** argument is found and is not null then the remaining arguments are optional. That is, if you say `ESO` then that's like using a non-magical `E` in: `E|ESO|ZSO`. ### But I have optional arguments?! You can provide more than one signature by separating them with pipes `|`. If any signature matches the arguments then they'll be considered valid. So for example, say you wanted to write a signature for `fs.createWriteStream`. The docs for it describe it thusly: ``` fs.createWriteStream(path[, options]) ``` This would be a signature of `SO|S`. That is, a string and and object, or just a string. Now, if you read the full `fs` docs, you'll see that actually path can ALSO be a buffer. And options can be a string, that is: ``` path <String> | <Buffer> options <String> | <Object> ``` To reproduce this you have to fully enumerate all of the possible combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The awkwardness is a feature: It reminds you of the complexity you're adding to your API when you do this sort of thing. ### Browser support This has no dependencies and should work in browsers, though you'll have noisier stack traces. ### Why this exists I wanted a very simple argument validator. It needed to do two things: 1. Be more concise and easier to use than assertions 2. Not encourage an infinite bikeshed of DSLs This is why types are specified by a single character and there's no such thing as an optional argument. This is not intended to validate user data. This is specifically about asserting the interface of your functions. If you need greater validation, I encourage you to write them by hand or look elsewhere. This folder contains entry points for [ECMAScript proposals](https://github.com/zloirock/core-js/tree/v3#ecmascript-proposals) with dependencies. # bonjour A Bonjour/Zeroconf protocol implementation in pure JavaScript. Publish services on the local network or discover existing services using multicast DNS. [![Build status](https://travis-ci.org/watson/bonjour.svg?branch=master)](https://travis-ci.org/watson/bonjour) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ``` npm install bonjour ``` ## Usage ```js var bonjour = require('bonjour')() // advertise an HTTP server on port 3000 bonjour.publish({ name: 'My Web Server', type: 'http', port: 3000 }) // browse for all http services bonjour.find({ type: 'http' }, function (service) { console.log('Found an HTTP server:', service) }) ``` ## API ### Initializing ```js var bonjour = require('bonjour')([options]) ``` The `options` are optional and will be used when initializing the underlying multicast-dns server. For details see [the multicast-dns documentation](https://github.com/mafintosh/multicast-dns#mdns--multicastdnsoptions). ### Publishing #### `var service = bonjour.publish(options)` Publishes a new service. Options are: - `name` (string) - `host` (string, optional) - defaults to local hostname - `port` (number) - `type` (string) - `subtypes` (array of strings, optional) - `protocol` (string, optional) - `udp` or `tcp` (default) - `txt` (object, optional) - a key/value object to broadcast as the TXT record IANA maintains a [list of official service types and port numbers](http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml). #### `bonjour.unpublishAll([callback])` Unpublish all services. The optional `callback` will be called when the services have been unpublished. #### `bonjour.destroy()` Destroy the mdns instance. Closes the udp socket. ### Browser #### `var browser = bonjour.find(options[, onup])` Listen for services advertised on the network. An optional callback can be provided as the 2nd argument and will be added as an event listener for the `up` event. Options (all optional): - `type` (string) - `subtypes` (array of strings) - `protocol` (string) - defaults to `tcp` - `txt` (object) - passed into [dns-txt module](https://github.com/watson/dns-txt) contructor. Set to `{ binary: true }` if you want to keep the TXT records in binary #### `var browser = bonjour.findOne(options[, callback])` Listen for and call the `callback` with the first instance of a service matching the `options`. If no `callback` is given, it's expected that you listen for the `up` event. The returned `browser` will automatically stop it self after the first matching service. Options are the same as given in the `browser.find` function. #### `Event: up` Emitted every time a new service is found that matches the browser. #### `Event: down` Emitted every time an existing service emmits a goodbye message. #### `browser.services` An array of services known by the browser to be online. #### `browser.start()` Start looking for matching services. #### `browser.stop()` Stop looking for matching services. #### `browser.update()` Broadcast the query again. ### Service #### `Event: up` Emitted when the service is up. #### `Event: error` Emitted if an error occurrs while publishing the service. #### `service.stop([callback])` Unpublish the service. The optional `callback` will be called when the service have been unpublished. #### `service.start()` Publish the service. #### `service.name` The name of the service, e.g. `Apple TV`. #### `service.type` The type of the service, e.g. `http`. #### `service.subtypes` An array of subtypes. Note that this property might be `null`. #### `service.protocol` The protocol used by the service, e.g. `tcp`. #### `service.host` The hostname or ip address where the service resides. #### `service.port` The port on which the service listens, e.g. `5000`. #### `service.fqdn` The fully qualified domain name of the service. E.g. if given the name `Foo Bar`, the type `http` and the protocol `tcp`, the `service.fqdn` property will be `Foo Bar._http._tcp.local`. #### `service.txt` The TXT record advertised by the service (a key/value object). Note that this property might be `null`. #### `service.published` A boolean indicating if the service is currently published. ## License MIT # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # Destroy [![NPM version][npm-image]][npm-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![Gittip][gittip-image]][gittip-url] Destroy a stream. This module is meant to ensure a stream gets destroyed, handling different APIs and Node.js bugs. ## API ```js var destroy = require('destroy') ``` ### destroy(stream) Destroy the given stream. In most cases, this is identical to a simple `stream.destroy()` call. The rules are as follows for a given stream: 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` and add a listener to the `open` event to call `stream.close()` if it is fired. This is for a Node.js bug that will leak a file descriptor if `.destroy()` is called before `open`. 2. If the `stream` is not an instance of `Stream`, then nothing happens. 3. If the `stream` has a `.destroy()` method, then call it. The function returns the `stream` passed in as the argument. ## Example ```js var destroy = require('destroy') var fs = require('fs') var stream = fs.createReadStream('package.json') // ... and later destroy(stream) ``` [npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square [npm-url]: https://npmjs.org/package/destroy [github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square [github-url]: https://github.com/stream-utils/destroy/tags [travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square [travis-url]: https://travis-ci.org/stream-utils/destroy [coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master [license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square [license-url]: LICENSE.md [downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square [downloads-url]: https://npmjs.org/package/destroy [gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square [gittip-url]: https://www.gittip.com/jonathanong/ # Electron-to-Chromium [![npm](https://img.shields.io/npm/v/electron-to-chromium.svg)](https://www.npmjs.com/package/electron-to-chromium) [![travis](https://img.shields.io/travis/Kilian/electron-to-chromium/master.svg)](https://travis-ci.org/Kilian/electron-to-chromium) [![npm-downloads](https://img.shields.io/npm/dm/electron-to-chromium.svg)](https://www.npmjs.com/package/electron-to-chromium) [![codecov](https://codecov.io/gh/Kilian/electron-to-chromium/branch/master/graph/badge.svg)](https://codecov.io/gh/Kilian/electron-to-chromium) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_shield) This repository provides a mapping of Electron versions to the Chromium version that it uses. This package is used in [Browserslist](https://github.com/ai/browserslist), so you can use e.g. `electron >= 1.4` in [Autoprefixer](https://github.com/postcss/autoprefixer), [Stylelint](https://github.com/stylelint/stylelint), [babel-preset-env](https://github.com/babel/babel-preset-env) and [eslint-plugin-compat](https://github.com/amilajack/eslint-plugin-compat). ## Install Install using `npm install electron-to-chromium`. ## Usage To include Electron-to-Chromium, require it: ```js var e2c = require('electron-to-chromium'); ``` ### Properties The Electron-to-Chromium object has 4 properties to use: #### `versions` An object of key-value pairs with a _major_ Electron version as the key, and the corresponding major Chromium version as the value. ```js var versions = e2c.versions; console.log(versions['1.4']); // returns "53" ``` #### `fullVersions` An object of key-value pairs with a Electron version as the key, and the corresponding full Chromium version as the value. ```js var versions = e2c.fullVersions; console.log(versions['1.4.11']); // returns "53.0.2785.143" ``` #### `chromiumVersions` An object of key-value pairs with a _major_ Chromium version as the key, and the corresponding major Electron version as the value. ```js var versions = e2c.chromiumVersions; console.log(versions['54']); // returns "1.4" ``` #### `fullChromiumVersions` An object of key-value pairs with a Chromium version as the key, and an array of the corresponding major Electron versions as the value. ```js var versions = e2c.fullChromiumVersions; console.log(versions['54.0.2840.101']); // returns ["1.5.1", "1.5.0"] ``` ### Functions #### `electronToChromium(query)` Arguments: * Query: string or number, required. A major or full Electron version. A function that returns the corresponding Chromium version for a given Electron function. Returns a string. If you provide it with a major Electron version, it will return a major Chromium version: ```js var chromeVersion = e2c.electronToChromium('1.4'); // chromeVersion is "53" ``` If you provide it with a full Electron version, it will return the full Chromium version. ```js var chromeVersion = e2c.electronToChromium('1.4.11'); // chromeVersion is "53.0.2785.143" ``` If a query does not match a Chromium version, it will return `undefined`. ```js var chromeVersion = e2c.electronToChromium('9000'); // chromeVersion is undefined ``` #### `chromiumToElectron(query)` Arguments: * Query: string or number, required. A major or full Chromium version. Returns a string with the corresponding Electron version for a given Chromium query. If you provide it with a major Chromium version, it will return a major Electron version: ```js var electronVersion = e2c.chromiumToElectron('54'); // electronVersion is "1.4" ``` If you provide it with a full Chrome version, it will return an array of full Electron versions. ```js var electronVersions = e2c.chromiumToElectron('56.0.2924.87'); // electronVersions is ["1.6.3", "1.6.2", "1.6.1", "1.6.0"] ``` If a query does not match an Electron version, it will return `undefined`. ```js var electronVersion = e2c.chromiumToElectron('10'); // chromeVersion is undefined ``` #### `electronToBrowserList(query)` **DEPRECATED** Arguments: * Query: string or number, required. A major Electron version. _**Deprecated**: Browserlist already includes electron-to-chromium._ A function that returns a [Browserslist](https://github.com/ai/browserslist) query that matches the given major Electron version. Returns a string. If you provide it with a major Electron version, it will return a Browserlist query string that matches the Chromium capabilities: ```js var query = e2c.electronToBrowserList('1.4'); // query is "Chrome >= 53" ``` If a query does not match a Chromium version, it will return `undefined`. ```js var query = e2c.electronToBrowserList('9000'); // query is undefined ``` ### Importing just versions, fullVersions, chromiumVersions and fullChromiumVersions All lists can be imported on their own, if file size is a concern. #### `versions` ```js var versions = require('electron-to-chromium/versions'); ``` #### `fullVersions` ```js var fullVersions = require('electron-to-chromium/full-versions'); ``` #### `chromiumVersions` ```js var chromiumVersions = require('electron-to-chromium/chromium-versions'); ``` #### `fullChromiumVersions` ```js var fullChromiumVersions = require('electron-to-chromium/full-chromium-versions'); ``` ## Updating This package will be updated with each new Electron release. To update the list, run `npm run build.js`. Requires internet access as it downloads from the canonical list of Electron versions. To verify correct behaviour, run `npm test`. ## License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2FKilian%2Felectron-to-chromium?ref=badge_large) # use [![NPM version](https://img.shields.io/npm/v/use.svg?style=flat)](https://www.npmjs.com/package/use) [![NPM monthly downloads](https://img.shields.io/npm/dm/use.svg?style=flat)](https://npmjs.org/package/use) [![NPM total downloads](https://img.shields.io/npm/dt/use.svg?style=flat)](https://npmjs.org/package/use) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/use.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/use) > Easily add plugin support to your node.js application. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save use ``` A different take on plugin handling! This is not a middleware system, if you need something that handles async middleware, [ware](https://github.com/segmentio/ware) is great for that. ## Usage ```js const use = require('use'); ``` See the [examples folder](./examples) for usage examples. ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [base-plugins](https://www.npmjs.com/package/base-plugins): Adds 'smart plugin' support to your base application. | [homepage](https://github.com/node-base/base-plugins "Adds 'smart plugin' support to your base application.") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [ware](https://www.npmjs.com/package/ware): Easily create your own middleware layer. | [homepage](https://github.com/segmentio/ware "Easily create your own middleware layer.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 37 | [jonschlinkert](https://github.com/jonschlinkert) | | 7 | [charlike-old](https://github.com/charlike-old) | | 2 | [doowb](https://github.com/doowb) | | 2 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 12, 2018._ # sax js A sax-style parser for XML and HTML. Designed with [node](http://nodejs.org/) in mind, but should work fine in the browser or other CommonJS implementations. ## What This Is * A very simple tool to parse through an XML string. * A stepping stone to a streaming HTML parser. * A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML docs. ## What This Is (probably) Not * An HTML Parser - That's a fine goal, but this isn't it. It's just XML. * A DOM Builder - You can use it to build an object model out of XML, but it doesn't do that out of the box. * XSLT - No DOM = no querying. * 100% Compliant with (some other SAX implementation) - Most SAX implementations are in Java and do a lot more than this does. * An XML Validator - It does a little validation when in strict mode, but not much. * A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic masochism. * A DTD-aware Thing - Fetching DTDs is a much bigger job. ## Regarding `<!DOCTYPE`s and `<!ENTITY`s The parser will handle the basic XML entities in text nodes and attribute values: `&amp; &lt; &gt; &apos; &quot;`. It's possible to define additional entities in XML by putting them in the DTD. This parser doesn't do anything with that. If you want to listen to the `ondoctype` event, and then fetch the doctypes, and read the entities and add them to `parser.ENTITIES`, then be my guest. Unknown entities will fail in strict mode, and in loose mode, will pass through unmolested. ## Usage ```javascript var sax = require("./lib/sax"), strict = true, // set to false for html-mode parser = sax.parser(strict); parser.onerror = function (e) { // an error happened. }; parser.ontext = function (t) { // got some text. t is the string of text. }; parser.onopentag = function (node) { // opened a tag. node has "name" and "attributes" }; parser.onattribute = function (attr) { // an attribute. attr has "name" and "value" }; parser.onend = function () { // parser stream is done, and ready to have more stuff written to it. }; parser.write('<xml>Hello, <who name="world">world</who>!</xml>').close(); // stream usage // takes the same options as the parser var saxStream = require("sax").createStream(strict, options) saxStream.on("error", function (e) { // unhandled errors will throw, since this is a proper node // event emitter. console.error("error!", e) // clear the error this._parser.error = null this._parser.resume() }) saxStream.on("opentag", function (node) { // same object as above }) // pipe is supported, and it's readable/writable // same chunks coming in also go out. fs.createReadStream("file.xml") .pipe(saxStream) .pipe(fs.createWriteStream("file-copy.xml")) ``` ## Arguments Pass the following arguments to the parser function. All are optional. `strict` - Boolean. Whether or not to be a jerk. Default: `false`. `opt` - Object bag of settings regarding string formatting. All default to `false`. Settings supported: * `trim` - Boolean. Whether or not to trim text and comment nodes. * `normalize` - Boolean. If true, then turn any whitespace into a single space. * `lowercase` - Boolean. If true, then lowercase tag names and attribute names in loose mode, rather than uppercasing them. * `xmlns` - Boolean. If true, then namespaces are supported. * `position` - Boolean. If false, then don't track line/col/position. * `strictEntities` - Boolean. If true, only parse [predefined XML entities](http://www.w3.org/TR/REC-xml/#sec-predefined-ent) (`&amp;`, `&apos;`, `&gt;`, `&lt;`, and `&quot;`) ## Methods `write` - Write bytes onto the stream. You don't have to do this all at once. You can keep writing as much as you want. `close` - Close the stream. Once closed, no more data may be written until it is done processing the buffer, which is signaled by the `end` event. `resume` - To gracefully handle errors, assign a listener to the `error` event. Then, when the error is taken care of, you can call `resume` to continue parsing. Otherwise, the parser will not continue while in an error state. ## Members At all times, the parser object will have the following members: `line`, `column`, `position` - Indications of the position in the XML document where the parser currently is looking. `startTagPosition` - Indicates the position where the current tag starts. `closed` - Boolean indicating whether or not the parser can be written to. If it's `true`, then wait for the `ready` event to write again. `strict` - Boolean indicating whether or not the parser is a jerk. `opt` - Any options passed into the constructor. `tag` - The current tag being dealt with. And a bunch of other stuff that you probably shouldn't touch. ## Events All events emit with a single argument. To listen to an event, assign a function to `on<eventname>`. Functions get executed in the this-context of the parser object. The list of supported events are also in the exported `EVENTS` array. When using the stream interface, assign handlers using the EventEmitter `on` function in the normal fashion. `error` - Indication that something bad happened. The error will be hanging out on `parser.error`, and must be deleted before parsing can continue. By listening to this event, you can keep an eye on that kind of stuff. Note: this happens *much* more in strict mode. Argument: instance of `Error`. `text` - Text node. Argument: string of text. `doctype` - The `<!DOCTYPE` declaration. Argument: doctype string. `processinginstruction` - Stuff like `<?xml foo="blerg" ?>`. Argument: object with `name` and `body` members. Attributes are not parsed, as processing instructions have implementation dependent semantics. `sgmldeclaration` - Random SGML declarations. Stuff like `<!ENTITY p>` would trigger this kind of event. This is a weird thing to support, so it might go away at some point. SAX isn't intended to be used to parse SGML, after all. `opentagstart` - Emitted immediately when the tag name is available, but before any attributes are encountered. Argument: object with a `name` field and an empty `attributes` set. Note that this is the same object that will later be emitted in the `opentag` event. `opentag` - An opening tag. Argument: object with `name` and `attributes`. In non-strict mode, tag names are uppercased, unless the `lowercase` option is set. If the `xmlns` option is set, then it will contain namespace binding information on the `ns` member, and will have a `local`, `prefix`, and `uri` member. `closetag` - A closing tag. In loose mode, tags are auto-closed if their parent closes. In strict mode, well-formedness is enforced. Note that self-closing tags will have `closeTag` emitted immediately after `openTag`. Argument: tag name. `attribute` - An attribute node. Argument: object with `name` and `value`. In non-strict mode, attribute names are uppercased, unless the `lowercase` option is set. If the `xmlns` option is set, it will also contains namespace information. `comment` - A comment node. Argument: the string of the comment. `opencdata` - The opening tag of a `<![CDATA[` block. `cdata` - The text of a `<![CDATA[` block. Since `<![CDATA[` blocks can get quite large, this event may fire multiple times for a single block, if it is broken up into multiple `write()`s. Argument: the string of random character data. `closecdata` - The closing tag (`]]>`) of a `<![CDATA[` block. `opennamespace` - If the `xmlns` option is set, then this event will signal the start of a new namespace binding. `closenamespace` - If the `xmlns` option is set, then this event will signal the end of a namespace binding. `end` - Indication that the closed stream has ended. `ready` - Indication that the stream has reset, and is ready to be written to. `noscript` - In non-strict mode, `<script>` tags trigger a `"script"` event, and their contents are not checked for special xml characters. If you pass `noscript: true`, then this behavior is suppressed. ## Reporting Problems It's best to write a failing test if you find an issue. I will always accept pull requests with failing tests if they demonstrate intended behavior, but it is very hard to figure out what issue you're describing without a test. Writing a test is also the best way for you yourself to figure out if you really understand the issue you think you have with sax-js. # is-accessor-descriptor [![NPM version](https://img.shields.io/npm/v/is-accessor-descriptor.svg)](https://www.npmjs.com/package/is-accessor-descriptor) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-accessor-descriptor.svg)](https://travis-ci.org/jonschlinkert/is-accessor-descriptor) > Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. - [Install](#install) - [Usage](#usage) - [Examples](#examples) - [API](#api) - [Related projects](#related-projects) - [Running tests](#running-tests) - [Contributing](#contributing) - [Author](#author) - [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm i is-accessor-descriptor --save ``` ## Usage ```js var isAccessor = require('is-accessor-descriptor'); isAccessor({get: function() {}}); //=> true ``` You may also pass an object and property name to check if the property is an accessor: ```js isAccessor(foo, 'bar'); ``` ## Examples `false` when not an object ```js isAccessor('a') isAccessor(null) isAccessor([]) //=> false ``` `true` when the object has valid properties and the properties all have the correct JavaScript types: ```js isAccessor({get: noop, set: noop}) isAccessor({get: noop}) isAccessor({set: noop}) //=> true ``` `false` when the object has invalid properties ```js isAccessor({get: noop, set: noop, bar: 'baz'}) isAccessor({get: noop, writable: true}) isAccessor({get: noop, value: true}) //=> false ``` `false` when an accessor is not a function ```js isAccessor({get: noop, set: 'baz'}) isAccessor({get: 'foo', set: noop}) isAccessor({get: 'foo', bar: 'baz'}) isAccessor({get: 'foo', set: 'baz'}) //=> false ``` `false` when a value is not the correct type ```js isAccessor({get: noop, set: noop, enumerable: 'foo'}) isAccessor({set: noop, configurable: 'foo'}) isAccessor({get: noop, configurable: 'foo'}) //=> false ``` ## Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor) * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor) * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://www.npmjs.com/package/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor) * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/is-accessor-descriptor/issues/new). ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 [Jon Schlinkert](https://github.com/jonschlinkert) Released under the MIT license. *** _This file was generated by [verb](https://github.com/verbose/verb) on December 28, 2015._ # jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](http://img.shields.io/coveralls/mathiasbynens/jsesc/master.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc) This is a JavaScript library for [escaping JavaScript strings](http://mathiasbynens.be/notes/javascript-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](http://mothereff.in/js-escapes) This can be used to avoid [mojibake](http://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](http://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder, respectively. Feel free to fork if you see possible improvements! ## Installation Via [Bower](http://bower.io/): ```bash bower install jsesc ``` Via [Component](https://github.com/component/component): ```bash component install mathiasbynens/jsesc ``` Via [npm](http://npmjs.org/): ```bash npm install jsesc ``` In a browser: ```html <script src="jsesc.js"></script> ``` In [Node.js](http://nodejs.org/) and [RingoJS](http://ringojs.org/): ```js var jsesc = require('jsesc'); ``` In [Narwhal](http://narwhaljs.org/): ```js var jsesc = require('jsesc').jsesc; ``` In [Rhino](http://www.mozilla.org/rhino/): ```js load('jsesc.js'); ``` Using an AMD loader like [RequireJS](http://requirejs.org/): ```js require( { 'paths': { 'jsesc': 'path/to/jsesc' } }, ['jsesc'], function(jsesc) { console.log(jsesc); } ); ``` ## API ### `jsesc(value, options)` This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](http://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings: ```js jsesc('Ich ♥ Bücher'); // → 'Ich \\u2665 B\\xFCcher' jsesc('foo 𝌆 bar'); // → 'foo \\uD834\\uDF06 bar' ``` Instead of a string, the `value` can also be an array, or an object. In such cases, `jsesc` will return a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way. ```js // Escaping an array jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ]); // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']' // Escaping an object jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }); // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}' ``` The optional `options` argument accepts an object with the following options: #### `quotes` The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input string will be escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes. ```js jsesc('Lorem ipsum "dolor" sit \'amet\' etc.'); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single' }); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." ``` If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`. ```js jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double' }); // → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.' // → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc." ``` This setting also affects the output for arrays and objects: ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'quotes': 'double' }); // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'quotes': 'double' }); // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]' ``` #### `wrap` The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. ```js jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true }); // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true }); // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" ``` #### `es6` The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input will be escaped using [ECMAScript 6 Unicode code point escape sequences](http://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`). ```js // By default, the `es6` option is disabled: jsesc('foo 𝌆 bar 💩 baz'); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To explicitly disable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': false }); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To enable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': true }); // → 'foo \\u{1D306} bar \\u{1F4A9} baz' ``` #### `escapeEverything` The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols. ```js jsesc('lolwat"foo\'bar', { 'escapeEverything': true }); // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72' // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72" ``` This setting also affects the output for arrays and objects: ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'escapeEverything': true }); // → '{\'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72\':\'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72\'}' // → "{'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72':'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72'}" jsesc([ 'Ich ♥ Bücher': 'foo 𝌆 bar' ], { 'escapeEverything': true }); // → '[\'\x49\x63\x68\x20\u2665\x20\x42\xFC\x63\x68\x65\x72\',\'\x66\x6F\x6F\x20\uD834\uDF06\x20\x62\x61\x72\']' ``` #### `compact` The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects will be as compact as possible; it won’t be formatted nicely. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': true // this is the default }); // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false }); // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `indent` The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is enabled (`true`), the value of the `indent` option is used to format the output for arrays and objects. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': '\t' // this is the default }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': ' ' }); // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false, 'indent': ' ' }); // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `json` The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](http://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](http://mathiasbynens.be/notes/javascript-escapes#single) will not be used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore. ```js jsesc('foo\x00bar\xFF\uFFFDbaz', { 'json': true }); // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"' jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, { 'json': true }); // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}' jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], { 'json': true }); // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]' // Values that are acceptable in JSON but aren’t strings, arrays, or object // literals can’t be escaped, so they’ll just be preserved: jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], { 'json': true }); // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]' // Values that aren’t allowed in JSON are run through `JSON.stringify()`: jsesc([ undefined, -Infinity ], { 'json': true }); // → '[null,null]' ``` **Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/). ### `jsesc.version` A string representing the semantic version number. ### Using the `jsesc` binary To use the `jsesc` binary in your shell, simply install jsesc globally using npm: ```bash npm install -g jsesc ``` After that you will be able to escape strings from the command line: ```bash $ jsesc 'föo ♥ bår 𝌆 baz' f\xF6o \u2665 b\xE5r \uD834\uDF06 baz ``` To escape arrays or objects containing string values, use the `-o`/`--object` option: ```bash $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }' {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'} ``` To prettify the output in such cases, use the `-p`/`--pretty` option: ```bash $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { 'f\xF6o': '\u2665', 'b\xE5r': '\uD834\uDF06 baz' } ``` For valid JSON output, use the `-j`/`--json` option: ```bash $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { "f\u00F6o": "\u2665", "b\u00E5r": "\uD834\uDF06 baz" } ``` Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file: ```bash $ jsesc --json --object < data-raw.json > data-escaped.json ``` Or do the same with an online JSON file: ```bash $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json ``` See `jsesc --help` for the full list of options. ## Support This library has been tested in at least Chrome 27-29, Firefox 3-22, Safari 4-6, Opera 10-12, IE 6-10, Node.js v0.10.0, Narwhal 0.3.2, RingoJS 0.8-0.9, PhantomJS 1.9.0, and Rhino 1.7RC4. **Note:** Using the `json` option on objects or arrays that contain non-string values relies on `JSON.parse()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/). ## Unit tests & code coverage After cloning this repository, run `npm install` to install the dependencies needed for development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`. To generate the code coverage report, use `grunt cover`. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](http://mathiasbynens.be/) | ## License This library is available under the [MIT](http://mths.be/mit) license. # postcss-value-parser [![Travis CI](https://travis-ci.org/TrySound/postcss-value-parser.svg)](https://travis-ci.org/TrySound/postcss-value-parser) Transforms CSS declaration values and at-rule parameters into a tree of nodes, and provides a simple traversal API. ## Usage ```js var valueParser = require('postcss-value-parser'); var cssBackgroundValue = 'url(foo.png) no-repeat 40px 73%'; var parsedValue = valueParser(cssBackgroundValue); // parsedValue exposes an API described below, // e.g. parsedValue.walk(..), parsedValue.toString(), etc. ``` For example, parsing the value `rgba(233, 45, 66, .5)` will return the following: ```js { nodes: [ { type: 'function', value: 'rgba', before: '', after: '', nodes: [ { type: 'word', value: '233' }, { type: 'div', value: ',', before: '', after: ' ' }, { type: 'word', value: '45' }, { type: 'div', value: ',', before: '', after: ' ' }, { type: 'word', value: '66' }, { type: 'div', value: ',', before: ' ', after: '' }, { type: 'word', value: '.5' } ] } ] } ``` If you wanted to convert each `rgba()` value in `sourceCSS` to a hex value, you could do so like this: ```js var valueParser = require('postcss-value-parser'); var parsed = valueParser(sourceCSS); // walk() will visit all the of the nodes in the tree, // invoking the callback for each. parsed.walk(function (node) { // Since we only want to transform rgba() values, // we can ignore anything else. if (node.type !== 'function' && node.value !== 'rgba') return; // We can make an array of the rgba() arguments to feed to a // convertToHex() function var color = node.nodes.filter(function (node) { return node.type === 'word'; }).map(function (node) { return Number(node.value); }); // [233, 45, 66, .5] // Now we will transform the existing rgba() function node // into a word node with the hex value node.type = 'word'; node.value = convertToHex(color); }) parsed.toString(); // #E92D42 ``` ## Nodes Each node is an object with these common properties: - **type**: The type of node (`word`, `string`, `div`, `space`, `comment`, or `function`). Each type is documented below. - **value**: Each node has a `value` property; but what exactly `value` means is specific to the node type. Details are documented for each type below. - **sourceIndex**: The starting index of the node within the original source string. For example, given the source string `10px 20px`, the `word` node whose value is `20px` will have a `sourceIndex` of `5`. ### word The catch-all node type that includes keywords (e.g. `no-repeat`), quantities (e.g. `20px`, `75%`, `1.5`), and hex colors (e.g. `#e6e6e6`). Node-specific properties: - **value**: The "word" itself. ### string A quoted string value, e.g. `"something"` in `content: "something";`. Node-specific properties: - **value**: The text content of the string. - **quote**: The quotation mark surrounding the string, either `"` or `'`. - **unclosed**: `true` if the string was not closed properly. e.g. `"unclosed string `. ### div A divider, for example - `,` in `animation-duration: 1s, 2s, 3s` - `/` in `border-radius: 10px / 23px` - `:` in `(min-width: 700px)` Node-specific properties: - **value**: The divider character. Either `,`, `/`, or `:` (see examples above). - **before**: Whitespace before the divider. - **after**: Whitespace after the divider. ### space Whitespace used as a separator, e.g. ` ` occurring twice in `border: 1px solid black;`. Node-specific properties: - **value**: The whitespace itself. ### comment A CSS comment starts with `/*` and ends with `*/` Node-specific properties: - **value**: The comment value without `/*` and `*/` - **unclosed**: `true` if the comment was not closed properly. e.g. `/* comment without an end `. ### function A CSS function, e.g. `rgb(0,0,0)` or `url(foo.bar)`. Function nodes have nodes nested within them: the function arguments. Additional properties: - **value**: The name of the function, e.g. `rgb` in `rgb(0,0,0)`. - **before**: Whitespace after the opening parenthesis and before the first argument, e.g. ` ` in `rgb( 0,0,0)`. - **after**: Whitespace before the closing parenthesis and after the last argument, e.g. ` ` in `rgb(0,0,0 )`. - **nodes**: More nodes representing the arguments to the function. - **unclosed**: `true` if the parentheses was not closed properly. e.g. `( unclosed-function `. Media features surrounded by parentheses are considered functions with an empty value. For example, `(min-width: 700px)` parses to these nodes: ```js [ { type: 'function', value: '', before: '', after: '', nodes: [ { type: 'word', value: 'min-width' }, { type: 'div', value: ':', before: '', after: ' ' }, { type: 'word', value: '700px' } ] } ] ``` `url()` functions can be parsed a little bit differently depending on whether the first character in the argument is a quotation mark. `url( /gfx/img/bg.jpg )` parses to: ```js { type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [ { type: 'word', sourceIndex: 5, value: '/gfx/img/bg.jpg' } ] } ``` `url( "/gfx/img/bg.jpg" )`, on the other hand, parses to: ```js { type: 'function', sourceIndex: 0, value: 'url', before: ' ', after: ' ', nodes: [ type: 'string', sourceIndex: 5, quote: '"', value: '/gfx/img/bg.jpg' }, ] } ``` ## API ``` var valueParser = require('postcss-value-parser'); ``` ### valueParser.unit(quantity) Parses `quantity`, distinguishing the number from the unit. Returns an object like the following: ```js // Given 2rem { number: '2', unit: 'rem' } ``` If the `quantity` argument cannot be parsed as a number, returns `false`. *This function does not parse complete values*: you cannot pass it `1px solid black` and expect `px` as the unit. Instead, you should pass it single quantities only. Parse `1px solid black`, then pass it the stringified `1px` node (a `word` node) to parse the number and unit. ### valueParser.stringify(nodes[, custom]) Stringifies a node or array of nodes. The `custom` function is called for each `node`; return a string to override the default behaviour. ### valueParser.walk(nodes, callback[, bubble]) Walks each provided node, recursively walking all descendent nodes within functions. Returning `false` in the `callback` will prevent traversal of descendent nodes (within functions). You can use this feature to for shallow iteration, walking over only the *immediate* children. *Note: This only applies if `bubble` is `false` (which is the default).* By default, the tree is walked from the outermost node inwards. To reverse the direction, pass `true` for the `bubble` argument. The `callback` is invoked with three arguments: `callback(node, index, nodes)`. - `node`: The current node. - `index`: The index of the current node. - `nodes`: The complete nodes array passed to `walk()`. Returns the `valueParser` instance. ### var parsed = valueParser(value) Returns the parsed node tree. ### parsed.nodes The array of nodes. ### parsed.toString() Stringifies the node tree. ### parsed.walk(callback[, bubble]) Walks each node inside `parsed.nodes`. See the documentation for `valueParser.walk()` above. # License MIT © [Bogdan Chadkin](mailto:[email protected]) # faye-websocket * Travis CI build: [![Build status](https://secure.travis-ci.org/faye/faye-websocket-node.svg)](http://travis-ci.org/faye/faye-websocket-node) * Autobahn tests: [server](http://faye.jcoglan.com/autobahn/servers/), [client](http://faye.jcoglan.com/autobahn/clients/) This is a general-purpose WebSocket implementation extracted from the [Faye](http://faye.jcoglan.com) project. It provides classes for easily building WebSocket servers and clients in Node. It does not provide a server itself, but rather makes it easy to handle WebSocket connections within an existing [Node](https://nodejs.org/) application. It does not provide any abstraction other than the standard [WebSocket API](https://html.spec.whatwg.org/multipage/comms.html#network). It also provides an abstraction for handling [EventSource](https://html.spec.whatwg.org/multipage/comms.html#server-sent-events) connections, which are one-way connections that allow the server to push data to the client. They are based on streaming HTTP responses and can be easier to access via proxies than WebSockets. ## Installation ``` $ npm install faye-websocket ``` ## Handling WebSocket connections in Node You can handle WebSockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual WebSocket methods for receiving and sending messages. For example this is how you'd implement an echo server: ```js var WebSocket = require('faye-websocket'), http = require('http'); var server = http.createServer(); server.on('upgrade', function(request, socket, body) { if (WebSocket.isWebSocket(request)) { var ws = new WebSocket(request, socket, body); ws.on('message', function(event) { ws.send(event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); } }); server.listen(8000); ``` `WebSocket` objects are also duplex streams, so you could replace the `ws.on('message', ...)` line with: ```js ws.pipe(ws); ``` Note that under certain circumstances (notably a draft-76 client connecting through an HTTP proxy), the WebSocket handshake will not be complete after you call `new WebSocket()` because the server will not have received the entire handshake from the client yet. In this case, calls to `ws.send()` will buffer the message in memory until the handshake is complete, at which point any buffered messages will be sent to the client. If you need to detect when the WebSocket handshake is complete, you can use the `onopen` event. If the connection's protocol version supports it, you can call `ws.ping()` to send a ping message and wait for the client's response. This method takes a message string, and an optional callback that fires when a matching pong message is received. It returns `true` if and only if a ping message was sent. If the client does not support ping/pong, this method sends no data and returns `false`. ```js ws.ping('Mic check, one, two', function() { // fires when pong is received }); ``` ## Using the WebSocket client The client supports both the plain-text `ws` protocol and the encrypted `wss` protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as `hybi-13`. ```js var WebSocket = require('faye-websocket'), ws = new WebSocket.Client('ws://www.example.com/'); ws.on('open', function(event) { console.log('open'); ws.send('Hello, world!'); }); ws.on('message', function(event) { console.log('message', event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); ``` The WebSocket client also lets you inspect the status and headers of the handshake response via its `statusCode` and `headers` properties. To connect via a proxy, set the `proxy` option to the HTTP origin of the proxy, including any authorization information, custom headers and TLS config you require. Only the `origin` setting is required. ```js var ws = new WebSocket.Client('ws://www.example.com/', [], { proxy: { origin: 'http://username:[email protected]', headers: {'User-Agent': 'node'}, tls: {cert: fs.readFileSync('client.crt')} } }); ``` The `tls` value is an object that will be passed to [`tls.connect()`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). ## Subprotocol negotiation The WebSocket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket: ```js var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']); ``` On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments: ```js var ws = new WebSocket(request, socket, body, ['irc', 'amqp']); ``` If the client and server agree on a protocol, both the client- and server-side socket objects expose the selected protocol through the `ws.protocol` property. ## Protocol extensions faye-websocket is based on the [websocket-extensions](https://github.com/faye/websocket-extensions-node) framework that allows extensions to be negotiated via the `Sec-WebSocket-Extensions` header. To add extensions to a connection, pass an array of extensions to the `:extensions` option. For example, to add [permessage-deflate](https://github.com/faye/permessage-deflate-node): ```js var deflate = require('permessage-deflate'); var ws = new WebSocket(request, socket, body, [], {extensions: [deflate]}); ``` ## Initialization options Both the server- and client-side classes allow an options object to be passed in at initialization time, for example: ```js var ws = new WebSocket(request, socket, body, protocols, options); var ws = new WebSocket.Client(url, protocols, options); ``` `protocols` is an array of subprotocols as described above, or `null`. `options` is an optional object containing any of these fields: * `extensions` - an array of [websocket-extensions](https://github.com/faye/websocket-extensions-node) compatible extensions, as described above * `headers` - an object containing key-value pairs representing HTTP headers to be sent during the handshake process * `maxLength` - the maximum allowed size of incoming message frames, in bytes. The default value is `2^26 - 1`, or 1 byte short of 64 MiB. * `ping` - an integer that sets how often the WebSocket should send ping frames, measured in seconds The client accepts some additional options: * `proxy` - settings for a proxy as described above * `net` - an object containing settings for the origin server that will be passed to [`net.connect()`](https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener) * `tls` - an object containing TLS settings for the origin server, this will be passed to [`tls.connect()`](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback) * `ca` - (legacy) a shorthand for passing `{tls: {ca: value}}` ## WebSocket API Both server- and client-side `WebSocket` objects support the following API. * <b>`on('open', function(event) {})`</b> fires when the socket connection is established. Event has no attributes. * <b>`on('message', function(event) {})`</b> fires when the socket receives a message. Event has one attribute, <b>`data`</b>, which is either a `String` (for text frames) or a `Buffer` (for binary frames). * <b>`on('error', function(event) {})`</b> fires when there is a protocol error due to bad data sent by the other peer. This event is purely informational, you do not need to implement error recover. * <b>`on('close', function(event) {})`</b> fires when either the client or the server closes the connection. Event has two optional attributes, <b>`code`</b> and <b>`reason`</b>, that expose the status code and message sent by the peer that closed the connection. * <b>`send(message)`</b> accepts either a `String` or a `Buffer` and sends a text or binary message over the connection to the other peer. * <b>`ping(message, function() {})`</b> sends a ping frame with an optional message and fires the callback when a matching pong is received. * <b>`close(code, reason)`</b> closes the connection, sending the given status code and reason text, both of which are optional. * <b>`version`</b> is a string containing the version of the `WebSocket` protocol the connection is using. * <b>`protocol`</b> is a string (which may be empty) identifying the subprotocol the socket is using. ## Handling EventSource connections in Node EventSource connections provide a very similar interface, although because they only allow the server to send data to the client, there is no `onmessage` API. EventSource allows the server to push text messages to the client, where each message has an optional event-type and ID. ```js var WebSocket = require('faye-websocket'), EventSource = WebSocket.EventSource, http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { if (EventSource.isEventSource(request)) { var es = new EventSource(request, response); console.log('open', es.url, es.lastEventId); // Periodically send messages var loop = setInterval(function() { es.send('Hello') }, 1000); es.on('close', function() { clearInterval(loop); es = null; }); } else { // Normal HTTP request response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello'); } }); server.listen(8000); ``` The `send` method takes two optional parameters, `event` and `id`. The default event-type is `'message'` with no ID. For example, to send a `notification` event with ID `99`: ```js es.send('Breaking News!', {event: 'notification', id: '99'}); ``` The `EventSource` object exposes the following properties: * <b>`url`</b> is a string containing the URL the client used to create the EventSource. * <b>`lastEventId`</b> is a string containing the last event ID received by the client. You can use this when the client reconnects after a dropped connection to determine which messages need resending. When you initialize an EventSource with ` new EventSource()`, you can pass configuration options after the `response` parameter. Available options are: * <b>`headers`</b> is an object containing custom headers to be set on the EventSource response. * <b>`retry`</b> is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect. * <b>`ping`</b> is a number that tells the server how often (in seconds) to send 'ping' packets to the client to keep the connection open, to defeat timeouts set by proxies. The client will ignore these messages. For example, this creates a connection that allows access from any origin, pings every 15 seconds and is retryable every 10 seconds if the connection is broken: ```js var es = new EventSource(request, response, { headers: {'Access-Control-Allow-Origin': '*'}, ping: 15, retry: 10 }); ``` You can send a ping message at any time by calling `es.ping()`. Unlike WebSocket, the client does not send a response to this; it is merely to send some data over the wire to keep the connection alive. ## License (The MIT License) Copyright (c) 2010-2017 James Coglan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i define-property --save ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## Related projects * [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object) * [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._ # move-concurrently Move files and directories. ``` const move = require('move-concurrently') move('/path/to/thing', '/new/path/thing').then(() => { // thing is now moved! }).catch(err => { // oh no! }) ``` Uses `rename` to move things as fast as possible. If you `move` across devices or on filesystems that don't support renaming large directories. That is, situations that result in `rename` returning the `EXDEV` error, then `move` will fallback to copy + delete. When recursively copying directories it will first try to rename the contents before falling back to copying. While this will be slightly slower in true cross-device scenarios, it is MUCH faster in cases where the filesystem can't handle directory renames. When copying ownership is maintained when running as root. Permissions are always maintained. On Windows, if symlinks are unavailable then junctions will be used. ## INTERFACE ### move(from, to, options) → Promise Recursively moves `from` to `to` and resolves its promise when finished. If `to` already exists then the promise will be rejected with an `EEXIST` error. Starts by trying to rename `from` to `to`. Options are: * maxConcurrency – (Default: `1`) The maximum number of concurrent copies to do at once. * isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory fails then we'll try making a junction instead. Options can also include dependency injection: * Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * writeStreamAtomic - (Default: `require('fs-write-stream-atomic')`) The implementation of `writeStreamAtomic` to use. Used to inject a mock. * getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock. # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # braces [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/braces.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/braces) > Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save braces ``` ## Why use braces? Brace patterns are great for matching ranges. Users (and implementors) shouldn't have to think about whether or not they will break their application (or yours) from accidentally defining an aggressive brace pattern. _Braces is the only library that offers a [solution to this problem](#performance)_. * **Safe(r)**: Braces isn't vulnerable to DoS attacks like [brace-expansion](https://github.com/juliangruber/brace-expansion), [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) (a different bug than the [other regex DoS bug](https://medium.com/node-security/minimatch-redos-vulnerability-590da24e6d3c#.jew0b6mpc)). * **Accurate**: complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests) * **[fast and performant](#benchmarks)**: Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity. * **Organized code base**: with parser and compiler that are eas(y|ier) to maintain and update when edge cases crop up. * **Well-tested**: thousands of test assertions. Passes 100% of the [minimatch](https://github.com/isaacs/minimatch) and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests as well (as of the writing of this). ## Usage The main export is a function that takes one or more brace `patterns` and `options`. ```js var braces = require('braces'); braces(pattern[, options]); ``` By default, braces returns an optimized regex-source string. To get an array of brace patterns, use `brace.expand()`. The following section explains the difference in more detail. _(If you're curious about "why" braces does this by default, see [brace matching pitfalls](#brace-matching-pitfalls)_. ### Optimized vs. expanded braces **Optimized** By default, patterns are optimized for regex and matching: ```js console.log(braces('a/{x,y,z}/b')); //=> ['a/(x|y|z)/b'] ``` **Expanded** To expand patterns the same way as Bash or [minimatch](https://github.com/isaacs/minimatch), use the [.expand](#expand) method: ```js console.log(braces.expand('a/{x,y,z}/b')); //=> ['a/x/b', 'a/y/b', 'a/z/b'] ``` Or use [options.expand](#optionsexpand): ```js console.log(braces('a/{x,y,z}/b', {expand: true})); //=> ['a/x/b', 'a/y/b', 'a/z/b'] ``` ## Features * [lists](#lists): Supports "lists": `a/{b,c}/d` => `['a/b/d', 'a/c/d']` * [sequences](#sequences): Supports alphabetical or numerical "sequences" (ranges): `{1..3}` => `['1', '2', '3']` * [steps](#steps): Supports "steps" or increments: `{2..10..2}` => `['2', '4', '6', '8', '10']` * [escaping](#escaping) * [options](#options) ### Lists Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric lists: ```js console.log(braces('a/{foo,bar,baz}/*.js')); //=> ['a/(foo|bar|baz)/*.js'] console.log(braces.expand('a/{foo,bar,baz}/*.js')); //=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js'] ``` ### Sequences Uses [fill-range](https://github.com/jonschlinkert/fill-range) for expanding alphabetical or numeric ranges (bash "sequences"): ```js console.log(braces.expand('{1..3}')); // ['1', '2', '3'] console.log(braces.expand('a{01..03}b')); // ['a01b', 'a02b', 'a03b'] console.log(braces.expand('a{1..3}b')); // ['a1b', 'a2b', 'a3b'] console.log(braces.expand('{a..c}')); // ['a', 'b', 'c'] console.log(braces.expand('foo/{a..c}')); // ['foo/a', 'foo/b', 'foo/c'] // supports padded ranges console.log(braces('a{01..03}b')); //=> [ 'a(0[1-3])b' ] console.log(braces('a{001..300}b')); //=> [ 'a(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)b' ] ``` ### Steps Steps, or increments, may be used with ranges: ```js console.log(braces.expand('{2..10..2}')); //=> ['2', '4', '6', '8', '10'] console.log(braces('{2..10..2}')); //=> ['(2|4|6|8|10)'] ``` When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion. ### Nesting Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved. **"Expanded" braces** ```js console.log(braces.expand('a{b,c,/{x,y}}/e')); //=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e'] console.log(braces.expand('a/{x,{1..5},y}/c')); //=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c'] ``` **"Optimized" braces** ```js console.log(braces('a{b,c,/{x,y}}/e')); //=> ['a(b|c|/(x|y))/e'] console.log(braces('a/{x,{1..5},y}/c')); //=> ['a/(x|([1-5])|y)/c'] ``` ### Escaping **Escaping braces** A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_: ```js console.log(braces.expand('a\\{d,c,b}e')); //=> ['a{d,c,b}e'] console.log(braces.expand('a{d,c,b\\}e')); //=> ['a{d,c,b}e'] ``` **Escaping commas** Commas inside braces may also be escaped: ```js console.log(braces.expand('a{b\\,c}d')); //=> ['a{b,c}d'] console.log(braces.expand('a{d\\,c,b}e')); //=> ['ad,ce', 'abe'] ``` **Single items** Following bash conventions, a brace pattern is also not expanded when it contains a single character: ```js console.log(braces.expand('a{b}c')); //=> ['a{b}c'] ``` ## Options ### options.maxLength **Type**: `Number` **Default**: `65,536` **Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera. ```js console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error ``` ### options.expand **Type**: `Boolean` **Default**: `undefined` **Description**: Generate an "expanded" brace pattern (this option is unncessary with the `.expand` method, which does the same thing). ```js console.log(braces('a/{b,c}/d', {expand: true})); //=> [ 'a/b/d', 'a/c/d' ] ``` ### options.optimize **Type**: `Boolean` **Default**: `true` **Description**: Enabled by default. ```js console.log(braces('a/{b,c}/d')); //=> [ 'a/(b|c)/d' ] ``` ### options.nodupes **Type**: `Boolean` **Default**: `true` **Description**: Duplicates are removed by default. To keep duplicates, pass `{nodupes: false}` on the options ### options.rangeLimit **Type**: `Number` **Default**: `250` **Description**: 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. **Examples** ```js // pattern exceeds the "rangeLimit", so it's optimized automatically console.log(braces.expand('{1..1000}')); //=> ['([1-9]|[1-9][0-9]{1,2}|1000)'] // pattern does not exceed "rangeLimit", so it's NOT optimized console.log(braces.expand('{1..100}')); //=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100'] ``` ### options.transform **Type**: `Function` **Default**: `undefined` **Description**: Customize range expansion. ```js var range = braces.expand('x{a..e}y', { transform: function(str) { return 'foo' + str; } }); console.log(range); //=> [ 'xfooay', 'xfooby', 'xfoocy', 'xfoody', 'xfooey' ] ``` ### options.quantifiers **Type**: `Boolean` **Default**: `undefined` **Description**: 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. **Examples** ```js var braces = require('braces'); console.log(braces('a/b{1,3}/{x,y,z}')); //=> [ 'a/b(1|3)/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true})); //=> [ 'a/b{1,3}/(x|y|z)' ] console.log(braces('a/b{1,3}/{x,y,z}', {quantifiers: true, expand: true})); //=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ] ``` ### options.unescape **Type**: `Boolean` **Default**: `undefined` **Description**: Strip backslashes that were used for escaping from the result. ## What is "brace expansion"? Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs). In addition to "expansion", braces are also used for matching. In other words: * [brace expansion](#brace-expansion) is for generating new lists * [brace matching](#brace-matching) is for filtering existing lists <details> <summary><strong>More about brace expansion</strong> (click to expand)</summary> There are two main types of brace expansion: 1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}` 2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges". Here are some example brace patterns to illustrate how they work: **Sets** ``` {a,b,c} => a b c {a,b,c}{1,2} => a1 a2 b1 b2 c1 c2 ``` **Sequences** ``` {1..9} => 1 2 3 4 5 6 7 8 9 {4..-4} => 4 3 2 1 0 -1 -2 -3 -4 {1..20..3} => 1 4 7 10 13 16 19 {a..j} => a b c d e f g h i j {j..a} => j i h g f e d c b a {a..z..3} => a d g j m p s v y ``` **Combination** Sets and sequences can be mixed together or used along with any other strings. ``` {a,b,c}{1..3} => a1 a2 a3 b1 b2 b3 c1 c2 c3 foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar ``` The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases. ## Brace matching In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching. For example, the pattern `foo/{1..3}/bar` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar ``` But not: ``` baz/1/qux baz/2/qux baz/3/qux ``` Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` ## Brace matching pitfalls Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of. ### tldr **"brace bombs"** * brace expansion can eat up a huge amount of processing resources * as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially * users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!) For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section. ### The solution Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries. ### Geometric complexity At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`. For example, the following sets demonstrate quadratic (`O(n^2)`) complexity: ``` {1,2}{3,4} => (2X2) => 13 14 23 24 {1,2}{3,4}{5,6} => (2X2X2) => 135 136 145 146 235 236 245 246 ``` But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity: ``` {1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248 249 257 258 259 267 268 269 347 348 349 357 358 359 367 368 369 ``` Now, imagine how this complexity grows given that each element is a n-tuple: ``` {1..100}{1..100} => (100X100) => 10,000 elements (38.4 kB) {1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB) ``` Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control. **More information** Interested in learning more about brace expansion? * [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion) * [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion) * [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product) </details> ## Performance Braces is not only screaming fast, it's also more accurate the other brace expansion libraries. ### Better algorithms Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_. Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently. **The proof is in the numbers** Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively. | **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** | | --- | --- | --- | | `{1..9007199254740991}`<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> | `298 B` (5ms 459μs) | N/A (freezes) | | `{1..1000000000000000}` | `41 B` (1ms 15μs) | N/A (freezes) | | `{1..100000000000000}` | `40 B` (890μs) | N/A (freezes) | | `{1..10000000000000}` | `39 B` (2ms 49μs) | N/A (freezes) | | `{1..1000000000000}` | `38 B` (608μs) | N/A (freezes) | | `{1..100000000000}` | `37 B` (397μs) | N/A (freezes) | | `{1..10000000000}` | `35 B` (983μs) | N/A (freezes) | | `{1..1000000000}` | `34 B` (798μs) | N/A (freezes) | | `{1..100000000}` | `33 B` (733μs) | N/A (freezes) | | `{1..10000000}` | `32 B` (5ms 632μs) | `78.89 MB` (16s 388ms 569μs) | | `{1..1000000}` | `31 B` (1ms 381μs) | `6.89 MB` (1s 496ms 887μs) | | `{1..100000}` | `30 B` (950μs) | `588.89 kB` (146ms 921μs) | | `{1..10000}` | `29 B` (1ms 114μs) | `48.89 kB` (14ms 187μs) | | `{1..1000}` | `28 B` (760μs) | `3.89 kB` (1ms 453μs) | | `{1..100}` | `22 B` (345μs) | `291 B` (196μs) | | `{1..10}` | `10 B` (533μs) | `20 B` (37μs) | | `{1..3}` | `7 B` (190μs) | `5 B` (27μs) | ### Faster algorithms When you need expansion, braces is still much faster. _(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_ | **Pattern** | **braces** | **[minimatch](https://github.com/isaacs/minimatch)** | | --- | --- | --- | | `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) | | `{1..1000000}` | `6.89 MB` (458ms 576μs) | `6.89 MB` (1s 491ms 621μs) | | `{1..100000}` | `588.89 kB` (20ms 728μs) | `588.89 kB` (156ms 919μs) | | `{1..10000}` | `48.89 kB` (2ms 202μs) | `48.89 kB` (13ms 641μs) | | `{1..1000}` | `3.89 kB` (1ms 796μs) | `3.89 kB` (1ms 958μs) | | `{1..100}` | `291 B` (424μs) | `291 B` (211μs) | | `{1..10}` | `20 B` (487μs) | `20 B` (72μs) | | `{1..3}` | `5 B` (166μs) | `5 B` (27μs) | If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm benchmark ``` ### Latest results ```bash Benchmarking: (8 of 8) · combination-nested · combination · escaped · list-basic · list-multiple · no-braces · sequence-basic · sequence-multiple # benchmark/fixtures/combination-nested.js (52 bytes) brace-expansion x 4,756 ops/sec ±1.09% (86 runs sampled) braces x 11,202,303 ops/sec ±1.06% (88 runs sampled) minimatch x 4,816 ops/sec ±0.99% (87 runs sampled) fastest is braces # benchmark/fixtures/combination.js (51 bytes) brace-expansion x 625 ops/sec ±0.87% (87 runs sampled) braces x 11,031,884 ops/sec ±0.72% (90 runs sampled) minimatch x 637 ops/sec ±0.84% (88 runs sampled) fastest is braces # benchmark/fixtures/escaped.js (44 bytes) brace-expansion x 163,325 ops/sec ±1.05% (87 runs sampled) braces x 10,655,071 ops/sec ±1.22% (88 runs sampled) minimatch x 147,495 ops/sec ±0.96% (88 runs sampled) fastest is braces # benchmark/fixtures/list-basic.js (40 bytes) brace-expansion x 99,726 ops/sec ±1.07% (83 runs sampled) braces x 10,596,584 ops/sec ±0.98% (88 runs sampled) minimatch x 100,069 ops/sec ±1.17% (86 runs sampled) fastest is braces # benchmark/fixtures/list-multiple.js (52 bytes) brace-expansion x 34,348 ops/sec ±1.08% (88 runs sampled) braces x 9,264,131 ops/sec ±1.12% (88 runs sampled) minimatch x 34,893 ops/sec ±0.87% (87 runs sampled) fastest is braces # benchmark/fixtures/no-braces.js (48 bytes) brace-expansion x 275,368 ops/sec ±1.18% (89 runs sampled) braces x 9,134,677 ops/sec ±0.95% (88 runs sampled) minimatch x 3,755,954 ops/sec ±1.13% (89 runs sampled) fastest is braces # benchmark/fixtures/sequence-basic.js (41 bytes) brace-expansion x 5,492 ops/sec ±1.35% (87 runs sampled) braces x 8,485,034 ops/sec ±1.28% (89 runs sampled) minimatch x 5,341 ops/sec ±1.17% (87 runs sampled) fastest is braces # benchmark/fixtures/sequence-multiple.js (51 bytes) brace-expansion x 116 ops/sec ±0.77% (77 runs sampled) braces x 9,445,118 ops/sec ±1.32% (84 runs sampled) minimatch x 109 ops/sec ±1.16% (76 runs sampled) fastest is braces ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 188 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | | 1 | [hemanth](https://github.com/hemanth) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 17, 2018._ <hr class="footnotes-sep"> <section class="footnotes"> <ol class="footnotes-list"> <li id="fn1" class="footnote-item">this is the largest safe integer allowed in JavaScript. <a href="#fnref1" class="footnote-backref">↩</a> </li> </ol> </section> # global <!-- [![build status][1]][2] [![browser support][3]][4] --> Require global variables ## Example ```js var global = require("global") var document = require("global/document") var window = require("global/window") ``` ## Installation `npm install global` ## Contributors - Raynos ## MIT Licenced [1]: https://secure.travis-ci.org/Colingo/global.png [2]: http://travis-ci.org/Colingo/global [3]: http://ci.testling.com/Colingo/global.png [4]: http://ci.testling.com/Colingo/global has-unicode =========== Try to guess if your terminal supports unicode ```javascript var hasUnicode = require("has-unicode") if (hasUnicode()) { // the terminal probably has unicode support } ``` ```javascript var hasUnicode = require("has-unicode").tryHarder hasUnicode(function(unicodeSupported) { if (unicodeSupported) { // the terminal probably has unicode support } }) ``` ## Detecting Unicode What we actually detect is UTF-8 support, as that's what Node itself supports. If you have a UTF-16 locale then you won't be detected as unicode capable. ### Windows Since at least Windows 7, `cmd` and `powershell` have been unicode capable, but unfortunately even then it's not guaranteed. In many localizations it still uses legacy code pages and there's no facility short of running programs or linking C++ that will let us detect this. As such, we report any Windows installation as NOT unicode capable, and recommend that you encourage your users to override this via config. ### Unix Like Operating Systems We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient for most POSIX systems. While locale data can be put in `/etc/locale.conf` as well, AFAIK it's always copied into the environment. # to-regex-range [![NPM version](https://img.shields.io/npm/v/to-regex-range.svg?style=flat)](https://www.npmjs.com/package/to-regex-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex-range.svg?style=flat)](https://npmjs.org/package/to-regex-range) [![Linux Build Status](https://img.shields.io/travis/micromatch/to-regex-range.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/to-regex-range) > Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex-range ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add to-regex-range ``` <details> <summary><strong>What does this do?</strong></summary> <br> This libary generates the `source` string to be passed to `new RegExp()` for matching a range of numbers. **Example** ```js var toRegexRange = require('to-regex-range'); var regex = new RegExp(toRegexRange('15', '95')); ``` A string is returned so that you can do whatever you need with it before passing it to `new RegExp()` (like adding `^` or `$` boundaries, defining flags, or combining it another string). <br> </details> <details> <summary><strong>Why use this library?</strong></summary> <br> ### Convenience Creating regular expressions for matching numbers gets deceptively complicated pretty fast. For example, let's say you need a validation regex for matching part of a user-id, postal code, social security number, tax id, etc: * regex for matching `1` => `/1/` (easy enough) * regex for matching `1` through `5` => `/[1-5]/` (not bad...) * regex for matching `1` or `5` => `/(1|5)/` (still easy...) * regex for matching `1` through `50` => `/([1-9]|[1-4][0-9]|50)/` (uh-oh...) * regex for matching `1` through `55` => `/([1-9]|[1-4][0-9]|5[0-5])/` (no prob, I can do this...) * regex for matching `1` through `555` => `/([1-9]|[1-9][0-9]|[1-4][0-9]{2}|5[0-4][0-9]|55[0-5])/` (maybe not...) * regex for matching `0001` through `5555` => `/(0{3}[1-9]|0{2}[1-9][0-9]|0[1-9][0-9]{2}|[1-4][0-9]{3}|5[0-4][0-9]{2}|55[0-4][0-9]|555[0-5])/` (okay, I get the point!) The numbers are contrived, but they're also really basic. In the real world you might need to generate a regex on-the-fly for validation. **Learn more** If you're interested in learning more about [character classes](http://www.regular-expressions.info/charclass.html) and other regex features, I personally have always found [regular-expressions.info](http://www.regular-expressions.info/charclass.html) to be pretty useful. ### Heavily tested As of April 27, 2017, this library runs [2,783,483 test assertions](./test/test.js) against generated regex-ranges to provide brute-force verification that results are indeed correct. Tests run in ~870ms on my MacBook Pro, 2.5 GHz Intel Core i7. ### Highly optimized Generated regular expressions are highly optimized: * duplicate sequences and character classes are reduced using quantifiers * smart enough to use `?` conditionals when number(s) or range(s) can be positive or negative * uses fragment caching to avoid processing the same exact string more than once <br> </details> ## Usage Add this library to your javascript application with the following line of code ```js var toRegexRange = require('to-regex-range'); ``` The main export is a function that takes two integers: the `min` value and `max` value (formatted as strings or numbers). ```js var source = toRegexRange('15', '95'); //=> 1[5-9]|[2-8][0-9]|9[0-5] var re = new RegExp('^' + source + '$'); console.log(re.test('14')); //=> false console.log(re.test('50')); //=> true console.log(re.test('94')); //=> true console.log(re.test('96')); //=> false ``` ## Options ### options.capture **Type**: `boolean` **Deafault**: `undefined` Wrap the returned value in parentheses when there is more than one regex condition. Useful when you're dynamically generating ranges. ```js console.log(toRegexRange('-10', '10')); //=> -[1-9]|-?10|[0-9] console.log(toRegexRange('-10', '10', {capture: true})); //=> (-[1-9]|-?10|[0-9]) ``` ### options.shorthand **Type**: `boolean` **Deafault**: `undefined` Use the regex shorthand for `[0-9]`: ```js console.log(toRegexRange('0', '999999')); //=> [0-9]|[1-9][0-9]{1,5} console.log(toRegexRange('0', '999999', {shorthand: true})); //=> \d|[1-9]\d{1,5} ``` ### options.relaxZeros **Type**: `boolean` **Default**: `true` This option only applies to **negative zero-padded ranges**. By default, when a negative zero-padded range is defined, the number of leading zeros is relaxed using `-0*`. ```js console.log(toRegexRange('-001', '100')); //=> -0*1|0{2}[0-9]|0[1-9][0-9]|100 console.log(toRegexRange('-001', '100', {relaxZeros: false})); //=> -0{2}1|0{2}[0-9]|0[1-9][0-9]|100 ``` <details> <summary><strong>Why are zeros relaxed for negative zero-padded ranges by default?</strong></summary> Consider the following. ```js var regex = toRegexRange('-001', '100'); ``` _Note that `-001` and `100` are both three digits long_. In most zero-padding implementations, only a single leading zero is enough to indicate that zero-padding should be applied. Thus, the leading zeros would be "corrected" on the negative range in the example to `-01`, instead of `-001`, to make total length of each string no greater than the length of the largest number in the range (in other words, `-001` is 4 digits, but `100` is only three digits). If zeros were not relaxed by default, you might expect the resulting regex of the above pattern to match `-001` - given that it's defined that way in the arguments - _but it wouldn't_. It would, however, match `-01`. This gets even more ambiguous with large ranges, like `-01` to `1000000`. Thus, we relax zeros by default to provide a more predictable experience for users. </details> ## Examples | **Range** | **Result** | **Compile time** | | --- | --- | --- | | `toRegexRange('5, 5')` | `5` | _33μs_ | | `toRegexRange('5, 6')` | `5\|6` | _53μs_ | | `toRegexRange('29, 51')` | `29\|[34][0-9]\|5[01]` | _699μs_ | | `toRegexRange('31, 877')` | `3[1-9]\|[4-9][0-9]\|[1-7][0-9]{2}\|8[0-6][0-9]\|87[0-7]` | _711μs_ | | `toRegexRange('111, 555')` | `11[1-9]\|1[2-9][0-9]\|[2-4][0-9]{2}\|5[0-4][0-9]\|55[0-5]` | _62μs_ | | `toRegexRange('-10, 10')` | `-[1-9]\|-?10\|[0-9]` | _74μs_ | | `toRegexRange('-100, -10')` | `-1[0-9]\|-[2-9][0-9]\|-100` | _49μs_ | | `toRegexRange('-100, 100')` | `-[1-9]\|-?[1-9][0-9]\|-?100\|[0-9]` | _45μs_ | | `toRegexRange('001, 100')` | `0{2}[1-9]\|0[1-9][0-9]\|100` | _158μs_ | | `toRegexRange('0010, 1000')` | `0{2}1[0-9]\|0{2}[2-9][0-9]\|0[1-9][0-9]{2}\|1000` | _61μs_ | | `toRegexRange('1, 2')` | `1\|2` | _10μs_ | | `toRegexRange('1, 5')` | `[1-5]` | _24μs_ | | `toRegexRange('1, 10')` | `[1-9]\|10` | _23μs_ | | `toRegexRange('1, 100')` | `[1-9]\|[1-9][0-9]\|100` | _30μs_ | | `toRegexRange('1, 1000')` | `[1-9]\|[1-9][0-9]{1,2}\|1000` | _52μs_ | | `toRegexRange('1, 10000')` | `[1-9]\|[1-9][0-9]{1,3}\|10000` | _47μs_ | | `toRegexRange('1, 100000')` | `[1-9]\|[1-9][0-9]{1,4}\|100000` | _44μs_ | | `toRegexRange('1, 1000000')` | `[1-9]\|[1-9][0-9]{1,5}\|1000000` | _49μs_ | | `toRegexRange('1, 10000000')` | `[1-9]\|[1-9][0-9]{1,6}\|10000000` | _63μs_ | ## Heads up! **Order of arguments** When the `min` is larger than the `max`, values will be flipped to create a valid range: ```js toRegexRange('51', '29'); ``` Is effectively flipped to: ```js toRegexRange('29', '51'); //=> 29|[3-4][0-9]|5[0-1] ``` **Steps / increments** This library does not support steps (increments). A pr to add support would be welcome. ## History ### v2.0.0 - 2017-04-21 **New features** Adds support for zero-padding! ### v1.0.0 **Optimizations** Repeating ranges are now grouped using quantifiers. rocessing time is roughly the same, but the generated regex is much smaller, which should result in faster matching. ## Attribution Inspired by the python library [range-regex](https://github.com/dimka665/range-regex). ## About ### Related projects * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 27, 2017._ ### esutils [![Build Status](https://secure.travis-ci.org/estools/esutils.svg)](http://travis-ci.org/estools/esutils) esutils ([esutils](http://github.com/estools/esutils)) is utility box for ECMAScript language tools. ### API ### ast #### ast.isExpression(node) Returns true if `node` is an Expression as defined in ECMA262 edition 5.1 section [11](https://es5.github.io/#x11). #### ast.isStatement(node) Returns true if `node` is a Statement as defined in ECMA262 edition 5.1 section [12](https://es5.github.io/#x12). #### ast.isIterationStatement(node) Returns true if `node` is an IterationStatement as defined in ECMA262 edition 5.1 section [12.6](https://es5.github.io/#x12.6). #### ast.isSourceElement(node) Returns true if `node` is a SourceElement as defined in ECMA262 edition 5.1 section [14](https://es5.github.io/#x14). #### ast.trailingStatement(node) Returns `Statement?` if `node` has trailing `Statement`. ```js if (cond) consequent; ``` When taking this `IfStatement`, returns `consequent;` statement. #### ast.isProblematicIfStatement(node) Returns true if `node` is a problematic IfStatement. If `node` is a problematic `IfStatement`, `node` cannot be represented as an one on one JavaScript code. ```js { type: 'IfStatement', consequent: { type: 'WithStatement', body: { type: 'IfStatement', consequent: {type: 'EmptyStatement'} } }, alternate: {type: 'EmptyStatement'} } ``` The above node cannot be represented as a JavaScript code, since the top level `else` alternate belongs to an inner `IfStatement`. ### code #### code.isDecimalDigit(code) Return true if provided code is decimal digit. #### code.isHexDigit(code) Return true if provided code is hexadecimal digit. #### code.isOctalDigit(code) Return true if provided code is octal digit. #### code.isWhiteSpace(code) Return true if provided code is white space. White space characters are formally defined in ECMA262. #### code.isLineTerminator(code) Return true if provided code is line terminator. Line terminator characters are formally defined in ECMA262. #### code.isIdentifierStart(code) Return true if provided code can be the first character of ECMA262 Identifier. They are formally defined in ECMA262. #### code.isIdentifierPart(code) Return true if provided code can be the trailing character of ECMA262 Identifier. They are formally defined in ECMA262. ### keyword #### keyword.isKeywordES5(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 sections [7.6.1.1](http://es5.github.io/#x7.6.1.1) and [7.6.1.2](http://es5.github.io/#x7.6.1.2), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isKeywordES6(id, strict) Returns `true` if provided identifier string is a Keyword or Future Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 sections [11.6.2.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-keywords) and [11.6.2.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-future-reserved-words), respectively. If the `strict` flag is truthy, this function additionally checks whether `id` is a Keyword or Future Reserved Word under strict mode. #### keyword.isReservedWordES5(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 5.1. They are formally defined in ECMA262 section [7.6.1](http://es5.github.io/#x7.6.1). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isReservedWordES6(id, strict) Returns `true` if provided identifier string is a Reserved Word in ECMA262 edition 6. They are formally defined in ECMA262 section [11.6.2](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-reserved-words). If the `strict` flag is truthy, this function additionally checks whether `id` is a Reserved Word under strict mode. #### keyword.isRestrictedWord(id) Returns `true` if provided identifier string is one of `eval` or `arguments`. They are restricted in strict mode code throughout ECMA262 edition 5.1 and in ECMA262 edition 6 section [12.1.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers-static-semantics-early-errors). #### keyword.isIdentifierName(id) Return true if provided identifier string is an IdentifierName as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). #### keyword.isIdentifierES5(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 5.1 section [7.6](https://es5.github.io/#x7.6). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. #### keyword.isIdentifierES6(id, strict) Return true if provided identifier string is an Identifier as specified in ECMA262 edition 6 section [12.1](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-identifiers). If the `strict` flag is truthy, this function additionally checks whether `id` is an Identifier under strict mode. ### License Copyright (C) 2013 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # json-parse-better-errors [![npm version](https://img.shields.io/npm/v/json-parse-better-errors.svg)](https://npm.im/json-parse-better-errors) [![license](https://img.shields.io/npm/l/json-parse-better-errors.svg)](https://npm.im/json-parse-better-errors) [![Travis](https://img.shields.io/travis/zkat/json-parse-better-errors.svg)](https://travis-ci.org/zkat/json-parse-better-errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/json-parse-better-errors?svg=true)](https://ci.appveyor.com/project/zkat/json-parse-better-errors) [![Coverage Status](https://coveralls.io/repos/github/zkat/json-parse-better-errors/badge.svg?branch=latest)](https://coveralls.io/github/zkat/json-parse-better-errors?branch=latest) [`json-parse-better-errors`](https://github.com/zkat/json-parse-better-errors) is a Node.js library for getting nicer errors out of `JSON.parse()`, including context and position of the parse errors. ## Install `$ npm install --save json-parse-better-errors` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * [`parse`](#parse) ### Example ```javascript const parseJson = require('json-parse-better-errors') parseJson('"foo"') parseJson('garbage') // more useful error message ``` ### Features * Like JSON.parse, but the errors are better. ### Contributing The npm team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### <a name="parse"></a> `> parse(txt, ?reviver, ?context=20)` Works just like `JSON.parse`, but will include a bit more information when an error happens. # proxy-addr [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Determine address of proxied request ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install proxy-addr ``` ## API <!-- eslint-disable no-unused-vars --> ```js var proxyaddr = require('proxy-addr') ``` ### proxyaddr(req, trust) Return the address of the request, using the given `trust` parameter. The `trust` argument is a function that returns `true` if you trust the address, `false` if you don't. The closest untrusted address is returned. <!-- eslint-disable no-undef --> ```js proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) proxyaddr(req, function (addr, i) { return i < 1 }) ``` The `trust` arugment may also be a single IP address string or an array of trusted addresses, as plain IP addresses, CIDR-formatted strings, or IP/netmask strings. <!-- eslint-disable no-undef --> ```js proxyaddr(req, '127.0.0.1') proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) ``` This module also supports IPv6. Your IPv6 addresses will be normalized automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). <!-- eslint-disable no-undef --> ```js proxyaddr(req, '::1') proxyaddr(req, ['::1/128', 'fe80::/10']) ``` This module will automatically work with IPv4-mapped IPv6 addresses as well to support node.js in IPv6-only mode. This means that you do not have to specify both `::ffff:a00:1` and `10.0.0.1`. As a convenience, this module also takes certain pre-defined names in addition to IP addresses, which expand into IP addresses: <!-- eslint-disable no-undef --> ```js proxyaddr(req, 'loopback') proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) ``` * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and `127.0.0.1`). * `linklocal`: IPv4 and IPv6 link-local addresses (like `fe80::1:1:1:1` and `169.254.0.1`). * `uniquelocal`: IPv4 private addresses and IPv6 unique-local addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). When `trust` is specified as a function, it will be called for each address to determine if it is a trusted address. The function is given two arguments: `addr` and `i`, where `addr` is a string of the address to check and `i` is a number that represents the distance from the socket address. ### proxyaddr.all(req, [trust]) Return all the addresses of the request, optionally stopping at the first untrusted. This array is ordered from closest to furthest (i.e. `arr[0] === req.connection.remoteAddress`). <!-- eslint-disable no-undef --> ```js proxyaddr.all(req) ``` The optional `trust` argument takes the same arguments as `trust` does in `proxyaddr(req, trust)`. <!-- eslint-disable no-undef --> ```js proxyaddr.all(req, 'loopback') ``` ### proxyaddr.compile(val) Compiles argument `val` into a `trust` function. This function takes the same arguments as `trust` does in `proxyaddr(req, trust)` and returns a function suitable for `proxyaddr(req, trust)`. <!-- eslint-disable no-undef, no-unused-vars --> ```js var trust = proxyaddr.compile('loopback') var addr = proxyaddr(req, trust) ``` This function is meant to be optimized for use against every request. It is recommend to compile a trust function up-front for the trusted configuration and pass that to `proxyaddr(req, trust)` for each request. ## Testing ```sh $ npm test ``` ## Benchmarks ```sh $ npm run-script bench ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/proxy-addr.svg [npm-url]: https://npmjs.org/package/proxy-addr [node-version-image]: https://img.shields.io/node/v/proxy-addr.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/proxy-addr/master.svg [travis-url]: https://travis-ci.org/jshttp/proxy-addr [coveralls-image]: https://img.shields.io/coveralls/jshttp/proxy-addr/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master [downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg [downloads-url]: https://npmjs.org/package/proxy-addr This folder contains entry points for [ECMAScript proposals](https://github.com/zloirock/core-js/tree/v3#ecmascript-proposals) with dependencies. This folder contains entry points for features from [WHATWG / W3C](https://github.com/zloirock/core-js/tree/v3#web-standards) with dependencies. # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # parallel-transform [Transform stream](http://nodejs.org/api/stream.html#stream_class_stream_transform_1) for Node.js that allows you to run your transforms in parallel without changing the order of the output. npm install parallel-transform It is easy to use ``` js var transform = require('parallel-transform'); var stream = transform(10, function(data, callback) { // 10 is the parallism level setTimeout(function() { callback(null, data); }, Math.random() * 1000); }); for (var i = 0; i < 10; i++) { stream.write(''+i); } stream.end(); stream.on('data', function(data) { console.log(data); // prints 0,1,2,... }); stream.on('end', function() { console.log('stream has ended'); }); ``` If you run the above example you'll notice that it runs in parallel (does not take ~1 second between each print) and that the order is preserved ## Stream options All transforms are Node 0.10 streams. Per default they are created with the options `{objectMode:true}`. If you want to use your own stream options pass them as the second parameter ``` js var stream = transform(10, {objectMode:false}, function(data, callback) { // data is now a buffer callback(null, data); }); fs.createReadStream('filename').pipe(stream).pipe(process.stdout); ``` ### Unordered Passing the option `{ordered:false}` will output the data as soon as it's processed by a transform, without waiting to respect the order. ## License MIT # node-tar Tar for Node.js. [![NPM](https://nodei.co/npm/tar.png)](https://nodei.co/npm/tar/) ## API See `examples/` for usage examples. ### var tar = require('tar') Returns an object with `.Pack`, `.Extract` and `.Parse` methods. ### tar.Pack([properties]) Returns a through stream. Use [fstream](https://npmjs.org/package/fstream) to write files into the pack stream and you will receive tar archive data from the pack stream. This only works with directories, it does not work with individual files. The optional `properties` object are used to set properties in the tar 'Global Extended Header'. If the `fromBase` property is set to true, the tar will contain files relative to the path passed, and not with the path included. ### tar.Extract([options]) Returns a through stream. Write tar data to the stream and the files in the tarball will be extracted onto the filesystem. `options` can be: ```js { path: '/path/to/extract/tar/into', strip: 0, // how many path segments to strip from the root when extracting } ``` `options` also get passed to the `fstream.Writer` instance that `tar` uses internally. ### tar.Parse() Returns a writable stream. Write tar data to it and it will emit `entry` events for each entry parsed from the tarball. This is used by `tar.Extract`. A light, featureful and explicit option parsing library for node.js. [Why another one? See below](#why). tl;dr: The others I've tried are one of too loosey goosey (not explicit), too big/too many deps, or ill specified. YMMV. Follow <a href="https://twitter.com/intent/user?screen_name=trentmick" target="_blank">@trentmick</a> for updates to node-dashdash. # Install npm install dashdash # Usage ```javascript var dashdash = require('dashdash'); // Specify the options. Minimally `name` (or `names`) and `type` // must be given for each. var options = [ { // `names` or a single `name`. First element is the `opts.KEY`. names: ['help', 'h'], // See "Option specs" below for types. type: 'bool', help: 'Print this help and exit.' } ]; // Shortcut form. As called it infers `process.argv`. See below for // the longer form to use methods like `.help()` on the Parser object. var opts = dashdash.parse({options: options}); console.log("opts:", opts); console.log("args:", opts._args); ``` # Longer Example A more realistic [starter script "foo.js"](./examples/foo.js) is as follows. This also shows using `parser.help()` for formatted option help. ```javascript var dashdash = require('./lib/dashdash'); var options = [ { name: 'version', type: 'bool', help: 'Print tool version and exit.' }, { names: ['help', 'h'], type: 'bool', help: 'Print this help and exit.' }, { names: ['verbose', 'v'], type: 'arrayOfBool', help: 'Verbose output. Use multiple times for more verbose.' }, { names: ['file', 'f'], type: 'string', help: 'File to process', helpArg: 'FILE' } ]; var parser = dashdash.createParser({options: options}); try { var opts = parser.parse(process.argv); } catch (e) { console.error('foo: error: %s', e.message); process.exit(1); } console.log("# opts:", opts); console.log("# args:", opts._args); // Use `parser.help()` for formatted options help. if (opts.help) { var help = parser.help({includeEnv: true}).trimRight(); console.log('usage: node foo.js [OPTIONS]\n' + 'options:\n' + help); process.exit(0); } // ... ``` Some example output from this script (foo.js): ``` $ node foo.js -h # opts: { help: true, _order: [ { name: 'help', value: true, from: 'argv' } ], _args: [] } # args: [] usage: node foo.js [OPTIONS] options: --version Print tool version and exit. -h, --help Print this help and exit. -v, --verbose Verbose output. Use multiple times for more verbose. -f FILE, --file=FILE File to process $ node foo.js -v # opts: { verbose: [ true ], _order: [ { name: 'verbose', value: true, from: 'argv' } ], _args: [] } # args: [] $ node foo.js --version arg1 # opts: { version: true, _order: [ { name: 'version', value: true, from: 'argv' } ], _args: [ 'arg1' ] } # args: [ 'arg1' ] $ node foo.js -f bar.txt # opts: { file: 'bar.txt', _order: [ { name: 'file', value: 'bar.txt', from: 'argv' } ], _args: [] } # args: [] $ node foo.js -vvv --file=blah # opts: { verbose: [ true, true, true ], file: 'blah', _order: [ { name: 'verbose', value: true, from: 'argv' }, { name: 'verbose', value: true, from: 'argv' }, { name: 'verbose', value: true, from: 'argv' }, { name: 'file', value: 'blah', from: 'argv' } ], _args: [] } # args: [] ``` See the ["examples"](examples/) dir for a number of starter examples using some of dashdash's features. # Environment variable integration If you want to allow environment variables to specify options to your tool, dashdash makes this easy. We can change the 'verbose' option in the example above to include an 'env' field: ```javascript { names: ['verbose', 'v'], type: 'arrayOfBool', env: 'FOO_VERBOSE', // <--- add this line help: 'Verbose output. Use multiple times for more verbose.' }, ``` then the **"FOO_VERBOSE" environment variable** can be used to set this option: ```shell $ FOO_VERBOSE=1 node foo.js # opts: { verbose: [ true ], _order: [ { name: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] ``` Boolean options will interpret the empty string as unset, '0' as false and anything else as true. ```shell $ FOO_VERBOSE= node examples/foo.js # not set # opts: { _order: [], _args: [] } # args: [] $ FOO_VERBOSE=0 node examples/foo.js # '0' is false # opts: { verbose: [ false ], _order: [ { key: 'verbose', value: false, from: 'env' } ], _args: [] } # args: [] $ FOO_VERBOSE=1 node examples/foo.js # true # opts: { verbose: [ true ], _order: [ { key: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] $ FOO_VERBOSE=boogabooga node examples/foo.js # true # opts: { verbose: [ true ], _order: [ { key: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] ``` Non-booleans can be used as well. Strings: ```shell $ FOO_FILE=data.txt node examples/foo.js # opts: { file: 'data.txt', _order: [ { key: 'file', value: 'data.txt', from: 'env' } ], _args: [] } # args: [] ``` Numbers: ```shell $ FOO_TIMEOUT=5000 node examples/foo.js # opts: { timeout: 5000, _order: [ { key: 'timeout', value: 5000, from: 'env' } ], _args: [] } # args: [] $ FOO_TIMEOUT=blarg node examples/foo.js foo: error: arg for "FOO_TIMEOUT" is not a positive integer: "blarg" ``` With the `includeEnv: true` config to `parser.help()` the environment variable can also be included in **help output**: usage: node foo.js [OPTIONS] options: --version Print tool version and exit. -h, --help Print this help and exit. -v, --verbose Verbose output. Use multiple times for more verbose. Environment: FOO_VERBOSE=1 -f FILE, --file=FILE File to process # Bash completion Dashdash provides a simple way to create a Bash completion file that you can place in your "bash_completion.d" directory -- sometimes that is "/usr/local/etc/bash_completion.d/"). Features: - Support for short and long opts - Support for knowing which options take arguments - Support for subcommands (e.g. 'git log <TAB>' to show just options for the log subcommand). See [node-cmdln](https://github.com/trentm/node-cmdln#bash-completion) for how to integrate that. - Does the right thing with "--" to stop options. - Custom optarg and arg types for custom completions. Dashdash will return bash completion file content given a parser instance: var parser = dashdash.createParser({options: options}); console.log( parser.bashCompletion({name: 'mycli'}) ); or directly from a `options` array of options specs: var code = dashdash.bashCompletionFromOptions({ name: 'mycli', options: OPTIONS }); Write that content to "/usr/local/etc/bash_completion.d/mycli" and you will have Bash completions for `mycli`. Alternatively you can write it to any file (e.g. "~/.bashrc") and source it. You could add a `--completion` hidden option to your tool that emits the completion content and document for your users to call that to install Bash completions. See [examples/ddcompletion.js](examples/ddcompletion.js) for a complete example, including how one can define bash functions for completion of custom option types. Also see [node-cmdln](https://github.com/trentm/node-cmdln) for how it uses this for Bash completion for full multi-subcommand tools. - TODO: document specExtra - TODO: document includeHidden - TODO: document custom types, `function complete\_FOO` guide, completionType - TODO: document argtypes # Parser config Parser construction (i.e. `dashdash.createParser(CONFIG)`) takes the following fields: - `options` (Array of option specs). Required. See the [Option specs](#option-specs) section below. - `interspersed` (Boolean). Optional. Default is true. If true this allows interspersed arguments and options. I.e.: node ./tool.js -v arg1 arg2 -h # '-h' is after interspersed args Set it to false to have '-h' **not** get parsed as an option in the above example. - `allowUnknown` (Boolean). Optional. Default is false. If false, this causes unknown arguments to throw an error. I.e.: node ./tool.js -v arg1 --afe8asefksjefhas Set it to true to treat the unknown option as a positional argument. **Caveat**: When a shortopt group, such as `-xaz` contains a mix of known and unknown options, the *entire* group is passed through unmolested as a positional argument. Consider if you have a known short option `-a`, and parse the following command line: node ./tool.js -xaz where `-x` and `-z` are unknown. There are multiple ways to interpret this: 1. `-x` takes a value: `{x: 'az'}` 2. `-x` and `-z` are both booleans: `{x:true,a:true,z:true}` Since dashdash does not know what `-x` and `-z` are, it can't know if you'd prefer to receive `{a:true,_args:['-x','-z']}` or `{x:'az'}`, or `{_args:['-xaz']}`. Leaving the positional arg unprocessed is the easiest mistake for the user to recover from. # Option specs Example using all fields (required fields are noted): ```javascript { names: ['file', 'f'], // Required (one of `names` or `name`). type: 'string', // Required. completionType: 'filename', env: 'MYTOOL_FILE', help: 'Config file to load before running "mytool"', helpArg: 'PATH', helpWrap: false, default: path.resolve(process.env.HOME, '.mytoolrc') } ``` Each option spec in the `options` array must/can have the following fields: - `name` (String) or `names` (Array). Required. These give the option name and aliases. The first name (if more than one given) is the key for the parsed `opts` object. - `type` (String). Required. One of: - bool - string - number - integer - positiveInteger - date (epoch seconds, e.g. 1396031701, or ISO 8601 format `YYYY-MM-DD[THH:MM:SS[.sss][Z]]`, e.g. "2014-03-28T18:35:01.489Z") - arrayOfBool - arrayOfString - arrayOfNumber - arrayOfInteger - arrayOfPositiveInteger - arrayOfDate FWIW, these names attempt to match with asserts on [assert-plus](https://github.com/mcavage/node-assert-plus). You can add your own custom option types with `dashdash.addOptionType`. See below. - `completionType` (String). Optional. This is used for [Bash completion](#bash-completion) for an option argument. If not specified, then the value of `type` is used. Any string may be specified, but only the following values have meaning: - `none`: Provide no completions. - `file`: Bash's default completion (i.e. `complete -o default`), which includes filenames. - *Any string FOO for which a `function complete_FOO` Bash function is defined.* This is for custom completions for a given tool. Typically these custom functions are provided in the `specExtra` argument to `dashdash.bashCompletionFromOptions()`. See ["examples/ddcompletion.js"](examples/ddcompletion.js) for an example. - `env` (String or Array of String). Optional. An environment variable name (or names) that can be used as a fallback for this option. For example, given a "foo.js" like this: var options = [{names: ['dry-run', 'n'], env: 'FOO_DRY_RUN'}]; var opts = dashdash.parse({options: options}); Both `node foo.js --dry-run` and `FOO_DRY_RUN=1 node foo.js` would result in `opts.dry_run = true`. An environment variable is only used as a fallback, i.e. it is ignored if the associated option is given in `argv`. - `help` (String). Optional. Used for `parser.help()` output. - `helpArg` (String). Optional. Used in help output as the placeholder for the option argument, e.g. the "PATH" in: ... -f PATH, --file=PATH File to process ... - `helpWrap` (Boolean). Optional, default true. Set this to `false` to have that option's `help` *not* be text wrapped in `<parser>.help()` output. - `default`. Optional. A default value used for this option, if the option isn't specified in argv. - `hidden` (Boolean). Optional, default false. If true, help output will not include this option. See also the `includeHidden` option to `bashCompletionFromOptions()` for [Bash completion](#bash-completion). # Option group headings You can add headings between option specs in the `options` array. To do so, simply add an object with only a `group` property -- the string to print as the heading for the subsequent options in the array. For example: ```javascript var options = [ { group: 'Armament Options' }, { names: [ 'weapon', 'w' ], type: 'string' }, { group: 'General Options' }, { names: [ 'help', 'h' ], type: 'bool' } ]; ... ``` Note: You can use an empty string, `{group: ''}`, to get a blank line in help output between groups of options. # Help config The `parser.help(...)` function is configurable as follows: Options: Armament Options: ^^ -w WEAPON, --weapon=WEAPON Weapon with which to crush. One of: | / sword, spear, maul | / General Options: | / -h, --help Print this help and exit. | / ^^^^ ^ | \ `-- indent `-- helpCol maxCol ---' `-- headingIndent - `indent` (Number or String). Default 4. Set to a number (for that many spaces) or a string for the literal indent. - `headingIndent` (Number or String). Default half length of `indent`. Set to a number (for that many spaces) or a string for the literal indent. This indent applies to group heading lines, between normal option lines. - `nameSort` (String). Default is 'length'. By default the names are sorted to put the short opts first (i.e. '-h, --help' preferred to '--help, -h'). Set to 'none' to not do this sorting. - `maxCol` (Number). Default 80. Note that reflow is just done on whitespace so a long token in the option help can overflow maxCol. - `helpCol` (Number). If not set a reasonable value will be determined between `minHelpCol` and `maxHelpCol`. - `minHelpCol` (Number). Default 20. - `maxHelpCol` (Number). Default 40. - `helpWrap` (Boolean). Default true. Set to `false` to have option `help` strings *not* be textwrapped to the helpCol..maxCol range. - `includeEnv` (Boolean). Default false. If the option has associated environment variables (via the `env` option spec attribute), then append mentioned of those envvars to the help string. - `includeDefault` (Boolean). Default false. If the option has a default value (via the `default` option spec attribute, or a default on the option's type), then a "Default: VALUE" string will be appended to the help string. # Custom option types Dashdash includes a good starter set of option types that it will parse for you. However, you can add your own via: var dashdash = require('dashdash'); dashdash.addOptionType({ name: '...', takesArg: true, helpArg: '...', parseArg: function (option, optstr, arg) { ... }, array: false, // optional arrayFlatten: false, // optional default: ..., // optional completionType: ... // optional }); For example, a simple option type that accepts 'yes', 'y', 'no' or 'n' as a boolean argument would look like: var dashdash = require('dashdash'); function parseYesNo(option, optstr, arg) { var argLower = arg.toLowerCase() if (~['yes', 'y'].indexOf(argLower)) { return true; } else if (~['no', 'n'].indexOf(argLower)) { return false; } else { throw new Error(format( 'arg for "%s" is not "yes" or "no": "%s"', optstr, arg)); } } dashdash.addOptionType({ name: 'yesno' takesArg: true, helpArg: '<yes|no>', parseArg: parseYesNo }); var options = { {names: ['answer', 'a'], type: 'yesno'} }; var opts = dashdash.parse({options: options}); See "examples/custom-option-\*.js" for other examples. See the `addOptionType` block comment in "lib/dashdash.js" for more details. Please let me know [with an issue](https://github.com/trentm/node-dashdash/issues/new) if you write a generally useful one. # Why Why another node.js option parsing lib? - `nopt` really is just for "tools like npm". Implicit opts (e.g. '--no-foo' works for every '--foo'). Can't disable abbreviated opts. Can't do multiple usages of same opt, e.g. '-vvv' (I think). Can't do grouped short opts. - `optimist` has surprise interpretation of options (at least to me). Implicit opts mean ambiguities and poor error handling for fat-fingering. `process.exit` calls makes it hard to use as a libary. - `optparse` Incomplete docs. Is this an attempted clone of Python's `optparse`. Not clear. Some divergence. `parser.on("name", ...)` API is weird. - `argparse` Dep on underscore. No thanks just for option processing. `find lib | wc -l` -> `26`. Overkill. Argparse is a bit different anyway. Not sure I want that. - `posix-getopt` No type validation. Though that isn't a killer. AFAIK can't have a long opt without a short alias. I.e. no `getopt_long` semantics. Also, no whizbang features like generated help output. - ["commander.js"](https://github.com/visionmedia/commander.js): I wrote [a critique](http://trentm.com/2014/01/a-critique-of-commander-for-nodejs.html) a while back. It seems fine, but last I checked had [an outstanding bug](https://github.com/visionmedia/commander.js/pull/121) that would prevent me from using it. # License MIT. See LICENSE.txt. # content-disposition [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Create and parse HTTP `Content-Disposition` header ## Installation ```sh $ npm install content-disposition ``` ## API ```js var contentDisposition = require('content-disposition') ``` ### contentDisposition(filename, options) Create an attachment `Content-Disposition` header value using the given file name, if supplied. The `filename` is optional and if no file name is desired, but you want to specify `options`, set `filename` to `undefined`. ```js res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) ``` **note** HTTP headers are of the ISO-8859-1 character set. If you are writing this header through a means different from `setHeader` in Node.js, you'll want to specify the `'binary'` encoding in Node.js. #### Options `contentDisposition` accepts these properties in the options object. ##### fallback If the `filename` option is outside ISO-8859-1, then the file name is actually stored in a supplemental field for clients that support Unicode file names and a ISO-8859-1 version of the file name is automatically generated. This specifies the ISO-8859-1 file name to override the automatic generation or disables the generation all together, defaults to `true`. - A string will specify the ISO-8859-1 file name to use in place of automatic generation. - `false` will disable including a ISO-8859-1 file name and only include the Unicode version (unless the file name is already ISO-8859-1). - `true` will enable automatic generation if the file name is outside ISO-8859-1. If the `filename` option is ISO-8859-1 and this option is specified and has a different value, then the `filename` option is encoded in the extended field and this set as the fallback field, even though they are both ISO-8859-1. ##### type Specifies the disposition type, defaults to `"attachment"`. This can also be `"inline"`, or any other value (all values except inline are treated like `attachment`, but can convey additional information if both parties agree to it). The type is normalized to lower-case. ### contentDisposition.parse(string) ```js var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); ``` Parse a `Content-Disposition` header string. This automatically handles extended ("Unicode") parameters by decoding them and providing them under the standard parameter name. This will return an object with the following properties (examples are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): - `type`: The disposition type (always lower case). Example: `'attachment'` - `parameters`: An object of the parameters in the disposition (name of parameter always lower case and extended versions replace non-extended versions). Example: `{filename: "€ rates.txt"}` ## Examples ### Send a file for download ```js var contentDisposition = require('content-disposition') var destroy = require('destroy') var http = require('http') var onFinished = require('on-finished') var filePath = '/path/to/public/plans.pdf' http.createServer(function onRequest(req, res) { // set headers res.setHeader('Content-Type', 'application/pdf') res.setHeader('Content-Disposition', contentDisposition(filePath)) // send file var stream = fs.createReadStream(filePath) stream.pipe(res) onFinished(res, function (err) { destroy(stream) }) }) ``` ## Testing ```sh $ npm test ``` ## References - [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] - [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] - [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] - [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] [rfc-2616]: https://tools.ietf.org/html/rfc2616 [rfc-5987]: https://tools.ietf.org/html/rfc5987 [rfc-6266]: https://tools.ietf.org/html/rfc6266 [tc-2231]: http://greenbytes.de/tech/tc2231/ ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat [npm-url]: https://npmjs.org/package/content-disposition [node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat [travis-url]: https://travis-ci.org/jshttp/content-disposition [coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat [coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master [downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat [downloads-url]: https://npmjs.org/package/content-disposition # convert-source-map [![build status](https://secure.travis-ci.org/thlorenz/convert-source-map.svg?branch=master)](http://travis-ci.org/thlorenz/convert-source-map) <a href="https://www.patreon.com/bePatron?u=8663953"><img alt="become a patron" src="https://c5.patreon.com/external/logo/become_a_patron_button.png" height="35px"></a> Converts a source-map from/to different formats and allows adding/changing properties. ```js var convert = require('convert-source-map'); var json = convert .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .toJSON(); var modified = convert .fromComment('//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnVpbGQvZm9vLm1pbi5qcyIsInNvdXJjZXMiOlsic3JjL2Zvby5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=') .setProperty('sources', [ 'SRC/FOO.JS' ]) .toJSON(); console.log(json); console.log(modified); ``` ```json {"version":3,"file":"build/foo.min.js","sources":["src/foo.js"],"names":[],"mappings":"AAAA","sourceRoot":"/"} {"version":3,"file":"build/foo.min.js","sources":["SRC/FOO.JS"],"names":[],"mappings":"AAAA","sourceRoot":"/"} ``` ## API ### fromObject(obj) Returns source map converter from given object. ### fromJSON(json) Returns source map converter from given json string. ### fromBase64(base64) Returns source map converter from given base64 encoded json string. ### fromComment(comment) Returns source map converter from given base64 encoded json string prefixed with `//# sourceMappingURL=...`. ### fromMapFileComment(comment, mapFileDir) Returns source map converter from given `filename` by parsing `//# sourceMappingURL=filename`. `filename` must point to a file that is found inside the `mapFileDir`. Most tools store this file right next to the generated file, i.e. the one containing the source map. ### fromSource(source) Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. ### fromMapFileSource(source, mapFileDir) Finds last sourcemap comment in file and returns source map converter or returns null if no source map comment was found. The sourcemap will be read from the map file found by parsing `# sourceMappingURL=file` comment. For more info see fromMapFileComment. ### toObject() Returns a copy of the underlying source map. ### toJSON([space]) Converts source map to json string. If `space` is given (optional), this will be passed to [JSON.stringify](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify) when the JSON string is generated. ### toBase64() Converts source map to base64 encoded json string. ### toComment([options]) Converts source map to an inline comment that can be appended to the source-file. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. ### addProperty(key, value) Adds given property to the source map. Throws an error if property already exists. ### setProperty(key, value) Sets given property to the source map. If property doesn't exist it is added, otherwise its value is updated. ### getProperty(key) Gets given property of the source map. ### removeComments(src) Returns `src` with all source map comments removed ### removeMapFileComments(src) Returns `src` with all source map comments pointing to map files removed. ### commentRegex Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments. ### mapFileCommentRegex Provides __a fresh__ RegExp each time it is accessed. Can be used to find source map comments pointing to map files. ### generateMapFileComment(file, [options]) Returns a comment that links to an external source map via `file`. By default, the comment is formatted like: `//# sourceMappingURL=...`, which you would normally see in a JS source file. When `options.multiline == true`, the comment is formatted like: `/*# sourceMappingURL=... */`, which you would find in a CSS source file. [![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/thlorenz/convert-source-map/trend.png)](https://bitdeli.com/free "Bitdeli Badge") # minimalistic-crypto-utils [![Build Status](https://secure.travis-ci.org/indutny/minimalistic-crypto-utils.svg)](http://travis-ci.org/indutny/minimalistic-crypto-utils) [![NPM version](https://badge.fury.io/js/minimalistic-crypto-utils.svg)](http://badge.fury.io/js/minimalistic-crypto-utils) Very minimal utils that are required in order to write reasonable JS-only crypto module. ## Usage ```js const utils = require('minimalistic-crypto-utils'); utils.toArray('abcd', 'hex'); utils.encode([ 1, 2, 3, 4 ], 'hex'); utils.toHex([ 1, 2, 3, 4 ]); ``` #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2017. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: http://tools.ietf.org/html/rfc6979 [1]: https://github.com/indutny/bn.js [2]: https://github.com/indutny/hash.js [3]: https://github.com/bitchan/eccrypto [4]: https://github.com/wanderer/secp256k1-node # normalize-path [![NPM version](https://img.shields.io/npm/v/normalize-path.svg?style=flat)](https://www.npmjs.com/package/normalize-path) [![NPM monthly downloads](https://img.shields.io/npm/dm/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![NPM total downloads](https://img.shields.io/npm/dt/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/normalize-path.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/normalize-path) > Normalize file path slashes to be unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes unless disabled. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save normalize-path ``` ## Usage ```js var normalize = require('normalize-path'); normalize('\\foo\\bar\\baz\\'); //=> '/foo/bar/baz' normalize('./foo/bar/baz/'); //=> './foo/bar/baz' ``` Pass `false` as the last argument to **keep** trailing slashes: ```js normalize('./foo/bar/baz/', false); //=> './foo/bar/baz/' normalize('foo\\bar\\baz\\', false); //=> 'foo/bar/baz/' ``` ## About ### Related projects * [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.") * [ends-with](https://www.npmjs.com/package/ends-with): Returns `true` if the given `string` or `array` ends with `suffix` using strict equality for… [more](https://github.com/jonschlinkert/ends-with) | [homepage](https://github.com/jonschlinkert/ends-with "Returns `true` if the given `string` or `array` ends with `suffix` using strict equality for comparisons.") * [is-absolute](https://www.npmjs.com/package/is-absolute): Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute. | [homepage](https://github.com/jonschlinkert/is-absolute "Polyfill for node.js `path.isAbolute`. Returns true if a file path is absolute.") * [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") * [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.") * [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.") * [path-segments](https://www.npmjs.com/package/path-segments): Get n specific segments of a file path, e.g. first 2, last 3, etc. | [homepage](https://github.com/jonschlinkert/path-segments "Get n specific segments of a file path, e.g. first 2, last 3, etc.") * [rewrite-ext](https://www.npmjs.com/package/rewrite-ext): Automatically re-write the destination extension of a filepath based on the source extension. e.g… [more](https://github.com/jonschlinkert/rewrite-ext) | [homepage](https://github.com/jonschlinkert/rewrite-ext "Automatically re-write the destination extension of a filepath based on the source extension. e.g `.coffee` => `.js`. This will only rename the ext, no other path parts are modified.") * [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 31 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [phated](https://github.com/phated) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.3, on March 29, 2017._ # expand-brackets [![NPM version](https://img.shields.io/npm/v/expand-brackets.svg?style=flat)](https://www.npmjs.com/package/expand-brackets) [![NPM monthly downloads](https://img.shields.io/npm/dm/expand-brackets.svg?style=flat)](https://npmjs.org/package/expand-brackets) [![NPM total downloads](https://img.shields.io/npm/dt/expand-brackets.svg?style=flat)](https://npmjs.org/package/expand-brackets) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/expand-brackets.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/expand-brackets) [![Windows Build Status](https://img.shields.io/appveyor/ci/jonschlinkert/expand-brackets.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/jonschlinkert/expand-brackets) > Expand POSIX bracket expressions (character classes) in glob patterns. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save expand-brackets ``` ## Usage ```js var brackets = require('expand-brackets'); brackets(string[, options]); ``` **Params** The main export is a function that takes the following parameters: * `pattern` **{String}**: the pattern to convert * `options` **{Object}**: optionally supply an options object * `returns` **{String}**: returns a string that can be used to create a regex **Example** ```js console.log(brackets('[![:lower:]]')); //=> '[^a-z]' ``` ## API ### [brackets](index.js#L29) Parses the given POSIX character class `pattern` and returns a string that can be used for creating regular expressions for matching. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}** ### [.match](index.js#L54) Takes an array of strings and a POSIX character class pattern, and returns a new array with only the strings that matched the pattern. **Example** ```js var brackets = require('expand-brackets'); console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]')); //=> ['a'] console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+')); //=> ['a', 'ab'] ``` **Params** * `arr` **{Array}**: Array of strings to match * `pattern` **{String}**: POSIX character class pattern(s) * `options` **{Object}** * `returns` **{Array}** ### [.isMatch](index.js#L100) Returns true if the specified `string` matches the given brackets `pattern`. **Example** ```js var brackets = require('expand-brackets'); console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]')); //=> true console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]')); //=> false ``` **Params** * `string` **{String}**: String to match * `pattern` **{String}**: Poxis pattern * `options` **{String}** * `returns` **{Boolean}** ### [.matcher](index.js#L123) Takes a POSIX character class pattern and returns a matcher function. The returned function takes the string to match as its only argument. **Example** ```js var brackets = require('expand-brackets'); var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.A')); //=> true ``` **Params** * `pattern` **{String}**: Poxis pattern * `options` **{String}** * `returns` **{Boolean}** ### [.makeRe](index.js#L145) Create a regular expression from the given `pattern`. **Example** ```js var brackets = require('expand-brackets'); var re = brackets.makeRe('[[:alpha:]]'); console.log(re); //=> /^(?:[a-zA-Z])$/ ``` **Params** * `pattern` **{String}**: The pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}** ### [.create](index.js#L187) Parses the given POSIX character class `pattern` and returns an object with the compiled `output` and optional source `map`. **Example** ```js var brackets = require('expand-brackets'); console.log(brackets('[[:alpha:]]')); // { options: { source: 'string' }, // input: '[[:alpha:]]', // state: {}, // compilers: // { eos: [Function], // noop: [Function], // bos: [Function], // not: [Function], // escape: [Function], // text: [Function], // posix: [Function], // bracket: [Function], // 'bracket.open': [Function], // 'bracket.inner': [Function], // 'bracket.literal': [Function], // 'bracket.close': [Function] }, // output: '[a-zA-Z]', // ast: // { type: 'root', // errors: [], // nodes: [ [Object], [Object], [Object] ] }, // parsingErrors: [] } ``` **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{Object}** ## Options ### options.sourcemap Generate a source map for the given pattern. **Example** ```js var res = brackets('[:alpha:]', {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'brackets' ], // names: [], // mappings: 'AAAA,MAAS', // sourcesContent: [ '[:alpha:]' ] } ``` ### POSIX Character classes The following named POSIX bracket expressions are supported: * `[:alnum:]`: Alphanumeric characters (`a-zA-Z0-9]`) * `[:alpha:]`: Alphabetic characters (`a-zA-Z]`) * `[:blank:]`: Space and tab (`[ t]`) * `[:digit:]`: Digits (`[0-9]`) * `[:lower:]`: Lowercase letters (`[a-z]`) * `[:punct:]`: Punctuation and symbols. (`[!"#$%&'()*+, -./:;<=>?@ [\]^_``{|}~]`) * `[:upper:]`: Uppercase letters (`[A-Z]`) * `[:word:]`: Word characters (letters, numbers and underscores) (`[A-Za-z0-9_]`) * `[:xdigit:]`: Hexadecimal digits (`[A-Fa-f0-9]`) See [posix-character-classes](https://github.com/jonschlinkert/posix-character-classes) for more details. **Not supported** * [equivalence classes](https://www.gnu.org/software/gawk/manual/html_node/Bracket-Expressions.html) are not supported * [POSIX.2 collating symbols](https://www.gnu.org/software/gawk/manual/html_node/Bracket-Expressions.html) are not supported ## Changelog ### v2.0.0 **Breaking changes** * The main export now returns the compiled string, instead of the object returned from the compiler **Added features** * Adds a `.create` method to do what the main function did before v2.0.0 ### v0.2.0 In addition to performance and matching improvements, the v0.2.0 refactor adds complete POSIX character class support, with the exception of equivalence classes and POSIX.2 collating symbols which are not relevant to node.js usage. **Added features** * parser is exposed, so that expand-brackets parsers can be used by upstream parsers (like [micromatch](https://github.com/jonschlinkert/micromatch)) * compiler is exposed, so that expand-brackets compilers can be used by upstream compilers * source maps **source map example** ```js var brackets = require('expand-brackets'); var res = brackets('[:alpha:]'); console.log(res.map); { version: 3, sources: [ 'brackets' ], names: [], mappings: 'AAAA,MAAS', sourcesContent: [ '[:alpha:]' ] } ``` ## About ### Related projects * [braces](https://www.npmjs.com/package/braces): Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/jonschlinkert/extglob) | [homepage](https://github.com/jonschlinkert/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/jonschlinkert/nanomatch) | [homepage](https://github.com/jonschlinkert/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor**<br/> | | --- | --- | | 66 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [es128](https://github.com/es128) | | 1 | [eush77](https://github.com/eush77) | ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/expand-brackets/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on December 12, 2016._ # unicode-match-property-ecmascript [![Build status](https://travis-ci.org/mathiasbynens/unicode-match-property-ecmascript.svg?branch=master)](https://travis-ci.org/mathiasbynens/unicode-match-property-ecmascript) _unicode-match-property-ecmascript_ matches a given Unicode property or [property alias](https://github.com/mathiasbynens/unicode-property-aliases-ecmascript) to its canonical property name without applying [loose matching](https://github.com/mathiasbynens/unicode-loose-match) per the algorithm used for [RegExp Unicode property escapes in ECMAScript](https://github.com/tc39/proposal-regexp-unicode-property-escapes). Consider it a strict alternative to loose matching. ## Installation To use _unicode-match-property-ecmascript_ programmatically, install it as a dependency via [npm](https://www.npmjs.com/): ```bash $ npm install unicode-match-property-ecmascript ``` Then, `require` it: ```js const matchProperty = require('unicode-match-property-ecmascript'); ``` ## API This module exports a single function named `matchProperty`. ### `matchProperty(value)` This function takes a string `value` and attempts to match it to a canonical Unicode property name. If there’s a match, it returns the canonical property name. Otherwise, it throws an exception. ```js // Find the canonical property name: matchProperty('sc') // → 'Script' matchProperty('Script') // → 'Script' matchProperty('script') // Note: incorrect casing. // → throws ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _unicode-match-property-ecmascript_ is available under the [MIT](https://mths.be/mit) license. # promise-inflight One promise for multiple requests in flight to avoid async duplication ## USAGE ```javascript const inflight = require('promise-inflight') // some request that does some stuff function req(key) { // key is any random string. like a url or filename or whatever. return inflight(key, () => { // this is where you'd fetch the url or whatever return Promise.delay(100) }) } // only assigns a single setTimeout // when it dings, all thens get called with the same result. (There's only // one underlying promise.) req('foo').then(…) req('foo').then(…) req('foo').then(…) req('foo').then(…) ``` ## SEE ALSO * [inflight](https://npmjs.com/package/inflight) - For the callback based function on which this is based. ## STILL NEEDS Tests! # CSS Modules: Scope Locals & Extend [![Build Status](https://travis-ci.org/css-modules/postcss-modules-scope.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-scope) Transforms: ```css :local(.continueButton) { color: green; } ``` into: ```css :export { continueButton: __buttons_continueButton_djd347adcxz9; } .__buttons_continueButton_djd347adcxz9 { color: green; } ``` so it doesn't pollute CSS global scope and can be simply used in JS like so: ```js import styles from './buttons.css' elem.innerHTML = `<button class="${styles.continueButton}">Continue</button>` ``` ## Composition Since we're exporting class names, there's no reason to export only one. This can give us some really useful reuse of styles: ```css .globalButtonStyle { background: white; border: 1px solid; border-radius: 0.25rem; } .globalButtonStyle:hover { box-shadow: 0 0 4px -2px; } :local(.continueButton) { compose-with: globalButtonStyle; color: green; } ``` becomes: ``` .globalButtonStyle { background: white; border: 1px solid; border-radius: 0.25rem; } .globalButtonStyle:hover { box-shadow: 0 0 4px -2px; } :local(.continueButton) { compose-with: globalButtonStyle; color: green; } ``` **Note:** you can also use `composes` as a shorthand for `compose-with` ## Local-by-default & reuse across files You're looking for [CSS Modules](https://github.com/css-modules/css-modules). It uses this plugin as well as a few others, and it's amazing. ## Building ``` npm install npm test ``` [![Build Status](https://travis-ci.org/css-modules/postcss-modules-scope.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-scope) * Lines: [![Coverage Status](https://coveralls.io/repos/css-modules/postcss-modules-scope/badge.svg?branch=master)](https://coveralls.io/r/css-modules/postcss-modules-scope?branch=master) * Statements: [![codecov.io](http://codecov.io/github/css-modules/postcss-modules-scope/coverage.svg?branch=master)](http://codecov.io/github/css-modules/postcss-modules-scope?branch=master) ## Development - `npm autotest` will watch `src` and `test` for changes and run the tests, and transpile the ES6 to ES5 on success ## License ISC ## With thanks - Mark Dalgleish - Tobias Koppers - Guy Bedford --- Glen Maddern, 2015. # constants-browserify Node's `constants` module for the browser. [![downloads](https://img.shields.io/npm/dm/constants-browserify.svg)](https://www.npmjs.org/package/constants-browserify) ## Usage To use with browserify cli: ```bash $ browserify -r constants:constants-browserify script.js ``` To use with browserify api: ```js browserify() .require('constants-browserify', { expose: 'constants' }) .add(__dirname + '/script.js') .bundle() // ... ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install constants-browserify ``` ## License Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # resolve-dir [![NPM version](https://img.shields.io/npm/v/resolve-dir.svg?style=flat)](https://www.npmjs.com/package/resolve-dir) [![NPM downloads](https://img.shields.io/npm/dm/resolve-dir.svg?style=flat)](https://npmjs.org/package/resolve-dir) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/resolve-dir.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/resolve-dir) > Resolve a directory that is either local, global or in the user's home directory. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save resolve-dir ``` ## Usage ```js var resolve = require('resolve-dir'); ``` Returns a local directory path unchanged ```js resolve('a') //=> 'a' ``` Resolves the path to user home ```js resolve('~') //=> '/Users/jonschlinkert' resolve('~/foo') //=> '/Users/jonschlinkert/foo' ``` Resolves the path to global npm modules ```js resolve('@') //=> '/usr/local/lib/node_modules' resolve('@/foo') //=> '/usr/local/lib/node_modules/foo' ``` ## About ### Related projects * [expand-tilde](https://www.npmjs.com/package/expand-tilde): Bash-like tilde expansion for node.js. Expands a leading tilde in a file path to the… [more](https://github.com/jonschlinkert/expand-tilde) | [homepage](https://github.com/jonschlinkert/expand-tilde "Bash-like tilde expansion for node.js. Expands a leading tilde in a file path to the user home directory, or `~+` to the cwd.") * [findup-sync](https://www.npmjs.com/package/findup-sync): Find the first file matching a given pattern in the current directory or the nearest… [more](https://github.com/cowboy/node-findup-sync) | [homepage](https://github.com/cowboy/node-findup-sync "Find the first file matching a given pattern in the current directory or the nearest ancestor directory.") * [resolve-modules](https://www.npmjs.com/package/resolve-modules): Resolves local and global npm modules that match specified patterns, and returns a configuration object… [more](https://github.com/jonschlinkert/resolve-modules) | [homepage](https://github.com/jonschlinkert/resolve-modules "Resolves local and global npm modules that match specified patterns, and returns a configuration object for each resolved module.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/resolve-dir/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 18, 2016._ # js-levenshtein [![Build Status](https://travis-ci.org/gustf/js-levenshtein.svg?branch=master)](https://travis-ci.org/gustf/js-levenshtein) A very efficient JS implementation calculating the Levenshtein distance, i.e. the difference between two strings. Based on Wagner-Fischer dynamic programming algorithm, optimized for speed and memory - use a single distance vector instead of a matrix - loop unrolling on the outer loop - remove common prefixes/postfixes from the calculation - minimize the number of comparisons ## Install ``` $ npm install --save js-levenshtein ``` ## Usage ```js const levenshtein = require('js-levenshtein'); levenshtein('kitten', 'sitting'); //=> 3 ``` ## Benchmark ``` $ npm run bench 50 paragraphs, length max=500 min=240 avr=372.5 162 op/s » js-levenshtein 98 op/s » talisman 94 op/s » levenshtein-edit-distance 85 op/s » leven 39 op/s » fast-levenshtein 100 sentences, length max=170 min=6 avr=57.5 3,076 op/s » js-levenshtein 2,024 op/s » talisman 1,817 op/s » levenshtein-edit-distance 1,633 op/s » leven 800 op/s » fast-levenshtein 2000 words, length max=20 min=3 avr=9.5 3,119 op/s » js-levenshtein 2,416 op/s » talisman 2,141 op/s » levenshtein-edit-distance 1,855 op/s » leven 1,260 op/s » fast-levenshtein ``` Benchmarks was performed with node v8.12.0 on a MacBook Pro 15", 2.9 GHz Intel Core i9 ## License MIT © Gustaf Andersson # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![](oh-my-glob.gif) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` This folder contains internal parts of `core-js` like helpers. # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-glob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-glob) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); isGlob('abc/?.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); isGlob('abc/\\?.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ## About ### Related projects * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/node-base/base) | [homepage](https://github.com/node-base/base "base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor**<br/> | | --- | --- | | 40 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [tuvistavie](https://github.com/tuvistavie) | ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-glob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # fs-minipass Filesystem streams based on [minipass](http://npm.im/minipass). 4 classes are exported: - ReadStream - ReadStreamSync - WriteStream - WriteStreamSync When using `ReadStreamSync`, all of the data is made available immediately upon consuming the stream. Nothing is buffered in memory when the stream is constructed. If the stream is piped to a writer, then it will synchronously `read()` and emit data into the writer as fast as the writer can consume it. (That is, it will respect backpressure.) If you call `stream.read()` then it will read the entire file and return the contents. When using `WriteStreamSync`, every write is flushed to the file synchronously. If your writes all come in a single tick, then it'll write it all out in a single tick. It's as synchronous as you are. The async versions work much like their node builtin counterparts, with the exception of introducing significantly less Stream machinery overhead. ## USAGE It's just streams, you pipe them or read() them or write() to them. ```js const fsm = require('fs-minipass') const readStream = new fsm.ReadStream('file.txt') const writeStream = new fsm.WriteStream('output.txt') writeStream.write('some file header or whatever\n') readStream.pipe(writeStream) ``` ## ReadStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `readSize` The size of reads to do, defaults to 16MB - `size` The size of the file, if known. Prevents zero-byte read() call at the end. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the file is done being read. ## WriteStream(path, options) Path string is required, but somewhat irrelevant if an open file descriptor is passed in as an option. Options: - `fd` Pass in a numeric file descriptor, if the file is already open. - `mode` The mode to create the file with. Defaults to `0o666`. - `start` The position in the file to start reading. If not specified, then the file will start writing at position zero, and be truncated by default. - `autoClose` Set to `false` to prevent the file descriptor from being closed when the stream is ended. - `flags` Flags to use when opening the file. Irrelevant if `fd` is passed in, since file won't be opened in that case. Defaults to `'a'` if a `pos` is specified, or `'w'` otherwise. # os-browserify The [os](https://nodejs.org/api/os.html) module from node.js, but for browsers. When you `require('os')` in [browserify](http://github.com/substack/node-browserify), this module will be loaded. # findup-sync [![Build Status](https://travis-ci.org/js-cli/node-findup-sync.svg)](https://travis-ci.org/js-cli/node-findup-sync) [![NPM version](https://badge.fury.io/js/findup-sync.svg)](http://badge.fury.io/js/findup-sync) > Find the first file matching a given pattern in the current directory or the nearest ancestor directory. Matching is done with [micromatch][], please report any matching related issues on that repository. ## Install with [npm](npmjs.org) ```bash npm i findup-sync --save ``` ## Usage ```js var findup = require('findup-sync'); findup(patternOrPatterns [, micromatchOptions]); // Start looking in the CWD. var filepath1 = findup('{a,b}*.txt'); // Start looking somewhere else, and ignore case (probably a good idea). var filepath2 = findup('{a,b}*.txt', {cwd: '/some/path', nocase: true}); ``` * `patterns` **{String|Array}**: Glob pattern(s) or file path(s) to match against. * `options` **{Object}**: Options to pass to [micromatch]. Note that if you want to start in a different directory than the current working directory, specify a `cwd` property here. * `returns` **{String}**: Returns the first matching file. ## Running tests Install dev dependencies: ```bash npm i -d && npm test ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/) For bugs and feature requests, [please create an issue](https://github.com/cowboy/node-findup-sync/issues). ## Release History 2017-08-07 - v2.0.0 - Drop node 0.8 support, Bump all dependencies (including some Majors) 2017-04-18 - v1.0.0 - Major bump from stable 0.4.3 2015-01-30 - v0.4.0 - Refactored, not also uses [micromatch][] instead of minimatch. 2015-09-14 - v0.3.0 - updated glob to ~5.0. 2014-12-17 - v0.2.1 - Updated to glob 4.3. 2014-12-16 - v0.2.0 - Removed lodash, updated to glob 4.x. 2014-03-14 - v0.1.3 - Updated dependencies. 2013-03-08 - v0.1.2 - Updated dependencies. Fixed a Node 0.9.x bug. Updated unit tests to work cross-platform. 2012-11-15 - v0.1.1 - Now works without an options object. 2012-11-01 - v0.1.0 - Initial release. ## Authors **"Cowboy" Ben Alman** + [github/cowboy](https://github.com/cowboy) + [twitter/cowboy](http://twitter.com/cowboy) ## License Copyright (c) 2012-2016 "Cowboy" Ben Alman Released under the MIT license [micromatch]: http://github.com/jonschlinkert/micromatch # pascalcase [![NPM version](https://badge.fury.io/js/pascalcase.svg)](http://badge.fury.io/js/pascalcase) > Convert a string to pascal-case. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i pascalcase --save ``` ## Usage ```js var pascalcase = require('pascalcase'); pascalcase('a'); //=> 'A' pascalcase('foo bar baz'); //=> 'FooBarBaz' pascalcase('foo_bar-baz'); //=> 'FooBarBaz' pascalcase('foo.bar.baz'); //=> 'FooBarBaz' pascalcase('foo/bar/baz'); //=> 'FooBarBaz' pascalcase('foo[bar)baz'); //=> 'FooBarBaz' pascalcase('#foo+bar*baz'); //=> 'FooBarBaz' pascalcase('$foo~bar`baz'); //=> 'FooBarBaz' pascalcase('_foo_bar-baz-'); //=> 'FooBarBaz' ``` ## Related projects * [justified](https://github.com/jonschlinkert/justified): Wrap words to a specified length and justified the text. * [pad-left](https://github.com/jonschlinkert/pad-left): Left pad a string with zeros or a specified string. Fastest implementation. * [pad-right](https://github.com/jonschlinkert/pad-right): Right pad a string with zeros or a specified string. Fastest implementation. * [repeat-string](https://github.com/jonschlinkert/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. * [word-wrap](https://github.com/jonschlinkert/word-wrap): Wrap words to a specified length. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/pascalcase/issues/new) ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 19, 2015._ # readable-stream ***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) ```bash npm install --save readable-stream ``` ***Node-core streams for userland*** This package is a mirror of the Streams2 and Streams3 implementations in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;[email protected]&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;[email protected]&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;[email protected]&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; # assert-plus This library is a super small wrapper over node's assert module that has two things: (1) the ability to disable assertions with the environment variable NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like `assert.string(myArg, 'myArg')`. As a simple example, most of my code looks like this: ```javascript var assert = require('assert-plus'); function fooAccount(options, callback) { assert.object(options, 'options'); assert.number(options.id, 'options.id'); assert.bool(options.isManager, 'options.isManager'); assert.string(options.name, 'options.name'); assert.arrayOfString(options.email, 'options.email'); assert.func(callback, 'callback'); // Do stuff callback(null, {}); } ``` # API All methods that *aren't* part of node's core assert API are simply assumed to take an argument, and then a string 'name' that's not a message; `AssertionError` will be thrown if the assertion fails with a message like: AssertionError: foo (string) is required at test (/home/mark/work/foo/foo.js:3:9) at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1) at Module._compile (module.js:446:26) at Object..js (module.js:464:10) at Module.load (module.js:353:31) at Function._load (module.js:311:12) at Array.0 (module.js:484:10) at EventEmitter._tickCallback (node.js:190:38) from: ```javascript function test(foo) { assert.string(foo, 'foo'); } ``` There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`: ```javascript function test(foo) { assert.arrayOfString(foo, 'foo'); } ``` You can assert IFF an argument is not `undefined` (i.e., an optional arg): ```javascript assert.optionalString(foo, 'foo'); ``` Lastly, you can opt-out of assertion checking altogether by setting the environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have lots of assertions, and don't want to pay `typeof ()` taxes to v8 in production. Be advised: The standard functions re-exported from `assert` are also disabled in assert-plus if NDEBUG is specified. Using them directly from the `assert` module avoids this behavior. The complete list of APIs is: * assert.array * assert.bool * assert.buffer * assert.func * assert.number * assert.finite * assert.object * assert.string * assert.stream * assert.date * assert.regexp * assert.uuid * assert.arrayOfArray * assert.arrayOfBool * assert.arrayOfBuffer * assert.arrayOfFunc * assert.arrayOfNumber * assert.arrayOfFinite * assert.arrayOfObject * assert.arrayOfString * assert.arrayOfStream * assert.arrayOfDate * assert.arrayOfRegexp * assert.arrayOfUuid * assert.optionalArray * assert.optionalBool * assert.optionalBuffer * assert.optionalFunc * assert.optionalNumber * assert.optionalFinite * assert.optionalObject * assert.optionalString * assert.optionalStream * assert.optionalDate * assert.optionalRegexp * assert.optionalUuid * assert.optionalArrayOfArray * assert.optionalArrayOfBool * assert.optionalArrayOfBuffer * assert.optionalArrayOfFunc * assert.optionalArrayOfNumber * assert.optionalArrayOfFinite * assert.optionalArrayOfObject * assert.optionalArrayOfString * assert.optionalArrayOfStream * assert.optionalArrayOfDate * assert.optionalArrayOfRegexp * assert.optionalArrayOfUuid * assert.AssertionError * assert.fail * assert.ok * assert.equal * assert.notEqual * assert.deepEqual * assert.notDeepEqual * assert.strictEqual * assert.notStrictEqual * assert.throws * assert.doesNotThrow * assert.ifError # Installation npm install assert-plus ## License The MIT License (MIT) Copyright (c) 2012 Mark Cavage Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## Bugs See <https://github.com/mcavage/node-assert-plus/issues>. ecc-jsbn ======== ECC package based on [jsbn](https://github.com/andyperlitch/jsbn) from [Tom Wu](http://www-cs-students.stanford.edu/~tjw/). This is a subset of the same interface as the [node compiled module](https://github.com/quartzjer/ecc), but works in the browser too. Also uses point compression now from [https://github.com/kaielvin](https://github.com/kaielvin/jsbn-ec-point-compression). # websocket-extensions [![Build status](https://secure.travis-ci.org/faye/websocket-extensions-node.svg)](http://travis-ci.org/faye/websocket-extensions-node) A minimal framework that supports the implementation of WebSocket extensions in a way that's decoupled from the main protocol. This library aims to allow a WebSocket extension to be written and used with any protocol library, by defining abstract representations of frames and messages that allow modules to co-operate. `websocket-extensions` provides a container for registering extension plugins, and provides all the functions required to negotiate which extensions to use during a session via the `Sec-WebSocket-Extensions` header. By implementing the APIs defined in this document, an extension may be used by any WebSocket library based on this framework. ## Installation ``` $ npm install websocket-extensions ``` ## Usage There are two main audiences for this library: authors implementing the WebSocket protocol, and authors implementing extensions. End users of a WebSocket library or an extension should be able to use any extension by passing it as an argument to their chosen protocol library, without needing to know how either of them work, or how the `websocket-extensions` framework operates. The library is designed with the aim that any protocol implementation and any extension can be used together, so long as they support the same abstract representation of frames and messages. ### Data types The APIs provided by the framework rely on two data types; extensions will expect to be given data and to be able to return data in these formats: #### *Frame* *Frame* is a structure representing a single WebSocket frame of any type. Frames are simple objects that must have at least the following properties, which represent the data encoded in the frame: | property | description | | ------------ | ------------------------------------------------------------------ | | `final` | `true` if the `FIN` bit is set, `false` otherwise | | `rsv1` | `true` if the `RSV1` bit is set, `false` otherwise | | `rsv2` | `true` if the `RSV2` bit is set, `false` otherwise | | `rsv3` | `true` if the `RSV3` bit is set, `false` otherwise | | `opcode` | the numeric opcode (`0`, `1`, `2`, `8`, `9`, or `10`) of the frame | | `masked` | `true` if the `MASK` bit is set, `false` otherwise | | `maskingKey` | a 4-byte `Buffer` if `masked` is `true`, otherwise `null` | | `payload` | a `Buffer` containing the (unmasked) application data | #### *Message* A *Message* represents a complete application message, which can be formed from text, binary and continuation frames. It has the following properties: | property | description | | -------- | ----------------------------------------------------------------- | | `rsv1` | `true` if the first frame of the message has the `RSV1` bit set | | `rsv2` | `true` if the first frame of the message has the `RSV2` bit set | | `rsv3` | `true` if the first frame of the message has the `RSV3` bit set | | `opcode` | the numeric opcode (`1` or `2`) of the first frame of the message | | `data` | the concatenation of all the frame payloads in the message | ### For driver authors A driver author is someone implementing the WebSocket protocol proper, and who wishes end users to be able to use WebSocket extensions with their library. At the start of a WebSocket session, on both the client and the server side, they should begin by creating an extension container and adding whichever extensions they want to use. ```js var Extensions = require('websocket-extensions'), deflate = require('permessage-deflate'); var exts = new Extensions(); exts.add(deflate); ``` In the following examples, `exts` refers to this `Extensions` instance. #### Client sessions Clients will use the methods `generateOffer()` and `activate(header)`. As part of the handshake process, the client must send a `Sec-WebSocket-Extensions` header to advertise that it supports the registered extensions. This header should be generated using: ```js request.headers['sec-websocket-extensions'] = exts.generateOffer(); ``` This returns a string, for example `"permessage-deflate; client_max_window_bits"`, that represents all the extensions the client is offering to use, and their parameters. This string may contain multiple offers for the same extension. When the client receives the handshake response from the server, it should pass the incoming `Sec-WebSocket-Extensions` header in to `exts` to activate the extensions the server has accepted: ```js exts.activate(response.headers['sec-websocket-extensions']); ``` If the server has sent any extension responses that the client does not recognize, or are in conflict with one another for use of RSV bits, or that use invalid parameters for the named extensions, then `exts.activate()` will `throw`. In this event, the client driver should fail the connection with closing code `1010`. #### Server sessions Servers will use the method `generateResponse(header)`. A server session needs to generate a `Sec-WebSocket-Extensions` header to send in its handshake response: ```js var clientOffer = request.headers['sec-websocket-extensions'], extResponse = exts.generateResponse(clientOffer); response.headers['sec-websocket-extensions'] = extResponse; ``` Calling `exts.generateResponse(header)` activates those extensions the client has asked to use, if they are registered, asks each extension for a set of response parameters, and returns a string containing the response parameters for all accepted extensions. #### In both directions Both clients and servers will use the methods `validFrameRsv(frame)`, `processIncomingMessage(message)` and `processOutgoingMessage(message)`. The WebSocket protocol requires that frames do not have any of the `RSV` bits set unless there is an extension in use that allows otherwise. When processing an incoming frame, sessions should pass a *Frame* object to: ```js exts.validFrameRsv(frame) ``` If this method returns `false`, the session should fail the WebSocket connection with closing code `1002`. To pass incoming messages through the extension stack, a session should construct a *Message* object according to the above datatype definitions, and call: ```js exts.processIncomingMessage(message, function(error, msg) { // hand the message off to the application }); ``` If any extensions fail to process the message, then the callback will yield an error and the session should fail the WebSocket connection with closing code `1010`. If `error` is `null`, then `msg` should be passed on to the application. To pass outgoing messages through the extension stack, a session should construct a *Message* as before, and call: ```js exts.processOutgoingMessage(message, function(error, msg) { // write message to the transport }); ``` If any extensions fail to process the message, then the callback will yield an error and the session should fail the WebSocket connection with closing code `1010`. If `error` is `null`, then `message` should be converted into frames (with the message's `rsv1`, `rsv2`, `rsv3` and `opcode` set on the first frame) and written to the transport. At the end of the WebSocket session (either when the protocol is explicitly ended or the transport connection disconnects), the driver should call: ```js exts.close(function() {}) ``` The callback is invoked when all extensions have finished processing any messages in the pipeline and it's safe to close the socket. ### For extension authors An extension author is someone implementing an extension that transforms WebSocket messages passing between the client and server. They would like to implement their extension once and have it work with any protocol library. Extension authors will not install `websocket-extensions` or call it directly. Instead, they should implement the following API to allow their extension to plug into the `websocket-extensions` framework. An `Extension` is any object that has the following properties: | property | description | | -------- | ---------------------------------------------------------------------------- | | `name` | a string containing the name of the extension as used in negotiation headers | | `type` | a string, must be `"permessage"` | | `rsv1` | either `true` if the extension uses the RSV1 bit, `false` otherwise | | `rsv2` | either `true` if the extension uses the RSV2 bit, `false` otherwise | | `rsv3` | either `true` if the extension uses the RSV3 bit, `false` otherwise | It must also implement the following methods: ```js ext.createClientSession() ``` This returns a *ClientSession*, whose interface is defined below. ```js ext.createServerSession(offers) ``` This takes an array of offer params and returns a *ServerSession*, whose interface is defined below. For example, if the client handshake contains the offer header: ``` Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; server_max_window_bits=8, \ permessage-deflate; server_max_window_bits=15 ``` then the `permessage-deflate` extension will receive the call: ```js ext.createServerSession([ {server_no_context_takeover: true, server_max_window_bits: 8}, {server_max_window_bits: 15} ]); ``` The extension must decide which set of parameters it wants to accept, if any, and return a *ServerSession* if it wants to accept the parameters and `null` otherwise. #### *ClientSession* A *ClientSession* is the type returned by `ext.createClientSession()`. It must implement the following methods, as well as the *Session* API listed below. ```js clientSession.generateOffer() // e.g. -> [ // {server_no_context_takeover: true, server_max_window_bits: 8}, // {server_max_window_bits: 15} // ] ``` This must return a set of parameters to include in the client's `Sec-WebSocket-Extensions` offer header. If the session wants to offer multiple configurations, it can return an array of sets of parameters as shown above. ```js clientSession.activate(params) // -> true ``` This must take a single set of parameters from the server's handshake response and use them to configure the client session. If the client accepts the given parameters, then this method must return `true`. If it returns any other value, the framework will interpret this as the client rejecting the response, and will `throw`. #### *ServerSession* A *ServerSession* is the type returned by `ext.createServerSession(offers)`. It must implement the following methods, as well as the *Session* API listed below. ```js serverSession.generateResponse() // e.g. -> {server_max_window_bits: 8} ``` This returns the set of parameters the server session wants to send in its `Sec-WebSocket-Extensions` response header. Only one set of parameters is returned to the client per extension. Server sessions that would confict on their use of RSV bits are not activated. #### *Session* The *Session* API must be implemented by both client and server sessions. It contains two methods, `processIncomingMessage(message)` and `processOutgoingMessage(message)`. ```js session.processIncomingMessage(message, function(error, msg) { ... }) ``` The session must implement this method to take an incoming *Message* as defined above, transform it in any way it needs, then return it via the callback. If there is an error processing the message, this method should yield an error as the first argument. ```js session.processOutgoingMessage(message, function(error, msg) { ... }) ``` The session must implement this method to take an outgoing *Message* as defined above, transform it in any way it needs, then return it via the callback. If there is an error processing the message, this method should yield an error as the first argument. Note that both `processIncomingMessage()` and `processOutgoingMessage()` can perform their logic asynchronously, are allowed to process multiple messages concurrently, and are not required to complete working on messages in the same order the messages arrive. `websocket-extensions` will reorder messages as your extension emits them and will make sure every extension is given messages in the order they arrive from the driver. This allows extensions to maintain state that depends on the messages' wire order, for example keeping a DEFLATE compression context between messages. ```js session.close() ``` The framework will call this method when the WebSocket session ends, allowing the session to release any resources it's using. ## Examples * Consumer: [websocket-driver](https://github.com/faye/websocket-driver-node) * Provider: [permessage-deflate](https://github.com/faye/permessage-deflate-node) # browserify-sign [![NPM Package](https://img.shields.io/npm/v/browserify-sign.svg?style=flat-square)](https://www.npmjs.org/package/browserify-sign) [![Build Status](https://img.shields.io/travis/crypto-browserify/browserify-sign.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/browserify-sign) [![Dependency status](https://img.shields.io/david/crypto-browserify/browserify-sign.svg?style=flat-square)](https://david-dm.org/crypto-browserify/browserify-sign#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) A package to duplicate the functionality of node's crypto public key functions, much of this is based on [Fedor Indutny's](https://github.com/indutny) work on [indutny/tls.js](https://github.com/indutny/tls.js). ## LICENSE ISC Overview [![Build Status](https://travis-ci.org/lydell/js-tokens.svg?branch=master)](https://travis-ci.org/lydell/js-tokens) ======== A regex that tokenizes JavaScript. ```js var jsTokens = require("js-tokens").default var jsString = "var foo=opts.foo;\n..." jsString.match(jsTokens) // ["var", " ", "foo", "=", "opts", ".", "foo", ";", "\n", ...] ``` Installation ============ `npm install js-tokens` ```js import jsTokens from "js-tokens" // or: var jsTokens = require("js-tokens").default ``` Usage ===== ### `jsTokens` ### A regex with the `g` flag that matches JavaScript tokens. The regex _always_ matches, even invalid JavaScript and the empty string. The next match is always directly after the previous. ### `var token = matchToToken(match)` ### ```js import {matchToToken} from "js-tokens" // or: var matchToToken = require("js-tokens").matchToToken ``` Takes a `match` returned by `jsTokens.exec(string)`, and returns a `{type: String, value: String}` object. The following types are available: - string - comment - regex - number - name - punctuator - whitespace - invalid Multi-line comments and strings also have a `closed` property indicating if the token was closed or not (see below). Comments and strings both come in several flavors. To distinguish them, check if the token starts with `//`, `/*`, `'`, `"` or `` ` ``. Names are ECMAScript IdentifierNames, that is, including both identifiers and keywords. You may use [is-keyword-js] to tell them apart. Whitespace includes both line terminators and other whitespace. [is-keyword-js]: https://github.com/crissdev/is-keyword-js ECMAScript support ================== The intention is to always support the latest ECMAScript version whose feature set has been finalized. If adding support for a newer version requires changes, a new version with a major verion bump will be released. Currently, ECMAScript 2018 is supported. Invalid code handling ===================== Unterminated strings are still matched as strings. JavaScript strings cannot contain (unescaped) newlines, so unterminated strings simply end at the end of the line. Unterminated template strings can contain unescaped newlines, though, so they go on to the end of input. Unterminated multi-line comments are also still matched as comments. They simply go on to the end of the input. Unterminated regex literals are likely matched as division and whatever is inside the regex. Invalid ASCII characters have their own capturing group. Invalid non-ASCII characters are treated as names, to simplify the matching of names (except unicode spaces which are treated as whitespace). Note: See also the [ES2018](#es2018) section. Regex literals may contain invalid regex syntax. They are still matched as regex literals. They may also contain repeated regex flags, to keep the regex simple. Strings may contain invalid escape sequences. Limitations =========== Tokenizing JavaScript using regexes—in fact, _one single regex_—won’t be perfect. But that’s not the point either. You may compare jsTokens with [esprima] by using `esprima-compare.js`. See `npm run esprima-compare`! [esprima]: http://esprima.org/ ### Template string interpolation ### Template strings are matched as single tokens, from the starting `` ` `` to the ending `` ` ``, including interpolations (whose tokens are not matched individually). Matching template string interpolations requires recursive balancing of `{` and `}`—something that JavaScript regexes cannot do. Only one level of nesting is supported. ### Division and regex literals collision ### Consider this example: ```js var g = 9.82 var number = bar / 2/g var regex = / 2/g ``` A human can easily understand that in the `number` line we’re dealing with division, and in the `regex` line we’re dealing with a regex literal. How come? Because humans can look at the whole code to put the `/` characters in context. A JavaScript regex cannot. It only sees forwards. (Well, ES2018 regexes can also look backwards. See the [ES2018](#es2018) section). When the `jsTokens` regex scans throught the above, it will see the following at the end of both the `number` and `regex` rows: ```js / 2/g ``` It is then impossible to know if that is a regex literal, or part of an expression dealing with division. Here is a similar case: ```js foo /= 2/g foo(/= 2/g) ``` The first line divides the `foo` variable with `2/g`. The second line calls the `foo` function with the regex literal `/= 2/g`. Again, since `jsTokens` only sees forwards, it cannot tell the two cases apart. There are some cases where we _can_ tell division and regex literals apart, though. First off, we have the simple cases where there’s only one slash in the line: ```js var foo = 2/g foo /= 2 ``` Regex literals cannot contain newlines, so the above cases are correctly identified as division. Things are only problematic when there are more than one non-comment slash in a single line. Secondly, not every character is a valid regex flag. ```js var number = bar / 2/e ``` The above example is also correctly identified as division, because `e` is not a valid regex flag. I initially wanted to future-proof by allowing `[a-zA-Z]*` (any letter) as flags, but it is not worth it since it increases the amount of ambigous cases. So only the standard `g`, `m`, `i`, `y` and `u` flags are allowed. This means that the above example will be identified as division as long as you don’t rename the `e` variable to some permutation of `gmiyus` 1 to 6 characters long. Lastly, we can look _forward_ for information. - If the token following what looks like a regex literal is not valid after a regex literal, but is valid in a division expression, then the regex literal is treated as division instead. For example, a flagless regex cannot be followed by a string, number or name, but all of those three can be the denominator of a division. - Generally, if what looks like a regex literal is followed by an operator, the regex literal is treated as division instead. This is because regexes are seldomly used with operators (such as `+`, `*`, `&&` and `==`), but division could likely be part of such an expression. Please consult the regex source and the test cases for precise information on when regex or division is matched (should you need to know). In short, you could sum it up as: If the end of a statement looks like a regex literal (even if it isn’t), it will be treated as one. Otherwise it should work as expected (if you write sane code). ### ES2018 ### ES2018 added some nice regex improvements to the language. - [Unicode property escapes] should allow telling names and invalid non-ASCII characters apart without blowing up the regex size. - [Lookbehind assertions] should allow matching telling division and regex literals apart in more cases. - [Named capture groups] might simplify some things. These things would be nice to do, but are not critical. They probably have to wait until the oldest maintained Node.js LTS release supports those features. [Unicode property escapes]: http://2ality.com/2017/07/regexp-unicode-property-escapes.html [Lookbehind assertions]: http://2ality.com/2017/05/regexp-lookbehind-assertions.html [Named capture groups]: http://2ality.com/2017/05/regexp-named-capture-groups.html License ======= [MIT](LICENSE). [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). # for-own [![NPM version](https://img.shields.io/npm/v/for-own.svg?style=flat)](https://www.npmjs.com/package/for-own) [![NPM monthly downloads](https://img.shields.io/npm/dm/for-own.svg?style=flat)](https://npmjs.org/package/for-own) [![NPM total downloads](https://img.shields.io/npm/dt/for-own.svg?style=flat)](https://npmjs.org/package/for-own) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/for-own.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/for-own) > Iterate over the own enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save for-own ``` ## Usage ```js var forOwn = require('for-own'); var obj = {a: 'foo', b: 'bar', c: 'baz'}; var values = []; var keys = []; forOwn(obj, function (value, key, o) { keys.push(key); values.push(value); }); console.log(keys); //=> ['a', 'b', 'c']; console.log(values); //=> ['foo', 'bar', 'baz']; ``` ## About ### Related projects * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten "Recursively flatten an array or arrays. This is the fastest implementation of array flatten.") * [collection-map](https://www.npmjs.com/package/collection-map): Returns an array of mapped values from an array or object. | [homepage](https://github.com/jonschlinkert/collection-map "Returns an array of mapped values from an array or object.") * [for-in](https://www.npmjs.com/package/for-in): Iterate over the own and inherited enumerable properties of an object, and return an object… [more](https://github.com/jonschlinkert/for-in) | [homepage](https://github.com/jonschlinkert/for-in "Iterate over the own and inherited enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 10 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [javiercejudo](https://github.com/javiercejudo) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 26, 2017._ WebSocket-multiplex SockJS example ================================== This example is a copy of example from [websocket-multiplex](https://github.com/sockjs/websocket-multiplex/) project: * https://github.com/sockjs/websocket-multiplex/ To run this example, first install dependencies: npm install And run a server: node server.js That will spawn an http server at http://127.0.0.1:9999/ which will serve both html (served from the current directory) and also SockJS service (under the [/multiplex](http://127.0.0.1:9999/multiplex) path). With that set up, WebSocket-multiplex is able to push three virtual connections over a single SockJS connection. See the code for details. # node-url [![Build Status](https://travis-ci.org/defunctzombie/node-url.svg?branch=master)](https://travis-ci.org/defunctzombie/node-url) This module has utilities for URL resolution and parsing meant to have feature parity with node.js core [url](http://nodejs.org/api/url.html) module. ```js var url = require('url'); ``` ## api Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL `'http://user:[email protected]:8080/p/a/t/h?query=string#hash'` * `href`: The full URL that was originally parsed. Both the protocol and host are lowercased. Example: `'http://user:[email protected]:8080/p/a/t/h?query=string#hash'` * `protocol`: The request protocol, lowercased. Example: `'http:'` * `host`: The full lowercased host portion of the URL, including port information. Example: `'host.com:8080'` * `auth`: The authentication information portion of a URL. Example: `'user:pass'` * `hostname`: Just the lowercased hostname portion of the host. Example: `'host.com'` * `port`: The port number portion of the host. Example: `'8080'` * `pathname`: The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: `'/p/a/t/h'` * `search`: The 'query string' portion of the URL, including the leading question mark. Example: `'?query=string'` * `path`: Concatenation of `pathname` and `search`. Example: `'/p/a/t/h?query=string'` * `query`: Either the 'params' portion of the query string, or a querystring-parsed object. Example: `'query=string'` or `{'query':'string'}` * `hash`: The 'fragment' portion of the URL including the pound-sign. Example: `'#hash'` The following methods are provided by the URL module: ### url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) Take a URL string, and return an object. Pass `true` as the second argument to also parse the query string using the `querystring` module. Defaults to `false`. Pass `true` as the third argument to treat `//foo/bar` as `{ host: 'foo', pathname: '/bar' }` rather than `{ pathname: '//foo/bar' }`. Defaults to `false`. ### url.format(urlObj) Take a parsed URL object, and return a formatted URL string. * `href` will be ignored. * `protocol` is treated the same with or without the trailing `:` (colon). * The protocols `http`, `https`, `ftp`, `gopher`, `file` will be postfixed with `://` (colon-slash-slash). * All other protocols `mailto`, `xmpp`, `aim`, `sftp`, `foo`, etc will be postfixed with `:` (colon) * `auth` will be used if present. * `hostname` will only be used if `host` is absent. * `port` will only be used if `host` is absent. * `host` will be used in place of `hostname` and `port` * `pathname` is treated the same with or without the leading `/` (slash) * `search` will be used in place of `query` * `query` (object; see `querystring`) will only be used if `search` is absent. * `search` is treated the same with or without the leading `?` (question mark) * `hash` is treated the same with or without the leading `#` (pound sign, anchor) ### url.resolve(from, to) Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag. Examples: url.resolve('/one/two/three', 'four') // '/one/two/four' url.resolve('http://example.com/', '/one') // 'http://example.com/one' url.resolve('http://example.com/one', '/two') // 'http://example.com/two' # pbkdf2 [![NPM Package](https://img.shields.io/npm/v/pbkdf2.svg?style=flat-square)](https://www.npmjs.org/package/pbkdf2) [![Build Status](https://img.shields.io/travis/crypto-browserify/pbkdf2.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/pbkdf2) [![Dependency status](https://img.shields.io/david/crypto-browserify/pbkdf2.svg?style=flat-square)](https://david-dm.org/crypto-browserify/pbkdf2#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) This library provides the functionality of PBKDF2 with the ability to use any supported hashing algorithm returned from `crypto.getHashes()` ## Usage ```js var pbkdf2 = require('pbkdf2') var derivedKey = pbkdf2.pbkdf2Sync('password', 'salt', 1, 32, 'sha512') ... ``` For more information on the API, please see the relevant [Node documentation](https://nodejs.org/api/crypto.html#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback). For high performance, use the `async` variant (`pbkdf2.pbkdf2`), not `pbkdf2.pbkdf2Sync`, this variant has the oppurtunity to use `window.crypto.subtle` when browserified. ## Credits This module is a derivative of [cryptocoinjs/pbkdf2-sha256](https://github.com/cryptocoinjs/pbkdf2-sha256/), so thanks to [JP Richardson](https://github.com/jprichardson/) for laying the ground work. Thank you to [FangDun Cai](https://github.com/fundon) for donating the package name on npm, if you're looking for his previous module it is located at [fundon/pbkdf2](https://github.com/fundon/pbkdf2). randombytes === [![Version](http://img.shields.io/npm/v/randombytes.svg)](https://www.npmjs.org/package/randombytes) [![Build Status](https://travis-ci.org/crypto-browserify/randombytes.svg?branch=master)](https://travis-ci.org/crypto-browserify/randombytes) randombytes from node that works in the browser. In node you just get crypto.randomBytes, but in the browser it uses .crypto/msCrypto.getRandomValues ```js var randomBytes = require('randombytes'); randomBytes(16);//get 16 random bytes randomBytes(16, function (err, resp) { // resp is 16 random bytes }); ``` # buffer-xor [![TRAVIS](https://secure.travis-ci.org/crypto-browserify/buffer-xor.png)](http://travis-ci.org/crypto-browserify/buffer-xor) [![NPM](http://img.shields.io/npm/v/buffer-xor.svg)](https://www.npmjs.org/package/buffer-xor) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) A simple module for bitwise-xor on buffers. ## Examples ``` javascript var xor = require("buffer-xor") var a = new Buffer('00ff0f', 'hex') var b = new Buffer('f0f0', 'hex') console.log(xor(a, b)) // => <Buffer f0 0f> ``` Or for those seeking those few extra cycles, perform the operation in place: ``` javascript var xorInplace = require("buffer-xor/inplace") var a = new Buffer('00ff0f', 'hex') var b = new Buffer('f0f0', 'hex') console.log(xorInplace(a, b)) // => <Buffer f0 0f> // NOTE: xorInplace will return the shorter slice of its parameters // See that a has been mutated console.log(a) // => <Buffer f0 0f 0f> ``` ## License [MIT](LICENSE) # async-each No-bullshit, ultra-simple, 35-lines-of-code async parallel forEach function for JavaScript. We don't need junky 30K async libs. Really. For browsers and node.js. ## Installation * Just include async-each before your scripts. * `npm install async-each` if you’re using node.js. * `bower install async-each` if you’re using [Bower](http://bower.io). ## Usage * `each(array, iterator, callback);` — `Array`, `Function`, `(optional) Function` * `iterator(item, next)` receives current item and a callback that will mark the item as done. `next` callback receives optional `error, transformedItem` arguments. * `callback(error, transformedArray)` optionally receives first error and transformed result `Array`. ```javascript var each = require('async-each'); each(['a.js', 'b.js', 'c.js'], fs.readFile, function(error, contents) { if (error) console.error(error); console.log('Contents for a, b and c:', contents); }); // Alternatively in browser: asyncEach(list, fn, callback); ``` ## License The MIT License (MIT) Copyright (c) 2016 Paul Miller [(paulmillr.com)](http://paulmillr.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) A tiny node.js debugging utility modelled after node core's debugging technique. **Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example _app.js_: ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %s', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example _worker.js_: ```js var debug = require('debug')('worker'); setInterval(function(){ debug('doing some work'); }, 1000); ``` The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` #### Web Inspector Colors Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). Colored output looks something like: ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example _stdout.js_: ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2016 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # regexp-tree [![Build Status](https://travis-ci.org/DmitrySoshnikov/regexp-tree.svg?branch=master)](https://travis-ci.org/DmitrySoshnikov/regexp-tree) [![npm version](https://badge.fury.io/js/regexp-tree.svg)](https://badge.fury.io/js/regexp-tree) [![npm downloads](https://img.shields.io/npm/dt/regexp-tree.svg)](https://www.npmjs.com/package/regexp-tree) Regular expressions processor in JavaScript TL;DR: **RegExp Tree** is a _regular expressions processor_, which includes _parser_, _traversal_, _transformer_, _optimizer_, and _interpreter_ APIs. You can get an overview of the tool in [this article](https://medium.com/@DmitrySoshnikov/regexp-tree-a-regular-expressions-parser-with-a-simple-ast-format-bcd4d5580df6). ### Table of Contents - [Installation](#installation) - [Development](#development) - [Usage as a CLI](#usage-as-a-cli) - [Usage from Node](#usage-from-node) - [Capturing locations](#capturing-locations) - [Using traversal API](#using-traversal-api) - [Using transform API](#using-transform-api) - [Transform plugins](#transform-plugins) - [Using generator API](#using-generator-api) - [Using optimizer API](#using-optimizer-api) - [Optimizer ESLint plugin](#optimizer-eslint-plugin) - [Using compat-transpiler API](#using-compat-transpiler-api) - [Compat-transpiler Babel plugin](#compat-transpiler-babel-plugin) - [RegExp extensions](#regexp-extensions) - [RegExp extensions Babel plugin](#regexp-extensions-babel-plugin) - [Creating RegExp objects](#creating-regexp-objects) - [Executing regexes](#executing-regexes) - [Using interpreter API](#using-interpreter-api) - [Printing NFA/DFA tables](#printing-nfadfa-tables) - [AST nodes specification](#ast-nodes-specification) ### Installation The parser can be installed as an [npm module](https://www.npmjs.com/package/regexp-tree): ``` npm install -g regexp-tree ``` You can also [try it online](https://astexplorer.net/#/gist/4ea2b52f0e546af6fb14f9b2f5671c1c/39b55944da3e5782396ffa1fea3ba68d126cd394) using _AST Explorer_. ### Development 1. Fork https://github.com/DmitrySoshnikov/regexp-tree repo 2. If there is an actual issue from the [issues](https://github.com/DmitrySoshnikov/regexp-tree/issues) list you'd like to work on, feel free to assign it yourself, or comment on it to avoid collisions (open a new issue if needed) 3. Make your changes 4. Make sure `npm test` still passes (add new tests if needed) 5. Submit a PR The _regexp-tree_ parser is implemented as an automatic LR parser using [Syntax](https://www.npmjs.com/package/syntax-cli) tool. The parser module is generated from the [regexp grammar](https://github.com/DmitrySoshnikov/regexp-tree/blob/master/src/parser/regexp.bnf), which is based on the regular expressions grammar used in ECMAScript. For development from the github repository, run `build` command to generate the parser module, and transpile JS code: ``` git clone https://github.com/<your-github-account>/regexp-tree.git cd regexp-tree npm install npm run build ``` > NOTE: JS code transpilation is used to support older versions of Node. For faster development cycle you can use `npm run watch` command, which continuously transpiles JS code. ### Usage as a CLI **Note:** the CLI is exposed as its own [regexp-tree-cli](https://www.npmjs.com/package/regexp-tree-cli) module. Check the options available from CLI: ``` regexp-tree-cli --help ``` ``` Usage: regexp-tree-cli [options] Options: -e, --expression A regular expression to be parsed -l, --loc Whether to capture AST node locations -o, --optimize Applies optimizer on the passed expression -c, --compat Applies compat-transpiler on the passed expression -t, --table Print NFA/DFA transition tables (nfa/dfa/all) ``` To parse a regular expression, pass `-e` option: ``` regexp-tree-cli -e '/a|b/i' ``` Which produces an AST node corresponding to this regular expression: ```js { type: 'RegExp', body: { type: 'Disjunction', left: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, right: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } }, flags: 'i', } ``` > NOTE: the format of a regexp is `/ Body / OptionalFlags`. ### Usage from Node The parser can also be used as a Node module: ```js const regexpTree = require('regexp-tree'); console.log(regexpTree.parse(/a|b/i)); // RegExp AST ``` Note, _regexp-tree_ supports parsing regexes from strings, and also from actual `RegExp` objects (in general -- from any object which can be coerced to a string). If some feature is not implemented yet in an actual JavaScript RegExp, it should be passed as a string: ```js // Pass an actual JS RegExp object. regexpTree.parse(/a|b/i); // Pass a string, since `s` flag may not be supported in older versions. regexpTree.parse('/./s'); ``` Also note, that in string-mode, escaping is done using two slashes `\\` per JavaScript: ```js // As an actual regexp. regexpTree.parse(/\n/); // As a string. regexpTree.parse('/\\n/'); ``` ### Capturing locations For source code transformation tools it might be useful also to capture _locations_ of the AST nodes. From the command line it's controlled via the `-l` option: ``` regexp-tree-cli -e '/ab/' -l ``` This attaches `loc` object to each AST node: ```js { type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97, loc: { start: { line: 1, column: 1, offset: 1, }, end: { line: 1, column: 2, offset: 2, }, } }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98, loc: { start: { line: 1, column: 2, offset: 2, }, end: { line: 1, column: 3, offset: 3, }, } } ], loc: { start: { line: 1, column: 1, offset: 1, }, end: { line: 1, column: 3, offset: 3, }, } }, flags: '', loc: { start: { line: 1, column: 0, offset: 0, }, end: { line: 1, column: 4, offset: 4, }, } } ``` From Node it's controlled via `setOptions` method exposed on the parser: ```js const regexpTree = require('regexp-tree'); const parsed = regexpTree .parser .setOptions({captureLocations: true}) .parse(/a|b/); ``` The `setOptions` method sets global options, which are preserved between calls. It is also possible to provide options per a single `parse` call, which might be more preferred: ```js const regexpTree = require('regexp-tree'); const parsed = regexpTree.parse(/a|b/, { captureLocations: true, }); ``` ### Using traversal API The [traverse](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/traverse) module allows handling needed AST nodes using the _visitor_ pattern. In Node the module is exposed as the `regexpTree.traverse` method. Handlers receive an instance of the [NodePath](https://github.com/DmitrySoshnikov/regexp-tree/blob/master/src/traverse/README.md#nodepath-class) class, which encapsulates `node` itself, its `parent` node, `property`, and `index` (in case the node is part of a collection). Visiting a node follows this algorithm: - call `pre` handler. - recurse into node's children. - call `post` handler. For each node type of interest, you can provide either: - a function (`pre`). - an object with members `pre` and `post`. You can also provide a `*` handler which will be executed on every node. Example: ```js const regexpTree = require('regexp-tree'); // Get AST. const ast = regexpTree.parse('/[a-z]{1,}/'); // Traverse AST nodes. regexpTree.traverse(ast, { // Visit every node before any type-specific handlers. '*': function({node}) { ... }, // Handle "Quantifier" node type. Quantifier({node}) { ... }, // Handle "Char" node type, before and after. Char: { pre({node}) { ... }, post({node}) { ... } } }); // Generate the regexp. const re = regexpTree.generate(ast); console.log(re); // '/[a-z]+/' ``` ### Using transform API > NOTE: you can play with transformation APIs, and write actual transforms for quick tests in AST Explorer. See [this example](http://astexplorer.net/#/gist/d293d22742b42cd1f7ee7b7e5dc6f697/39b0aabc42fb6fb106b9e368341d3300098f08c0). While traverse module provides basic traversal API, which can be used for any purposes of AST handling, _transform_ module focuses mainly on _transformation_ of regular expressions. It accepts a regular expressions in different formats (string, an actual `RegExp` object, or an AST), applies a set of transformations, and retuns an instance of [TransformResult](https://github.com/DmitrySoshnikov/regexp-tree/blob/master/src/transform/README.md#transformresult). Handles receive as a parameter the same [NodePath](https://github.com/DmitrySoshnikov/regexp-tree/blob/master/src/traverse/README.md#nodepath-class) object used in traverse. Example: ```js const regexpTree = require('regexp-tree'); // Handle nodes. const re = regexpTree.transform('/[a-z]{1,}/i', { /** * Handle "Quantifier" node type, * transforming `{1,}` quantifier to `+`. */ Quantifier(path) { const {node} = path; // {1,} -> + if ( node.kind === 'Range' && node.from === 1 && !node.to ) { path.replace({ type: 'Quantifier', kind: '+', greedy: node.greedy, }); } }, }); console.log(re.toString()); // '/[a-z]+/i' console.log(re.toRegExp()); // /[a-z]+/i console.log(re.getAST()); // AST for /[a-z]+/i ``` #### Transform plugins A _transformation plugin_ is a module which exports a _transformation handler_. We have seen [above](#using-transform-api) how we can pass a handler object directly to the `regexpTree.transform` method, here we extract it into a separate module, so it can be implemented and shared independently: Example of a plugin: ```js // file: ./regexp-tree-a-to-b-transform.js /** * This plugin replaces chars 'a' with chars 'b'. */ module.exports = { Char({node}) { if (node.kind === 'simple' && node.value === 'a') { node.value = 'b'; node.symbol = 'b'; node.codePoint = 98; } }, }; ``` Once we have this plugin ready, we can require it, and pass to the `transform` function: ```js const regexpTree = require('regexp-tree'); const plugin = require('./regexp-tree-a-to-b-transform'); const re = regexpTree.transform(/(a|c)a+[a-z]/, plugin); console.log(re.toRegExp()); // /(b|c)b+[b-z]/ ``` > NOTE: we can also pass a _list of plugins_ to the `regexpTree.transform`. In this case the plugins are applied in one pass in order. Another approach is to run several sequential calls to `transform`, setting up a pipeline, when a transformed AST is passed further to another plugin, etc. You can see other examples of transform plugins in the [optimizer/transforms](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/optimizer/transforms) or in the [compat-transpiler/transforms](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/compat-transpiler/transforms) directories. ### Using generator API The [generator](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/generator) module generates regular expressions from corresponding AST nodes. In Node the module is exposed as `regexpTree.generate` method. Example: ```js const regexpTree = require('regexp-tree'); const re = regexpTree.generate({ type: 'RegExp', body: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, flags: 'i', }); console.log(re); // '/a/i' ``` ### Using optimizer API [Optimizer](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/optimizer) transforms your regexp into an _optimized_ version, replacing some sub-expressions with their idiomatic patterns. This might be good for different kinds of minifiers, as well as for regexp machines. > NOTE: the Optimizer is implemented as a set of _regexp-tree_ [plugins](#transform-plugins). Example: ```js const regexpTree = require('regexp-tree'); const originalRe = /[a-zA-Z_0-9][A-Z_\da-z]*\e{1,}/; const optimizedRe = regexpTree .optimize(originalRe) .toRegExp(); console.log(optimizedRe); // /\w+e+/ ``` From CLI the optimizer is available via `--optimize` (`-o`) option: ``` regexp-tree-cli -e '/[a-zA-Z_0-9][A-Z_\da-z]*\e{1,}/' -o ``` Result: ``` Optimized: /\w+e+/ ``` See the [optimizer README](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/optimizer) for more details. #### Optimizer ESLint plugin The [optimizer](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/optimizer) module is also available as an _ESLint plugin_, which can be installed at: [eslint-plugin-optimize-regex](https://www.npmjs.com/package/eslint-plugin-optimize-regex). ### Using compat-transpiler API The [compat-transpiler](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/compat-transpiler) module translates your regexp in new format or in new syntax, into an equivalent regexp in a legacy representation, so it can be used in engines which don't yet implement the new syntax. > NOTE: the compat-transpiler is implemented as a set of _regexp-tree_ [plugins](#transform-plugins). Example, "dotAll" `s` flag: ```js /./s ``` Is translated into: ```js /[\0-\uFFFF]/ ``` Or [named capturing groups](#named-capturing-group): ```js /(?<value>a)\k<value>\1/ ``` Becomes: ```js /(a)\1\1/ ``` To use the API from Node: ```js const regexpTree = require('regexp-tree'); // Using new syntax. const originalRe = '/(?<all>.)\\k<all>/s'; // For legacy engines. const compatTranspiledRe = regexpTree .compatTranspile(originalRe) .toRegExp(); console.log(compatTranspiledRe); // /([\0-\uFFFF])\1/ ``` From CLI the compat-transpiler is available via `--compat` (`-c`) option: ``` regexp-tree-cli -e '/(?<all>.)\k<all>/s' -c ``` Result: ``` Compat: /([\0-\uFFFF])\1/ ``` #### Compat-transpiler Babel plugin The [compat-transpiler](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/compat-transpiler) module is also available as a _Babel plugin_, which can be installed at: [babel-plugin-transform-modern-regexp](https://www.npmjs.com/package/babel-plugin-transform-modern-regexp). Note, the plugin also includes [extended regexp](#regexp-extensions) features. ### RegExp extensions Besides future proposals, like [named capturing group](#named-capturing-group), and other which are being currently standardized, _regexp-tree_ also supports _non-standard_ features. > NOTE: _"non-standard"_ means specifically ECMAScript standard, since in other regexp egnines, e.g. PCRE, Python, etc. these features are standard. One of such featurs is `x` flag, which enables _extended_ mode of regular expressions. In this mode most of whitespaces are ignored, and expressions can use #-comments. Example: ```regex / # A regular expression for date. (?<year>\d{4})- # year part of a date (?<month>\d{2})- # month part of a date (?<day>\d{2}) # day part of a date /x ``` This is normally parsed by the _regexp-tree_ parser, and [compat-transpiler](#using-compat-transpiler-api) has full support for it; it's translated into: ```regex /(\d{4})-(\d{2})-(\d{2})/ ``` #### RegExp extensions Babel plugin The regexp extensions are also available as a _Babel plugin_, which can be installed at: [babel-plugin-transform-modern-regexp](https://www.npmjs.com/package/babel-plugin-transform-modern-regexp). Note, the plugin also includes [compat-transpiler](#using-compat-transpiler-api) features. ### Creating RegExp objects To create an actual `RegExp` JavaScript object, we can use `regexpTree.toRegExp` method: ```js const regexpTree = require('regexp-tree'); const re = regexpTree.toRegExp('/[a-z]/i'); console.log( re.test('a'), // true re.test('Z'), // true ); ``` ### Executing regexes It is also possible to execute regular expressions using `exec` API method, which has support for new syntax, and features, such as [named capturing group](#named-capturing-group), etc: ```js const regexpTree = require('regexp-tree'); const re = `/ # A regular expression for date. (?<year>\\d{4})- # year part of a date (?<month>\\d{2})- # month part of a date (?<day>\\d{2}) # day part of a date /x`; const string = '2017-04-14'; const result = regexpTree.exec(re, string); console.log(result.groups); // {year: '2017', month: '04', day: '14'} ``` ### Using interpreter API > NOTE: you can read more about implementation details of the interpreter in [this series of articles](https://medium.com/@DmitrySoshnikov/building-a-regexp-machine-part-1-regular-grammars-d4986b585d7e). In addition to executing regular expressions using JavaScript built-in RegExp engine, RegExp Tree also implements own [interpreter](https://github.com/DmitrySoshnikov/regexp-tree/tree/master/src/interpreter/finite-automaton) based on classic NFA/DFA finite automaton engine. Currently it aims educational purposes -- to trace the regexp matching process, transitioning in NFA/DFA states. It also allows building state transitioning table, which can be used for custom implementation. In API the module is exposed as `fa` (finite-automaton) object. Example: ```js const {fa} = require('regexp-tree'); const re = /ab|c*/; console.log(fa.test(re, 'ab')); // true console.log(fa.test(re, '')); // true console.log(fa.test(re, 'c')); // true // NFA, and its transition table. const nfa = fa.toNFA(re); console.log(nfa.getTransitionTable()); // DFA, and its transition table. const dfa = fa.toDFA(re); console.log(dfa.getTransitionTable()); ``` For more granular work with NFA and DFA, `fa` module also exposes convenient builders, so you can build NFA fragments directly: ```js const {fa} = require('regexp-tree'); const { alt, char, or, rep, } = fa.builders; // ab|c* const re = or( alt(char('a'), char('b')), rep(char('c')) ); console.log(re.matches('ab')); // true console.log(re.matches('')); // true console.log(re.matches('c')); // true // Build DFA from NFA const {DFA} = fa; const reDFA = new DFA(re); console.log(reDFA.matches('ab')); // true console.log(reDFA.matches('')); // true console.log(reDFA.matches('c')); // true ``` #### Printing NFA/DFA tables The `--table` option allows displaying NFA/DFA transition tables. RegExp Tree also applies _DFA minimization_ (using _N-equivalence_ algorithm), and produces the minimal transition table as its final result. In the example below for the `/a|b|c/` regexp, we first obtain the NFA transition table, which is further converted to the original DFA transition table (down from the 10 non-deterministic states to 4 deterministic states), and eventually minimized to the final DFA table (from 4 to only 2 states). ``` ./bin/regexp-tree-cli -e '/a|b|c/' --table all ``` Result: ``` > - starting ✓ - accepting NFA transition table: ┌─────┬───┬───┬────┬─────────────┐ │ │ a │ b │ c │ ε* │ ├─────┼───┼───┼────┼─────────────┤ │ 1 > │ │ │ │ {1,2,3,7,9} │ ├─────┼───┼───┼────┼─────────────┤ │ 2 │ │ │ │ {2,3,7} │ ├─────┼───┼───┼────┼─────────────┤ │ 3 │ 4 │ │ │ 3 │ ├─────┼───┼───┼────┼─────────────┤ │ 4 │ │ │ │ {4,5,6} │ ├─────┼───┼───┼────┼─────────────┤ │ 5 │ │ │ │ {5,6} │ ├─────┼───┼───┼────┼─────────────┤ │ 6 ✓ │ │ │ │ 6 │ ├─────┼───┼───┼────┼─────────────┤ │ 7 │ │ 8 │ │ 7 │ ├─────┼───┼───┼────┼─────────────┤ │ 8 │ │ │ │ {8,5,6} │ ├─────┼───┼───┼────┼─────────────┤ │ 9 │ │ │ 10 │ 9 │ ├─────┼───┼───┼────┼─────────────┤ │ 10 │ │ │ │ {10,6} │ └─────┴───┴───┴────┴─────────────┘ DFA: Original transition table: ┌─────┬───┬───┬───┐ │ │ a │ b │ c │ ├─────┼───┼───┼───┤ │ 1 > │ 4 │ 3 │ 2 │ ├─────┼───┼───┼───┤ │ 2 ✓ │ │ │ │ ├─────┼───┼───┼───┤ │ 3 ✓ │ │ │ │ ├─────┼───┼───┼───┤ │ 4 ✓ │ │ │ │ └─────┴───┴───┴───┘ DFA: Minimized transition table: ┌─────┬───┬───┬───┐ │ │ a │ b │ c │ ├─────┼───┼───┼───┤ │ 1 > │ 2 │ 2 │ 2 │ ├─────┼───┼───┼───┤ │ 2 ✓ │ │ │ │ └─────┴───┴───┴───┘ ``` ### AST nodes specification Below are the AST node types for different regular expressions patterns: - [Char](#char) - [Simple char](#simple-char) - [Escaped char](#escaped-char) - [Meta char](#meta-char) - [Control char](#control-char) - [Hex char-code](#hex-char-code) - [Decimal char-code](#decimal-char-code) - [Octal char-code](#octal-char-code) - [Unicode](#unicode) - [Character class](#character-class) - [Positive character class](#positive-character-class) - [Negative character class](#negative-character-class) - [Character class ranges](#character-class-ranges) - [Alternative](#alternative) - [Disjunction](#disjunction) - [Groups](#groups) - [Capturing group](#capturing-group) - [Named capturing group](#named-capturing-group) - [Non-capturing group](#non-capturing-group) - [Backreferences](#backreferences) - [Quantifiers](#quantifiers) - [? zero-or-one](#-zero-or-one) - [* zero-or-more](#-zero-or-more) - [+ one-or-more](#-one-or-more) - [Range-based quantifiers](#range-based-quantifiers) - [Exact number of matches](#exact-number-of-matches) - [Open range](#open-range) - [Closed range](#closed-range) - [Non-greedy](#non-greedy) - [Assertions](#assertions) - [^ begin marker](#-begin-marker) - [$ end marker](#-end-marker) - [Boundary assertions](#boundary-assertions) - [Lookahead assertions](#lookahead-assertions) - [Positive lookahead assertion](#positive-lookahead-assertion) - [Negative lookahead assertion](#negative-lookahead-assertion) - [Lookbehind assertions](#lookbehind-assertions) - [Positive lookbehind assertion](#positive-lookbehind-assertion) - [Negative lookbehind assertion](#negative-lookbehind-assertion) #### Char A basic building block, single character. Can be _escaped_, and be of different _kinds_. ##### Simple char Basic _non-escaped_ char in a regexp: ``` z ``` Node: ```js { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 122 } ``` > NOTE: to test this from CLI, the char should be in an actual regexp -- `/z/`. ##### Escaped char ``` \z ``` The same value, `escaped` flag is added: ```js { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 122, escaped: true } ``` Escaping is mostly used with meta symbols: ``` // Syntax error * ``` ``` \* ``` OK, node: ```js { type: 'Char', value: '*', symbol: '*', kind: 'simple', codePoint: 42, escaped: true } ``` ##### Meta char A _meta character_ should not be confused with an [escaped char](#escaped-char). Example: ``` \n ``` Node: ```js { type: 'Char', value: '\\n', symbol: '\n', kind: 'meta', codePoint: 10 } ``` Among other meta character are: `.`, `\f`, `\r`, `\n`, `\t`, `\v`, `\0`, `[\b]` (backspace char), `\s`, `\S`, `\w`, `\W`, `\d`, `\D`. > NOTE: Meta characters representing ranges (like `.`, `\s`, etc.) have `undefined` value for `symbol` and `NaN` for `codePoint`. > NOTE: `\b` and `\B` are parsed as `Assertion` node type, not `Char`. ##### Control char A char preceded with `\c`, e.g. `\cx`, which stands for `CTRL+x`: ``` \cx ``` Node: ```js { type: 'Char', value: '\\cx', symbol: undefined, kind: 'control', codePoint: NaN } ``` ##### HEX char-code A char preceded with `\x`, followed by a HEX-code, e.g. `\x3B` (symbol `;`): ``` \x3B ``` Node: ```js { type: 'Char', value: '\\x3B', symbol: ';', kind: 'hex', codePoint: 59 } ``` ##### Decimal char-code Char-code: ``` \42 ``` Node: ```js { type: 'Char', value: '\\42', symbol: '*', kind: 'decimal', codePoint: 42 } ``` ##### Octal char-code Char-code started with `\0`, followed by an octal number: ``` \073 ``` Node: ```js { type: 'Char', value: '\\073', symbol: ';', kind: 'oct', codePoint: 59 } ``` ##### Unicode Unicode char started with `\u`, followed by a hex number: ``` \u003B ``` Node: ```js { type: 'Char', value: '\\u003B', symbol: ';', kind: 'unicode', codePoint: 59 } ``` When using the `u` flag, unicode chars can also be represented using `\u` followed by a hex number between curly braces: ``` \u{1F680} ``` Node: ```js { type: 'Char', value: '\\u{1F680}', symbol: '🚀', kind: 'unicode', codePoint: 128640 } ``` When using the `u` flag, unicode chars can also be represented using a surrogate pair: ``` \ud83d\ude80 ``` Node: ```js { type: 'Char', value: '\\ud83d\\ude80', symbol: '🚀', kind: 'unicode', codePoint: 128640, isSurrogatePair: true } ``` #### Character class Character classes define a _set_ of characters. A set may include as simple characters, as well as _character ranges_. A class can be _positive_ (any from the characters in the class match), or _negative_ (any _but_ the characters from the class match). ##### Positive character class A positive character class is defined between `[` and `]` brackets: ``` [a*] ``` A node: ```js { type: 'CharacterClass', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: '*', symbol: '*', kind: 'simple', codePoint: 42 } ] } ``` > NOTE: some meta symbols are treated as normal characters in a character class. E.g. `*` is not a repetition quantifier, but a simple char. ##### Negative character class A negative character class is defined between `[^` and `]` brackets: ``` [^ab] ``` An AST node is the same, just `negative` property is added: ```js { type: 'CharacterClass', negative: true, expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } ] } ``` ##### Character class ranges As mentioned, a character class may also contain _ranges_ of symbols: ``` [a-z] ``` A node: ```js { type: 'CharacterClass', expressions: [ { type: 'ClassRange', from: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, to: { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 122 } } ] } ``` > NOTE: it is a _syntax error_ if `to` value is less than `from` value: `/[z-a]/`. The range value can be the same for `from` and `to`, and the special range `-` character is treated as a simple character when it stands in a char position: ``` // from: 'a', to: 'a' [a-a] // from: '-', to: '-' [---] // simple '-' char: [-] // 3 ranges: [a-zA-Z0-9]+ ``` #### Alternative An _alternative_ (or _concatenation_) defines a chain of patterns followed one after another: ``` abc ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 }, { type: 'Char', value: 'c', symbol: 'c', kind: 'simple', codePoint: 99 } ] } ``` Another examples: ``` // 'a' with a quantifier, followed by 'b' a?b // A group followed by a class: (ab)[a-z] ``` #### Disjunction The _disjunction_ defines "OR" operation for regexp patterns. It's a _binary_ operation, having `left`, and `right` nodes. Matches `a` or `b`: ``` a|b ``` A node: ```js { type: 'Disjunction', left: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, right: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } } ``` #### Groups The groups play two roles: they define _grouping precedence_, and allow to _capture_ needed sub-expressions in case of a capturing group. ##### Capturing group _"Capturing"_ means the matched string can be referred later by a user, including in the pattern itself -- by using [backreferences](#backreferences). Char `a`, and `b` are grouped, followed by the `c` char: ``` (ab)c ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Group', capturing: true, number: 1, expression: { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } ] } }, { type: 'Char', value: 'c', symbol: 'c', kind: 'simple', codePoint: 99 } ] } ``` As we can see, it also tracks the number of the group. Another example: ``` // A grouped disjunction of a symbol, and a character class: (5|[a-z]) ``` ##### Named capturing group > NOTE: _Named capturing groups_ are not yet supported by JavaScript RegExp. It is an ECMAScript [proposal](https://tc39.github.io/proposal-regexp-named-groups/) which is at stage 3 at the moment. A capturing group can be given a name using the `(?<name>...)` syntax, for any identifier `name`. For example, a regular expressions for a date: ```js /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u ``` For the group: ```js (?<foo>x) ``` We have the following node (the `name` property with value `foo` is added): ```js { type: 'Group', capturing: true, name: 'foo', number: 1, expression: { type: 'Char', value: 'x', symbol: 'x', kind: 'simple', codePoint: 120 } } ``` ##### Non-capturing group Sometimes we don't need to actually capture the matched string from a group. In this case we can use a _non-capturing_ group: Char `a`, and `b` are grouped, _but not captured_, followed by the `c` char: ``` (?:ab)c ``` The same node, the `capturing` flag is `false`: ```js { type: 'Alternative', expressions: [ { type: 'Group', capturing: false, expression: { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } ] } }, { type: 'Char', value: 'c', symbol: 'c', kind: 'simple', codePoint: 99 } ] } ``` ##### Backreferences A [capturing group](#capturing-group) can be referenced in the pattern using notation of an escaped group number. Matches `abab` string: ``` (ab)\1 ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Group', capturing: true, number: 1, expression: { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } ] } }, { type: 'Backreference', kind: 'number', number: 1, reference: 1, } ] } ``` A [named capturing group](#named-capturing-group) can be accessed using `\k<name>` pattern, and also using a numbered reference. Matches `www`: ```js (?<foo>w)\k<foo>\1 ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Group', capturing: true, name: 'foo', number: 1, expression: { type: 'Char', value: 'w', symbol: 'w', kind: 'simple', codePoint: 119 } }, { type: 'Backreference', kind: 'name', number: 1, reference: 'foo' }, { type: 'Backreference', kind: 'number', number: 1, reference: 1 } ] } ``` #### Quantifiers Quantifiers specify _repetition_ of a regular expression (or of its part). Below are the quantifiers which _wrap_ a parsed expression into a `Repetition` node. The quantifier itself can be of different _kinds_, and has `Quantifier` node type. ##### ? zero-or-one The `?` quantifier is short for `{0,1}`. ``` a? ``` Node: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: '?', greedy: true } } ``` ##### * zero-or-more The `*` quantifier is short for `{0,}`. ``` a* ``` Node: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: '*', greedy: true } } ``` ##### + one-or-more The `+` quantifier is short for `{1,}`. ``` // Same as `aa*`, or `a{1,}` a+ ``` Node: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: '+', greedy: true } } ``` ##### Range-based quantifiers Explicit _range-based_ quantifiers are parsed as follows: ###### Exact number of matches ``` a{3} ``` The type of the quantifier is `Range`, and `from`, and `to` properties have the same value: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: 'Range', from: 3, to: 3, greedy: true } } ``` ###### Open range An open range doesn't have max value (assuming semantic "more", or Infinity value): ``` a{3,} ``` An AST node for such range doesn't contain `to` property: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: 'Range', from: 3, greedy: true } } ``` ###### Closed range A closed range has explicit max value: (which syntactically can be the same as min value): ``` a{3,5} // Same as a{3} a{3,3} ``` An AST node for a closed range: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: 'Range', from: 3, to: 5, greedy: true } } ``` > NOTE: it is a _syntax error_ if the max value is less than min value: `/a{3,2}/` ##### Non-greedy If any quantifier is followed by the `?`, the quantifier becomes _non-greedy_. Example: ``` a+? ``` Node: ```js { type: 'Repetition', expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, quantifier: { type: 'Quantifier', kind: '+', greedy: false } } ``` Other examples: ``` a?? a*? a{1}? a{1,}? a{1,3}? ``` #### Assertions Assertions appear as separate AST nodes, however instread of manipulating on the characters themselves, they _assert_ certain conditions of a matching string. Examples: `^` -- beginning of a string (or a line in multiline mode), `$` -- end of a string, etc. ##### ^ begin marker The `^` assertion checks whether a scanner is at the beginning of a string (or a line in multiline mode). In the example below `^` is not a property of the `a` symbol, but a separate AST node for the assertion. The parsed node is actually an `Alternative` with two nodes: ``` ^a ``` The node: ```js { type: 'Alternative', expressions: [ { type: 'Assertion', kind: '^' }, { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 } ] } ``` Since assertion is a separate node, it may appear anywhere in the matching string. The following regexp is completely valid, and asserts beginning of the string; it'll match an empty string: ``` ^^^^^ ``` ##### $ end marker The `$` assertion is similar to `^`, but asserts the end of a string (or a line in a multiline mode): ``` a$ ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Assertion', kind: '$' } ] } ``` And again, this is a completely valid regexp, and matches an empty string: ``` ^^^^$$$$$ // valid too: $^ ``` ##### Boundary assertions The `\b` assertion check for _word boundary_, i.e. the position between a word and a space. Matches `x` in `x y`, but not in `xy`: ``` x\b ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'x', symbol: 'x', kind: 'simple', codePoint: 120 }, { type: 'Assertion', kind: '\\b' } ] } ``` The `\B` is vice-versa checks for _non-word_ boundary. The following example matches `x` in `xy`, but not in `x y`: ``` x\B ``` A node is the same: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'x', symbol: 'x', kind: 'simple', codePoint: 120 }, { type: 'Assertion', kind: '\\B' } ] } ``` ##### Lookahead assertions These assertions check whether a pattern is _followed_ (or not followed for the negative assertion) by another pattern. ###### Positive lookahead assertion Matches `a` only if it's followed by `b`: ``` a(?=b) ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Assertion', kind: 'Lookahead', assertion: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } } ] } ``` ###### Negative lookahead assertion Matches `a` only if it's _not_ followed by `b`: ``` a(?!b) ``` A node is similar, just `negative` flag is added: ```js { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 }, { type: 'Assertion', kind: 'Lookahead', negative: true, assertion: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 } } ] } ``` ##### Lookbehind assertions > NOTE: _Lookbehind assertions_ are not yet supported by JavaScript RegExp. It is an ECMAScript [proposal](https://tc39.github.io/proposal-regexp-lookbehind/) which is at stage 3 at the moment. These assertions check whether a pattern is _preceded_ (or not preceded for the negative assertion) by another pattern. ###### Positive lookbehind assertion Matches `b` only if it's preceded by `a`: ``` (?<=a)b ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Assertion', kind: 'Lookbehind', assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 } }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 }, ] } ``` ###### Negative lookbehind assertion Matches `b` only if it's _not_ preceded by `a`: ``` (?<!a)b ``` A node: ```js { type: 'Alternative', expressions: [ { type: 'Assertion', kind: 'Lookbehind', negative: true, assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 97 } }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 98 }, ] } ``` # flush-write-stream A write stream constructor that supports a flush function that is called before `finish` is emitted ``` npm install flush-write-stream ``` [![build status](http://img.shields.io/travis/mafintosh/flush-write-stream.svg?style=flat)](http://travis-ci.org/mafintosh/flush-write-stream) ## Usage ``` js var writer = require('flush-write-stream') var ws = writer(write, flush) ws.on('finish', function () { console.log('finished') }) ws.write('hello') ws.write('world') ws.end() function write (data, enc, cb) { // i am your normal ._write method console.log('writing', data.toString()) cb() } function flush (cb) { // i am called before finish is emitted setTimeout(cb, 1000) // wait 1 sec } ``` If you run the above it will produce the following output ``` writing hello writing world (nothing happens for 1 sec) finished ``` ## API #### `var ws = writer([options], write, [flush])` Create a new writable stream. Options are forwarded to the stream constructor. #### `var ws = writer.obj([options], write, [flush])` Same as the above except `objectMode` is set to `true` per default. ## License MIT # define-property [![NPM version](https://img.shields.io/npm/v/define-property.svg?style=flat)](https://www.npmjs.com/package/define-property) [![NPM monthly downloads](https://img.shields.io/npm/dm/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![NPM total downloads](https://img.shields.io/npm/dt/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/define-property.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/define-property) > Define a non-enumerable property on an object. Uses Reflect.defineProperty when available, otherwise Object.defineProperty. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save define-property ``` ## Release history See [the CHANGELOG](changelog.md) for updates. ## Usage **Params** * `object`: The object on which to define the property. * `key`: The name of the property to be defined or modified. * `value`: The value or descriptor of the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); // by default, defined properties are non-enumberable console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **defining setters/getters** Pass the same properties you would if using [Object.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty) or [Reflect.defineProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty). ```js define(obj, 'foo', { set: function() {}, get: function() {} }); ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 28 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | ### Author **Jon Schlinkert** * Connect with me on [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * Follow me on [github/jonschlinkert](https://github.com/jonschlinkert) * Follow me on [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on January 25, 2018._ # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [![Greenkeeper badge][greenkeeper-image]][greenkeeper-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:http://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn [travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn [codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn [david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev [david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg [greenkeeper-image]:https://badges.greenkeeper.io/moxystudio/node-cross-spawn.svg [greenkeeper-url]:https://greenkeeper.io/ A cross platform solution to node's spawn and spawnSync. ## Installation `$ npm install cross-spawn` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix)) - Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367) - Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`) - Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149) - No `options.shell` support on node `<v4.8` All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```js const spawn = require('cross-spawn'); // Spawn NPM asynchronously const child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously const result = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Caveats ### Using `options.shell` as an alternative to `cross-spawn` Starting from node `v4.8`, `spawn` has a `shell` option that allows you run commands from within a shell. This new option solves the [PATHEXT](https://github.com/joyent/node/issues/2318) issue but: - It's not supported in node `<v4.8` - You must manually escape the command and arguments which is very error prone, specially when passing user input - There are a lot of other unresolved issues from the [Why](#why) section that you must take into account If you are using the `shell` option to spawn a command in a cross platform way, consider using `cross-spawn` instead. You have been warned. ### `options.shell` support While `cross-spawn` adds support for `options.shell` in node `<v4.8`, all of its enhancements are disabled. This mimics the Node.js behavior. More specifically, the command and its arguments will not be automatically escaped nor shebang support will be offered. This is by design because if you are using `options.shell` you are probably targeting a specific platform anyway and you don't want things to get into your way. ### Shebangs support While `cross-spawn` handles shebangs on Windows, its support is limited. More specifically, it just supports `#!/usr/bin/env <program>` where `<program>` must not contain any arguments. If you would like to have the shebang support improved, feel free to contribute via a pull-request. Remember to always test your code on Windows! ## Tests `$ npm test` `$ npm test -- --watch` during development ## License Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). # is-descriptor [![NPM version](https://img.shields.io/npm/v/is-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-descriptor) > Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-descriptor ``` ## Usage ```js var isDescriptor = require('is-descriptor'); isDescriptor({value: 'foo'}) //=> true isDescriptor({get: function(){}, set: function(){}}) //=> true isDescriptor({get: 'foo', set: function(){}}) //=> false ``` You may also check for a descriptor by passing an object as the first argument and property name (`string`) as the second argument. ```js var obj = {}; obj.foo = 'abc'; Object.defineProperty(obj, 'bar', { value: 'xyz' }); isDescriptor(obj, 'foo'); //=> true isDescriptor(obj, 'bar'); //=> true ``` ## Examples ### value type `false` when not an object ```js isDescriptor('a'); //=> false isDescriptor(null); //=> false isDescriptor([]); //=> false ``` ### data descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({value: 'foo'}); //=> true isDescriptor({value: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', get: noop}); //=> false isDescriptor({get: noop, value: noop}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({value: 'foo', enumerable: 'foo'}); //=> false isDescriptor({value: 'foo', configurable: 'foo'}); //=> false isDescriptor({value: 'foo', writable: 'foo'}); //=> false ``` ### accessor descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({get: noop, set: noop}); //=> true isDescriptor({get: noop}); //=> true isDescriptor({set: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({get: noop, set: noop, bar: 'baz'}); //=> false isDescriptor({get: noop, writable: true}); //=> false isDescriptor({get: noop, value: true}); //=> false ``` `false` when an accessor is not a function ```js isDescriptor({get: noop, set: 'baz'}); //=> false isDescriptor({get: 'foo', set: noop}); //=> false isDescriptor({get: 'foo', bar: 'baz'}); //=> false isDescriptor({get: 'foo', set: 'baz'}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({get: noop, set: noop, enumerable: 'foo'}); //=> false isDescriptor({set: noop, configurable: 'foo'}); //=> false isDescriptor({get: noop, configurable: 'foo'}); //=> false ``` ## About ### Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 24 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ # is-windows [![NPM version](https://img.shields.io/npm/v/is-windows.svg?style=flat)](https://www.npmjs.com/package/is-windows) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-windows.svg?style=flat)](https://npmjs.org/package/is-windows) [![NPM total downloads](https://img.shields.io/npm/dt/is-windows.svg?style=flat)](https://npmjs.org/package/is-windows) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-windows.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-windows) > Returns true if the platform is windows. UMD module, works with node.js, commonjs, browser, AMD, electron, etc. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-windows ``` ## Heads up! As of `v0.2.0` this module always returns a function. ## Node.js usage ```js var isWindows = require('is-windows'); console.log(isWindows()); //=> returns true if the platform is windows ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [window-size](https://www.npmjs.com/package/window-size): Reliable way to get the height and width of terminal/console, since it's not calculated or… [more](https://github.com/jonschlinkert/window-size) | [homepage](https://github.com/jonschlinkert/window-size "Reliable way to get the height and width of terminal/console, since it's not calculated or updated the same way on all platforms, environments and node.js versions.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 11 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [SimenB](https://github.com/SimenB) | | 1 | [gucong3000](https://github.com/gucong3000) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 14, 2018._ # inflight Add callbacks to requests in flight to avoid async duplication ## USAGE ```javascript var inflight = require('inflight') // some request that does some stuff function req(key, callback) { // key is any random string. like a url or filename or whatever. // // will return either a falsey value, indicating that the // request for this key is already in flight, or a new callback // which when called will call all callbacks passed to inflightk // with the same key callback = inflight(key, callback) // If we got a falsey value back, then there's already a req going if (!callback) return // this is where you'd fetch the url or whatever // callback is also once()-ified, so it can safely be assigned // to multiple events etc. First call wins. setTimeout(function() { callback(null, key) }, 100) } // only assigns a single setTimeout // when it dings, all cbs get called req('foo', cb1) req('foo', cb2) req('foo', cb3) req('foo', cb4) ``` # lodash.tail v4.1.1 The [lodash](https://lodash.com/) method `_.tail` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.tail ``` In Node.js: ```js var tail = require('lodash.tail'); ``` See the [documentation](https://lodash.com/docs#tail) or [package source](https://github.com/lodash/lodash/blob/4.1.1-npm-packages/lodash.tail) for more details. # get-caller-file [![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) [![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) # enhanced-resolve Offers an async require.resolve function. It's highly configurable. ## Features * plugin system * provide a custom filesystem * sync and async node.js filesystems included ## Getting Started ### Install ```sh # npm npm install enhanced-resolve # or Yarn yarn add enhanced-resolve ``` ### Creating a Resolver The easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations. ```js const { NodeJsInputFileSystem, CachedInputFileSystem, ResolverFactory } = require('enhanced-resolve'); // create a resolver const myResolver = ResolverFactory.createResolver({ // Typical usage will consume the `NodeJsInputFileSystem` + `CachedInputFileSystem`, which wraps the Node.js `fs` wrapper to add resilience + caching. fileSystem: new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000), extensions: ['.js', '.json'] /* any other resolver options here. Options/defaults can be seen below */ }); // resolve a file with the new resolver const context = {}; const resolveContext = {}; const lookupStartPath = '/Users/webpack/some/root/dir'; const request = './path/to-look-up.js'; myResolver.resolve({}, lookupStartPath, request, resolveContext, (err/*Error*/, filepath/*string*/) => { // Do something with the path }); ``` For more examples creating different types resolvers (sync/async, context, etc) see `lib/node.js`. #### Resolver Options | Field | Default | Description | | ------------------------ | --------------------------- | ---------------------------------------------------------------------------------- | | alias | [] | A list of module alias configurations or an object which maps key to value | | aliasFields | [] | A list of alias fields in description files | | cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key | | descriptionFiles | ["package.json"] | A list of description files to read from | | enforceExtension | false | Enforce that a extension from extensions must be used | | enforceModuleExtension | false | Enforce that a extension from moduleExtensions must be used | | extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files | | mainFields | ["main"] | A list of main fields in description files | | mainFiles | ["index"] | A list of main files in directories | | modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name | | unsafeCache | false | Use this cache object to unsafely cache the successful requests | | plugins | [] | A list of additional resolve plugins which should be applied | | symlinks | true | Whether to resolve symlinks to their symlinked location | | cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with `path` and `request` properties. | | moduleExtensions | [] | A list of module extensions which should be tried for modules | | resolveToContext | false | Resolve to a context instead of a file | | fileSystem | | The file system which should be used | | resolver | undefined | A prepared Resolver to which the plugins are attached | ## Plugins Similar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`Tapable`](https://github.com/webpack/tapable). These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved. A plugin should be a `class` (or its ES5 equivalent) with an `apply` method. The `apply` method will receive a `resolver` instance, that can be used to hook in to the event system. ### Plugin Boilerplate ```js class MyResolverPlugin { constructor(source, target) { this.source = source; this.target = target; } apply(resolver) { const target = resolver.ensureHook(this.target); resolver.getHook(this.source).tapAsync("MyResolverPlugin", (request, resolveContext, callback) => { // Any logic you need to create a new `request` can go here resolver.doResolve(target, request, null, resolveContext, callback); }); } } ``` Plugins are executed in a pipeline, and register which event they should be executed before/after. In the example above, `source` is the name of the event that starts the pipeline, and `target` is what event this plugin should fire, which is what continues the execution of the pipeline. For an example of how these different plugin events create a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section. ## Tests ``` javascript npm test ``` [![Build Status](https://secure.travis-ci.org/webpack/enhanced-resolve.png?branch=master)](http://travis-ci.org/webpack/enhanced-resolve) ## Passing options from webpack If you are using `webpack`, and you want to pass custom options to `enhanced-resolve`, the options are passed from the `resolve` key of your webpack configuration e.g.: ``` resolve: { extensions: ['', '.js', '.jsx'], modules: ['src', 'node_modules'], plugins: [new DirectoryNamedWebpackPlugin()] ... }, ``` ## License Copyright (c) 2012-2016 Tobias Koppers MIT (http://www.opensource.org/licenses/mit-license.php) # create-hash [![Build Status](https://travis-ci.org/crypto-browserify/createHash.svg)](https://travis-ci.org/crypto-browserify/createHash) Node style hashes for use in the browser, with native hash functions in node. API is the same as hashes in node: ```js var createHash = require('create-hash') var hash = createHash('sha224') hash.update('synchronous write') // optional encoding parameter hash.digest() // synchronously get result with optional encoding parameter hash.write('write to it as a stream') hash.end() // remember it's a stream hash.read() // only if you ended it as a stream though ``` To get the JavaScript version even in node do `require('create-hash/browser')` # define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i define-property --save ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## Related projects * [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object) * [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._ [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] # extend() for Node.js <sup>[![Version Badge][npm-version-png]][npm-url]</sup> `node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. Notes: * Since Node.js >= 4, [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) now offers the same functionality natively (but without the "deep copy" option). See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6). * Some native implementations of `Object.assign` in both Node.js and many browsers (since NPM modules are for the browser too) may not be fully spec-compliant. Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for a compliant candidate. ## Installation This package is available on [npm][npm-url] as: `extend` ``` sh npm install extend ``` ## Usage **Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)** *Extend one object with one or more others, returning the modified object.* **Example:** ``` js var extend = require('extend'); extend(targetObject, object1, object2); ``` Keep in mind that the target object will be modified, and will be returned from extend(). If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s). Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. Warning: passing `false` as the first argument is not supported. ### Arguments * `deep` *Boolean* (optional) If set, the merge becomes recursive (i.e. deep copy). * `target` *Object* The object to extend. * `object1` *Object* The object that will be merged into the first. * `objectN` *Object* (Optional) More objects to merge into the first. ## License `node-extend` is licensed under the [MIT License][mit-license-url]. ## Acknowledgements All credit to the jQuery authors for perfecting this amazing utility. Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb]. [travis-svg]: https://travis-ci.org/justmoon/node-extend.svg [travis-url]: https://travis-ci.org/justmoon/node-extend [npm-url]: https://npmjs.org/package/extend [mit-license-url]: http://opensource.org/licenses/MIT [github-justmoon]: https://github.com/justmoon [github-insin]: https://github.com/insin [github-ljharb]: https://github.com/ljharb [npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg [deps-svg]: https://david-dm.org/justmoon/node-extend.svg [deps-url]: https://david-dm.org/justmoon/node-extend [dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg [dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies # set-blocking [![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) [![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) [![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. ```js const setBlocking = require('set-blocking') setBlocking(true) console.log(someLargeStringToOutput) ``` ## Historical Context/Word of Warning This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on newer versions of Node.js (`0.12+`), truncating terminal output. You should be mindful of the side-effects caused by using `set-blocking`: * if your module sets blocking to `true`, it will effect other modules consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call `setBlocking(true)` once we already know we are about to call `process.exit(code)`. * this patch will not apply to subprocesses spawned with `isTTY = true`, this is the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). ## License ISC # stream-each Iterate all the data in a stream ``` npm install stream-each ``` [![build status](http://img.shields.io/travis/mafintosh/stream-each.svg?style=flat)](http://travis-ci.org/mafintosh/stream-each) ## Usage ``` js var each = require('stream-each') each(stream, function (data, next) { console.log('data from stream', data) // when ready to consume next chunk next() }, function (err) { console.log('no more data') }) ``` ## API #### `each(stream, iterator, cb)` Iterate the data in the stream by calling the iterator function with `(data, next)` where data is a data chunk and next is a callback. Call next when you are ready to consume the next chunk. Optionally you can call next with an error to destroy the stream When the stream ends/errors the callback is called if provided ## License MIT ## Related `stream-each` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # is-accessor-descriptor [![NPM version](https://img.shields.io/npm/v/is-accessor-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-accessor-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-accessor-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-accessor-descriptor) > Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-accessor-descriptor ``` ## Usage ```js var isAccessor = require('is-accessor-descriptor'); isAccessor({get: function() {}}); //=> true ``` You may also pass an object and property name to check if the property is an accessor: ```js isAccessor(foo, 'bar'); ``` ## Examples `false` when not an object ```js isAccessor('a') isAccessor(null) isAccessor([]) //=> false ``` `true` when the object has valid properties and the properties all have the correct JavaScript types: ```js isAccessor({get: noop, set: noop}) isAccessor({get: noop}) isAccessor({set: noop}) //=> true ``` `false` when the object has invalid properties ```js isAccessor({get: noop, set: noop, bar: 'baz'}) isAccessor({get: noop, writable: true}) isAccessor({get: noop, value: true}) //=> false ``` `false` when an accessor is not a function ```js isAccessor({get: noop, set: 'baz'}) isAccessor({get: 'foo', set: noop}) isAccessor({get: 'foo', bar: 'baz'}) isAccessor({get: 'foo', set: 'baz'}) //=> false ``` `false` when a value is not the correct type ```js isAccessor({get: noop, set: noop, enumerable: 'foo'}) isAccessor({set: noop, configurable: 'foo'}) isAccessor({get: noop, configurable: 'foo'}) //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 22 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) ipaddr.js is a small (1.9K minified and gzipped) library for manipulating IP addresses in JavaScript environments. It runs on both CommonJS runtimes (e.g. [nodejs]) and in a web browser. ipaddr.js allows you to verify and parse string representation of an IP address, match it against a CIDR range or range list, determine if it falls into some reserved ranges (examples include loopback and private ranges), and convert between IPv4 and IPv4-mapped IPv6 addresses. [nodejs]: http://nodejs.org ## Installation `npm install ipaddr.js` or `bower install ipaddr.js` ## API ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, it is exported from the module: ```js var ipaddr = require('ipaddr.js'); ``` The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. ### Global methods There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and `ipaddr.process`. All of them receive a string as a single parameter. The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or IPv6 address, and `false` otherwise. It does not throw any exceptions. The `ipaddr.parse` method returns an object representing the IP address, or throws an `Error` if the passed string is not a valid representation of an IP address. The `ipaddr.process` method works just like the `ipaddr.parse` one, but it automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts before returning. It is useful when you have a Node.js instance listening on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 connections on your IPv6-only socket, but the remote address will be mangled. Use `ipaddr.process` method to automatically demangle it. ### Object representation Parsing methods return an object which descends from `ipaddr.IPv6` or `ipaddr.IPv4`. These objects share some properties, but most of them differ. #### Shared properties One can determine the type of address by calling `addr.kind()`. It will return either `"ipv6"` or `"ipv4"`. An address can be converted back to its string representation with `addr.toString()`. Note that this method: * does not return the original string used to create the object (in fact, there is no way of getting that string) * returns a compact representation (when it is applicable) A `match(range, bits)` method can be used to check if the address falls into a certain CIDR range. Note that an address can be (obviously) matched only against an address of the same type. For example: ```js var addr = ipaddr.parse("2001:db8:1234::1"); var range = ipaddr.parse("2001:db8::"); addr.match(range, 32); // => true ``` Alternatively, `match` can also be called as `match([range, bits])`. In this way, it can be used together with the `parseCIDR(string)` method, which parses an IP address together with a CIDR range. For example: ```js var addr = ipaddr.parse("2001:db8:1234::1"); addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true ``` A `range()` method returns one of predefined names for several special ranges defined by IP protocols. The exact names (and their respective CIDR ranges) can be looked up in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` (the default one) and `"reserved"`. You can match against your own range list by using `ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: ```js var rangeList = { documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], tunnelProviders: [ [ ipaddr.parse('2001:470::'), 32 ], // he.net [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 ] }; ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" ``` The addresses can be converted to their byte representation with `toByteArray()`. (Actually, JavaScript mostly does not know about byte buffers. They are emulated with arrays of numbers, each in range of 0..255.) ```js var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, <zeroes...>, 0x00, 0x68 ] ``` The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them have the same interface for both protocols, and are similar to global methods. `ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. `ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. [IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 [IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 #### IPv6 properties Sometimes you will want to convert IPv6 not to a compact string representation (with the `::` substitution); the `toNormalizedString()` method will return an address where all zeroes are explicit. For example: ```js var addr = ipaddr.parse("2001:0db8::0001"); addr.toString(); // => "2001:db8::1" addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" ``` The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped one, and `toIPv4Address()` will return an IPv4 object address. To access the underlying binary representation of the address, use `addr.parts`. ```js var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] ``` A IPv6 zone index can be accessed via `addr.zoneId`: ```js var addr = ipaddr.parse("2001:db8::%eth0"); addr.zoneId // => 'eth0' ``` #### IPv4 properties `toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. To access the underlying representation of the address, use `addr.octets`. ```js var addr = ipaddr.parse("192.168.1.1"); addr.octets // => [192, 168, 1, 1] ``` `prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or false if the netmask is not valid. ```js ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null ``` `subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. ```js ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" ``` `broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. ```js ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" ``` `networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. ```js ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" ``` #### Conversion IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, while for IPv6 it has to be an array of sixteen 8-bit values. For example: ```js var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); addr.toString(); // => "127.0.0.1" ``` or ```js var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) addr.toString(); // => "2001:db8::1" ``` Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). For example: ```js var addr = ipaddr.parse("127.0.0.1"); addr.toByteArray(); // => [0x7f, 0, 0, 1] ``` or ```js var addr = ipaddr.parse("2001:db8::1"); addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] ``` # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. # Source Map Support [![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process. ## Installation and Usage #### Node support ``` $ npm install source-map-support ``` Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler): ``` //# sourceMappingURL=path/to/source.map ``` If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). The path should either be absolute or relative to the compiled file. From here you have two options. ##### CLI Usage ```bash node -r source-map-support/register compiled.js ``` ##### Programmatic Usage Put the following line at the top of the compiled file. ```js require('source-map-support').install(); ``` It is also possible to install the source map support directly by requiring the `register` module which can be handy with ES6: ```js import 'source-map-support/register' // Instead of: import sourceMapSupport from 'source-map-support' sourceMapSupport.install() ``` Note: if you're using babel-register, it includes source-map-support already. It is also very useful with Mocha: ``` $ mocha --require source-map-support/register tests/ ``` #### Browser support This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code. This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify. ```html <script src="browser-source-map-support.js"></script> <script>sourceMapSupport.install();</script> ``` This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency: ```html <script> define(['browser-source-map-support'], function(sourceMapSupport) { sourceMapSupport.install(); }); </script> ``` ## Options This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer: ```js require('source-map-support').install({ handleUncaughtExceptions: false }); ``` This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access. ```js require('source-map-support').install({ retrieveSourceMap: function(source) { if (source === 'compiled.js') { return { url: 'original.js', map: fs.readFileSync('compiled.js.map', 'utf8') }; } return null; } }); ``` The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'. ```js require('source-map-support').install({ environment: 'node' }); ``` To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps. ```js require('source-map-support').install({ hookRequire: true }); ``` This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage. ## Demos #### Basic Demo original.js: ```js throw new Error('test'); // This is the original code ``` compiled.js: ```js require('source-map-support').install(); throw new Error('test'); // This is the compiled code // The next line defines the sourceMapping. //# sourceMappingURL=compiled.js.map ``` compiled.js.map: ```json { "version": 3, "file": "compiled.js", "sources": ["original.js"], "names": [], "mappings": ";;AAAA,MAAM,IAAI" } ``` Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js): ``` $ node compiled.js original.js:1 throw new Error('test'); // This is the original code ^ Error: test at Object.<anonymous> (original.js:1:7) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 ``` #### TypeScript Demo demo.ts: ```typescript declare function require(name: string); require('source-map-support').install(); class Foo { constructor() { this.bar(); } bar() { throw new Error('this is a demo'); } } new Foo(); ``` Compile and run the file using the TypeScript compiler from the terminal: ``` $ npm install source-map-support typescript $ node_modules/typescript/bin/tsc -sourcemap demo.ts $ node demo.js demo.ts:5 bar() { throw new Error('this is a demo'); } ^ Error: this is a demo at Foo.bar (demo.ts:5:17) at new Foo (demo.ts:4:24) at Object.<anonymous> (demo.ts:7:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 ``` There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base: ``` $ npm install source-map-support typescript $ node_modules/typescript/bin/tsc -sourcemap demo.ts $ node -r source-map-support/register demo.js demo.ts:5 bar() { throw new Error('this is a demo'); } ^ Error: this is a demo at Foo.bar (demo.ts:5:17) at new Foo (demo.ts:4:24) at Object.<anonymous> (demo.ts:7:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:901:3 ``` #### CoffeeScript Demo demo.coffee: ```coffee require('source-map-support').install() foo = -> bar = -> throw new Error 'this is a demo' bar() foo() ``` Compile and run the file using the CoffeeScript compiler from the terminal: ```sh $ npm install source-map-support coffeescript $ node_modules/.bin/coffee --map --compile demo.coffee $ node demo.js demo.coffee:3 bar = -> throw new Error 'this is a demo' ^ Error: this is a demo at bar (demo.coffee:3:22) at foo (demo.coffee:4:3) at Object.<anonymous> (demo.coffee:5:1) at Object.<anonymous> (demo.coffee:1:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) ``` ## Tests This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests: * Build the tests using `build.js` * Launch the HTTP server (`npm run serve-tests`) and visit * http://127.0.0.1:1336/amd-test * http://127.0.0.1:1336/browser-test * http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details). * For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/ ## License This code is available under the [MIT license](http://opensource.org/licenses/MIT). semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install --save semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the http://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <http://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero digit in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # string_decoder ***Node-core v8.9.4 string_decoder for userland*** [![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) [![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) ```bash npm install --save string_decoder ``` ***Node-core string_decoder for userland*** This package is a mirror of the string_decoder implementation in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). As of version 1.0.0 **string_decoder** uses semantic versioning. ## Previous versions Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. ## Update The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. ## Streams Working Group `string_decoder` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. See [readable-stream](https://github.com/nodejs/readable-stream) for more details. # etag [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Create simple HTTP ETags This module generates HTTP ETags (as defined in RFC 7232) for use in HTTP responses. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install etag ``` ## API <!-- eslint-disable no-unused-vars --> ```js var etag = require('etag') ``` ### etag(entity, [options]) Generate a strong ETag for the given entity. This should be the complete body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By default, a strong ETag is generated except for `fs.Stats`, which will generate a weak ETag (this can be overwritten by `options.weak`). <!-- eslint-disable no-undef --> ```js res.setHeader('ETag', etag(body)) ``` #### Options `etag` accepts these properties in the options object. ##### weak Specifies if the generated ETag will include the weak validator mark (that is, the leading `W/`). The actual entity tag is the same. The default value is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. ## Testing ```sh $ npm test ``` ## Benchmark ```bash $ npm run-script bench > [email protected] bench nodejs-etag > node benchmark/index.js [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] modules@48 [email protected] > node benchmark/body0-100b.js 100B body 4 tests completed. buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) > node benchmark/body1-1kb.js 1KB body 4 tests completed. buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) > node benchmark/body2-5kb.js 5KB body 4 tests completed. buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) > node benchmark/body3-10kb.js 10KB body 4 tests completed. buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) > node benchmark/body4-100kb.js 100KB body 4 tests completed. buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) > node benchmark/stats.js stat 4 tests completed. real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/etag.svg [npm-url]: https://npmjs.org/package/etag [node-version-image]: https://img.shields.io/node/v/etag.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg [travis-url]: https://travis-ci.org/jshttp/etag [coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master [downloads-image]: https://img.shields.io/npm/dm/etag.svg [downloads-url]: https://npmjs.org/package/etag # unicode-property-aliases-ecmascript [![Build status](https://travis-ci.org/mathiasbynens/unicode-property-aliases-ecmascript.svg?branch=master)](https://travis-ci.org/mathiasbynens/unicode-property-aliases-ecmascript) _unicode-property-aliases-ecmascript_ offers Unicode property alias mappings in an easy-to-consume JavaScript format. It only contains the Unicode property names that are supported in [ECMAScript RegExp property escapes](https://github.com/tc39/proposal-regexp-unicode-property-escapes). It’s based on [the `PropertyAliases.txt` data for Unicode v12.0.0](http://unicode.org/Public/12.0.0/ucd/PropertyAliases.txt). ## Installation To use _unicode-property-aliases-ecmascript_ programmatically, install it as a dependency via [npm](https://www.npmjs.com/): ```bash $ npm install unicode-property-aliases-ecmascript ``` Then, `require` it: ```js const propertyAliases = require('unicode-property-aliases-ecmascript'); ``` ## Usage This module exports a `Map` object. The most common usage is to convert a property alias to its canonical form: ```js propertyAliases.get('scx') // → 'Script_Extensions' ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _unicode-property-aliases-ecmascript_ is available under the [MIT](https://mths.be/mit) license. # array-unique [![NPM version](https://img.shields.io/npm/v/array-unique.svg?style=flat)](https://www.npmjs.com/package/array-unique) [![NPM downloads](https://img.shields.io/npm/dm/array-unique.svg?style=flat)](https://npmjs.org/package/array-unique) [![Build Status](https://img.shields.io/travis/jonschlinkert/array-unique.svg?style=flat)](https://travis-ci.org/jonschlinkert/array-unique) Remove duplicate values from an array. Fastest ES5 implementation. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save array-unique ``` ## Usage ```js var unique = require('array-unique'); var arr = ['a', 'b', 'c', 'c']; console.log(unique(arr)) //=> ['a', 'b', 'c'] console.log(arr) //=> ['a', 'b', 'c'] /* The above modifies the input array. To prevent that at a slight performance cost: */ var unique = require("array-unique").immutable; var arr = ['a', 'b', 'c', 'c']; console.log(unique(arr)) //=> ['a', 'b', 'c'] console.log(arr) //=> ['a', 'b', 'c', 'c'] ``` ## About ### Related projects * [arr-diff](https://www.npmjs.com/package/arr-diff): Returns an array with only the unique values from the first array, by excluding all… [more](https://github.com/jonschlinkert/arr-diff) | [homepage](https://github.com/jonschlinkert/arr-diff "Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons.") * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten "Recursively flatten an array or arrays. This is the fastest implementation of array flatten.") * [arr-map](https://www.npmjs.com/package/arr-map): Faster, node.js focused alternative to JavaScript's native array map. | [homepage](https://github.com/jonschlinkert/arr-map "Faster, node.js focused alternative to JavaScript's native array map.") * [arr-pluck](https://www.npmjs.com/package/arr-pluck): Retrieves the value of a specified property from all elements in the collection. | [homepage](https://github.com/jonschlinkert/arr-pluck "Retrieves the value of a specified property from all elements in the collection.") * [arr-reduce](https://www.npmjs.com/package/arr-reduce): Fast array reduce that also loops over sparse elements. | [homepage](https://github.com/jonschlinkert/arr-reduce "Fast array reduce that also loops over sparse elements.") * [arr-union](https://www.npmjs.com/package/arr-union): Combines a list of arrays, returning a single array with unique values, using strict equality… [more](https://github.com/jonschlinkert/arr-union) | [homepage](https://github.com/jonschlinkert/arr-union "Combines a list of arrays, returning a single array with unique values, using strict equality for comparisons.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/array-unique/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.28, on July 31, 2016._ # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` # is-descriptor [![NPM version](https://img.shields.io/npm/v/is-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-descriptor) > Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-descriptor ``` ## Usage ```js var isDescriptor = require('is-descriptor'); isDescriptor({value: 'foo'}) //=> true isDescriptor({get: function(){}, set: function(){}}) //=> true isDescriptor({get: 'foo', set: function(){}}) //=> false ``` You may also check for a descriptor by passing an object as the first argument and property name (`string`) as the second argument. ```js var obj = {}; obj.foo = 'abc'; Object.defineProperty(obj, 'bar', { value: 'xyz' }); isDescriptor(obj, 'foo'); //=> true isDescriptor(obj, 'bar'); //=> true ``` ## Examples ### value type `false` when not an object ```js isDescriptor('a'); //=> false isDescriptor(null); //=> false isDescriptor([]); //=> false ``` ### data descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({value: 'foo'}); //=> true isDescriptor({value: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', get: noop}); //=> false isDescriptor({get: noop, value: noop}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({value: 'foo', enumerable: 'foo'}); //=> false isDescriptor({value: 'foo', configurable: 'foo'}); //=> false isDescriptor({value: 'foo', writable: 'foo'}); //=> false ``` ### accessor descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({get: noop, set: noop}); //=> true isDescriptor({get: noop}); //=> true isDescriptor({set: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({get: noop, set: noop, bar: 'baz'}); //=> false isDescriptor({get: noop, writable: true}); //=> false isDescriptor({get: noop, value: true}); //=> false ``` `false` when an accessor is not a function ```js isDescriptor({get: noop, set: 'baz'}); //=> false isDescriptor({get: 'foo', set: noop}); //=> false isDescriptor({get: 'foo', bar: 'baz'}); //=> false isDescriptor({get: 'foo', set: 'baz'}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({get: noop, set: noop, enumerable: 'foo'}); //=> false isDescriptor({set: noop, configurable: 'foo'}); //=> false isDescriptor({get: noop, configurable: 'foo'}); //=> false ``` ## About ### Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 24 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ util-deprecate ============== ### The Node.js `util.deprecate()` function with browser support In Node.js, this module simply re-exports the `util.deprecate()` function. In the web browser (i.e. via browserify), a browser-specific implementation of the `util.deprecate()` function is used. ## API A `deprecate()` function is the only thing exposed by this module. ``` javascript // setup: exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead'); // users see: foo(); // foo() is deprecated, use bar() instead foo(); foo(); ``` ## License (The MIT License) Copyright (c) 2014 Nathan Rajlich <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Overview Adds support for the `timers` module to browserify. ## Wait, isn't it already supported in the browser? The public methods of the `timers` module are: * `setTimeout(callback, delay, [arg], [...])` * `clearTimeout(timeoutId)` * `setInterval(callback, delay, [arg], [...])` * `clearInterval(intervalId)` and indeed, browsers support these already. ## So, why does this exist? The `timers` module also includes some private methods used in other built-in Node.js modules: * `enroll(item, delay)` * `unenroll(item)` * `active(item)` These are used to efficiently support a large quantity of timers with the same timeouts by creating only a few timers under the covers. Node.js also offers the `immediate` APIs, which aren't yet available cross-browser, so we polyfill those: * `setImmediate(callback, [arg], [...])` * `clearImmediate(immediateId)` ## I need lots of timers and want to use linked list timers as Node.js does. Linked lists are efficient when you have thousands (millions?) of timers with the same delay. Take a look at [timers-browserify-full](https://www.npmjs.com/package/timers-browserify-full) in this case. # License [MIT](http://jryans.mit-license.org/) yargs ======== Yargs be a node.js library fer hearties tryin' ter parse optstrings. With yargs, ye be havin' a map that leads straight to yer treasure! Treasure of course, being a simple option hash. [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![Windows Tests][windows-image]][windows-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Gitter][gitter-image]][gitter-url] > Yargs is the official successor to optimist. Please feel free to submit issues and pull requests. If you'd like to contribute and don't know where to start, have a look at [the issue list](https://github.com/yargs/yargs/issues) :) examples ======== With yargs, the options be just a hash! ------------------------------------------------------------------- plunder.js: ````javascript #!/usr/bin/env node var argv = require('yargs').argv; if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!'); } else { console.log('Retreat from the xupptumblers!'); } ```` *** $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ![Joe was one optimistic pirate.](https://i.imgur.com/4WFGVJ9.png) But don't walk the plank just yet! There be more! You can do short options: ------------------------------------------------- short.js: ````javascript #!/usr/bin/env node var argv = require('yargs').argv; console.log('(%d,%d)', argv.x, argv.y); ```` *** $ ./short.js -x 10 -y 21 (10,21) And booleans, both long, short, and even grouped: ---------------------------------- bool.js: ````javascript #!/usr/bin/env node var argv = require('yargs').argv; if (argv.s) { process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: '); } console.log( (argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : '') ); ```` *** $ ./bool.js -s The parrot says: squawk $ ./bool.js -sp The parrot says: squawk! $ ./bool.js -sp --fr Le perroquet dit: couac! And non-hyphenated options too! Just use `argv._`! ------------------------------------------------- nonopt.js: ````javascript #!/usr/bin/env node var argv = require('yargs').argv; console.log('(%d,%d)', argv.x, argv.y); console.log(argv._); ```` *** $ ./nonopt.js -x 6.82 -y 3.35 rum (6.82,3.35) [ 'rum' ] $ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho (0.54,1.12) [ 'me hearties', 'yo', 'ho' ] Yargs even counts your booleans! ---------------------------------------------------------------------- count.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .count('verbose') .alias('v', 'verbose') .argv; VERBOSE_LEVEL = argv.verbose; function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); } WARN("Showing only important stuff"); INFO("Showing semi-important stuff too"); DEBUG("Extra chatty mode"); ```` *** $ node count.js Showing only important stuff $ node count.js -v Showing only important stuff Showing semi-important stuff too $ node count.js -vv Showing only important stuff Showing semi-important stuff too Extra chatty mode $ node count.js -v --verbose Showing only important stuff Showing semi-important stuff too Extra chatty mode Tell users how to use yer options and make demands. ------------------------------------------------- area.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .usage('Usage: $0 -w [num] -h [num]') .demandOption(['w','h']) .argv; console.log("The area is:", argv.w * argv.h); ```` *** $ ./area.js -w 55 -h 11 The area is: 605 $ node ./area.js -w 4.91 -w 2.51 Usage: area.js -w [num] -h [num] Options: -w [required] -h [required] Missing required arguments: h After yer demands have been met, demand more! Ask for non-hyphenated arguments! ----------------------------------------- demand_count.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .demandCommand(2) .argv; console.dir(argv); ```` *** $ ./demand_count.js a Not enough non-option arguments: got 1, need at least 2 $ ./demand_count.js a b { _: [ 'a', 'b' ], '$0': 'demand_count.js' } $ ./demand_count.js a b c { _: [ 'a', 'b', 'c' ], '$0': 'demand_count.js' } EVEN MORE SHIVER ME TIMBERS! ------------------ default_singles.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .default('x', 10) .default('y', 10) .argv ; console.log(argv.x + argv.y); ```` *** $ ./default_singles.js -x 5 15 default_hash.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .default({ x : 10, y : 10 }) .argv ; console.log(argv.x + argv.y); ```` *** $ ./default_hash.js -y 7 17 And if you really want to get all descriptive about it... --------------------------------------------------------- boolean_single.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .boolean('v') .argv ; console.dir(argv.v); console.dir(argv._); ```` *** $ ./boolean_single.js -v "me hearties" yo ho true [ 'me hearties', 'yo', 'ho' ] boolean_double.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .boolean(['x','y','z']) .argv ; console.dir([ argv.x, argv.y, argv.z ]); console.dir(argv._); ```` *** $ ./boolean_double.js -x -z one two three [ true, false, true ] [ 'one', 'two', 'three' ] Yargs is here to help you... --------------------------- Ye can describe parameters fer help messages and set aliases. Yargs figures out how ter format a handy help string automatically. line_count.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .usage('Usage: $0 <command> [options]') .command('count', 'Count the lines in a file') .example('$0 count -f foo.js', 'count the lines in the given file') .alias('f', 'file') .nargs('f', 1) .describe('f', 'Load a file') .demandOption(['f']) .help('h') .alias('h', 'help') .epilog('copyright 2015') .argv; var fs = require('fs'); var s = fs.createReadStream(argv.file); var lines = 0; s.on('data', function (buf) { lines += buf.toString().match(/\n/g).length; }); s.on('end', function () { console.log(lines); }); ```` *** $ node line_count.js count Usage: line_count.js <command> [options] Commands: count Count the lines in a file Options: -f, --file Load a file [required] -h, --help Show help [boolean] Examples: line_count.js count -f foo.js count the lines in the given file copyright 2015 Missing required arguments: f $ node line_count.js count --file line_count.js 26 $ node line_count.js count -f line_count.js 26 methods ======= By itself, ````javascript require('yargs').argv ```` will use the `process.argv` array to construct the `argv` object. You can pass in the `process.argv` yourself: ````javascript require('yargs')([ '-x', '1', '-y', '2' ]).argv ```` or use `.parse()` to do the same thing: ````javascript require('yargs').parse([ '-x', '1', '-y', '2' ]) ```` The rest of these methods below come in just before the terminating `.argv`. <a name="alias"></a>.alias(key, alias) ------------------ Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa. Optionally `.alias()` can take an object that maps keys to aliases. Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings. .argv ----- Get the arguments as a plain old object. Arguments without a corresponding flag show up in the `argv._` array. The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl. If `yargs` is executed in an environment that embeds node and there's no script name (e.g. [Electron](http://electron.atom.io/) or [nw.js](http://nwjs.io/)), it will ignore the first parameter since it expects it to be the script name. In order to override this behavior, use `.parse(process.argv.slice(1))` instead of `.argv` and the first parameter won't be ignored. <a name="array"></a>.array(key) ---------- Tell the parser to interpret `key` as an array. If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`. <a name="boolean"></a>.boolean(key) ------------- Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`. `key` will default to `false`, unless a `default(key, undefined)` is explicitly set. If `key` is an array, interpret all the elements as booleans. .check(fn, [global=true]) ---------- Check that certain conditions are met in the provided arguments. `fn` is called with two arguments, the parsed `argv` hash and an array of options and their aliases. If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and exit. `global` indicates whether `check()` should be enabled both at the top-level and for each sub-command. <a name="choices"></a>.choices(key, choices) ---------------------- Limit valid values for `key` to a predefined set of `choices`, given as an array or as an individual value. ```js var argv = require('yargs') .alias('i', 'ingredient') .describe('i', 'choose your sandwich ingredients') .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) .help('help') .argv ``` If this method is called multiple times, all enumerated values will be merged together. Choices are generally strings or numbers, and value matching is case-sensitive. Optionally `.choices()` can take an object that maps multiple keys to their choices. Choices can also be specified as `choices` in the object given to `option()`. ```js var argv = require('yargs') .option('size', { alias: 's', describe: 'choose a size', choices: ['xs', 's', 'm', 'l', 'xl'] }) .argv ``` <a name="coerce"></a>.coerce(key, fn) ---------------- Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`. The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error. The returned value will be used as the value for `key` (or one of its aliases) in `argv`. If the function throws, the error will be treated as a validation failure, delegating to either a custom [`.fail()`](#fail) handler or printing the error message in the console. Coercion will be applied to a value after all other modifications, such as [`.normalize()`](#normalize). _Examples:_ ```js var argv = require('yargs') .coerce('file', function (arg) { return require('fs').readFileSync(arg, 'utf8') }) .argv ``` Optionally `.coerce()` can take an object that maps several keys to their respective coercion function. ```js var argv = require('yargs') .coerce({ date: Date.parse, json: JSON.parse }) .argv ``` You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`: ```js var path = require('path') var argv = require('yargs') .coerce(['src', 'dest'], path.resolve) .argv ``` If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed: ```js // --user.name Batman --user.password 123 // gives us: {name: 'batman', password: '[SECRET]'} var argv = require('yargs') .option('user') .coerce('user', opt => { opt.name = opt.name.toLowerCase() opt.password = '[SECRET]' return opt }) .argv ``` .command(cmd, desc, [builder], [handler]) ----------------------------------------- .command(cmd, desc, [module]) ----------------------------- .command(module) ---------------- Define the commands exposed by your application. `cmd` should be a string representing the command or an array of strings representing the command and its aliases. Read more about command aliases in the subsection below. Use `desc` to provide a description for each command your application accepts (the values stored in `argv._`). Set `desc` to `false` to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion. Optionally, you can provide a `builder` object to give hints about the options that your command accepts: ```js yargs .command('get', 'make a get HTTP request', { url: { alias: 'u', default: 'http://yargs.js.org/' } }) .help() .argv ``` `builder` can also be a function. This function is executed with a `yargs` instance, and can be used to provide _advanced_ command specific help: ```js yargs .command('get', 'make a get HTTP request', function (yargs) { return yargs.option('url', { alias: 'u', default: 'http://yargs.js.org/' }) }) .help() .argv ``` You can also provide a handler function, which will be executed with the parsed `argv` object: ```js yargs .command( 'get', 'make a get HTTP request', function (yargs) { return yargs.option('u', { alias: 'url', describe: 'the URL to make an HTTP request to' }) }, function (argv) { console.log(argv.url) } ) .help() .argv ``` ### Default Commands To specify a default command use the character `*`. A default command will be run if the positional arguments provided match no known commands: ```js const argv = require('yargs') .command('*', 'the default command', () => {}, (argv) => { console.log('this command will be run by default') }) ``` The command defined above will be executed if the program is run with `./my-cli.js --x=22`. Default commands can also be used as a command alias, like so: ```js const argv = require('yargs') .command(['serve', '*'], 'the serve command', () => {}, (argv) => { console.log('this command will be run by default') }) ``` The command defined above will be executed if the program is run with `./my-cli.js --x=22`, or with `./my-cli.js serve --x=22`. ### Positional Arguments Commands can accept _optional_ and _required_ positional arguments. Required positional arguments take the form `<foo>`, and optional arguments take the form `[bar]`. The parsed positional arguments will be populated in `argv`: ```js yargs.command('get <source> [proxy]', 'make a get HTTP request') .help() .argv ``` #### Positional Argument Aliases Aliases can be provided for positional arguments using the `|` character. As an example, suppose our application allows either a username _or_ an email as the first argument: ```js yargs.command('get <username|email> [password]', 'fetch a user by username or email.') .help() .argv ``` In this way, both `argv.username` and `argv.email` would be populated with the same value when the command is executed. #### Variadic Positional Arguments The last positional argument can optionally accept an array of values, by using the `..` operator: ```js yargs.command('download <url> [files..]', 'download several files') .help() .argv ``` ### Command Execution When a command is given on the command line, yargs will execute the following: 1. push the command into the current context 2. reset non-global configuration 3. apply command configuration via the `builder`, if given 4. parse and validate args from the command line, including positional args 5. if validation succeeds, run the `handler` function, if given 6. pop the command from the current context ### Command Aliases You can define aliases for a command by putting the command and all of its aliases into an array. Alternatively, a command module may specify an `aliases` property, which may be a string or an array of strings. All aliases defined via the `command` property and the `aliases` property will be concatenated together. The first element in the array is considered the canonical command, which may define positional arguments, and the remaining elements in the array are considered aliases. Aliases inherit positional args from the canonical command, and thus any positional args defined in the aliases themselves are ignored. If either the canonical command or any of its aliases are given on the command line, the command will be executed. ```js #!/usr/bin/env node require('yargs') .command(['start [app]', 'run', 'up'], 'Start up an app', {}, (argv) => { console.log('starting up the', argv.app || 'default', 'app') }) .command({ command: 'configure <key> [value]', aliases: ['config', 'cfg'], desc: 'Set a config variable', builder: (yargs) => yargs.default('value', 'true'), handler: (argv) => { console.log(`setting ${argv.key} to ${argv.value}`) } }) .demandCommand() .help() .wrap(72) .argv ``` ``` $ ./svc.js help Commands: start [app] Start up an app [aliases: run, up] configure <key> [value] Set a config variable [aliases: config, cfg] Options: --help Show help [boolean] $ ./svc.js cfg concurrency 4 setting concurrency to 4 $ ./svc.js run web starting up the web app ``` ### Providing a Command Module For complicated commands you can pull the logic into a module. A module simply needs to export: * `exports.command`: string (or array of strings) that executes this command when given on the command line, first string may contain positional args * `exports.aliases`: array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored * `exports.describe`: string used as the description for the command in help text, use `false` for a hidden command * `exports.builder`: object declaring the options the command accepts, or a function accepting and returning a yargs instance * `exports.handler`: a function which will be passed the parsed argv. ```js // my-module.js exports.command = 'get <source> [proxy]' exports.describe = 'make a get HTTP request' exports.builder = { banana: { default: 'cool' }, batman: { default: 'sad' } } exports.handler = function (argv) { // do something with argv. } ``` You then register the module like so: ```js yargs.command(require('my-module')) .help() .argv ``` Or if the module does not export `command` and `describe` (or if you just want to override them): ```js yargs.command('get <source> [proxy]', 'make a get HTTP request', require('my-module')) .help() .argv ``` .commandDir(directory, [opts]) ------------------------------ Apply command modules from a directory relative to the module calling this method. This allows you to organize multiple commands into their own modules under a single directory and apply all of them at once instead of calling `.command(require('./dir/module'))` multiple times. By default, it ignores subdirectories. This is so you can use a directory structure to represent your command hierarchy, where each command applies its subcommands using this method in its builder function. See the example below. Note that yargs assumes all modules in the given directory are command modules and will error if non-command modules are encountered. In this scenario, you can either move your module to a different directory or use the `exclude` or `visit` option to manually filter it out. More on that below. `directory` is a relative directory path as a string (required). `opts` is an options object (optional). The following options are valid: - `recurse`: boolean, default `false` Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. - `extensions`: array of strings, default `['js']` The types of files to look for when requiring command modules. - `visit`: function A synchronous function called for each command module encountered. Accepts `commandObject`, `pathToFile`, and `filename` as arguments. Returns `commandObject` to include the command; any falsy value to exclude/skip it. - `include`: RegExp or function Whitelist certain modules. See [`require-directory` whitelisting](https://www.npmjs.com/package/require-directory#whitelisting) for details. - `exclude`: RegExp or function Blacklist certain modules. See [`require-directory` blacklisting](https://www.npmjs.com/package/require-directory#blacklisting) for details. ### Example command hierarchy using `.commandDir()` Desired CLI: ```sh $ myapp --help $ myapp init $ myapp remote --help $ myapp remote add base http://yargs.js.org $ myapp remote prune base $ myapp remote prune base fork whatever ``` Directory structure: ``` myapp/ ├─ cli.js └─ cmds/ ├─ init.js ├─ remote.js └─ remote_cmds/ ├─ add.js └─ prune.js ``` cli.js: ```js #!/usr/bin/env node require('yargs') .commandDir('cmds') .demandCommand() .help() .argv ``` cmds/init.js: ```js exports.command = 'init [dir]' exports.desc = 'Create an empty repo' exports.builder = { dir: { default: '.' } } exports.handler = function (argv) { console.log('init called for dir', argv.dir) } ``` cmds/remote.js: ```js exports.command = 'remote <command>' exports.desc = 'Manage set of tracked repos' exports.builder = function (yargs) { return yargs.commandDir('remote_cmds') } exports.handler = function (argv) {} ``` cmds/remote_cmds/add.js: ```js exports.command = 'add <name> <url>' exports.desc = 'Add remote named <name> for repo at url <url>' exports.builder = {} exports.handler = function (argv) { console.log('adding remote %s at url %s', argv.name, argv.url) } ``` cmds/remote_cmds/prune.js: ```js exports.command = 'prune <name> [names..]' exports.desc = 'Delete tracked branches gone stale for remotes' exports.builder = {} exports.handler = function (argv) { console.log('pruning remotes %s', [].concat(argv.name).concat(argv.names).join(', ')) } ``` .completion([cmd], [description], [fn]) --------------------------------------- Enable bash-completion shortcuts for commands and options. `cmd`: When present in `argv._`, will result in the `.bashrc` completion script being outputted. To enable bash completions, concat the generated script to your `.bashrc` or `.bash_profile`. `description`: Provide a description in your usage instructions for the command that generates bash completion scripts. `fn`: Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method. If invoked without parameters, `.completion()` will make `completion` the command to output the completion script. ```js var argv = require('yargs') .completion('completion', function(current, argv) { // 'current' is the current command being completed. // 'argv' is the parsed arguments so far. // simply return an array of completions. return [ 'foo', 'bar' ]; }) .argv; ``` You can also provide asynchronous completions. ```js var argv = require('yargs') .completion('completion', function(current, argv, done) { setTimeout(function() { done([ 'apple', 'banana' ]); }, 500); }) .argv; ``` But wait, there's more! You can return an asynchronous promise. ```js var argv = require('yargs') .completion('completion', function(current, argv, done) { return new Promise(function (resolve, reject) { setTimeout(function () { resolve(['apple', 'banana']) }, 10) }) }) .argv; ``` <a name="config"></a>.config([key], [description], [parseFn]) ------------------------------------------------------------- .config(object) --------------- Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file. The file is loaded and parsed, and its properties are set as arguments. Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly. If invoked without parameters, `.config()` will make `--config` the option to pass the JSON config file. An optional `description` can be provided to customize the config (`key`) option in the usage string. An optional `parseFn` can be used to provide a custom parser. The parsing function must be synchronous, and should return an object containing key value pairs or an error. ```js var argv = require('yargs') .config('settings', function (configPath) { return JSON.parse(fs.readFileSync(configPath, 'utf-8')) }) .argv ``` You can also pass an explicit configuration `object`, it will be parsed and its properties will be set as arguments. ```js var argv = require('yargs') .config({foo: 1, bar: 2}) .argv console.log(argv) ``` ``` $ node test.js { _: [], foo: 1, bar: 2, '$0': 'test.js' } ``` Note that a configuration object may extend from a JSON file using the `"extends"` property. When doing so, the `"extends"` value should be a path (relative or absolute) to the extended JSON file. <a name="conflicts"></a>.conflicts(x, y) ---------------------------------------------- Given the key `x` is set, the key `y` must not be set. Optionally `.conflicts()` can accept an object specifying multiple conflicting keys. <a name="count"></a>.count(key) ------------ Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`. <a name="default"></a>.default(key, value, [description]) --------------------------------------------------------- .defaults(key, value, [description]) ------------------------------------ **Note:** The `.defaults()` alias is deprecated. It will be removed in the next major version. Set `argv[key]` to `value` if no option was specified in `process.argv`. Optionally `.default()` can take an object that maps keys to default values. But wait, there's more! The default value can be a `function` which returns a value. The name of the function will be used in the usage string: ```js var argv = require('yargs') .default('random', function randomValue() { return Math.random() * 256; }).argv; ``` Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions: ```js .default('timeout', 60000, '(one-minute)') ``` <a name="demand"></a>.demand(count, [max], [msg]) [DEPRECATED] -------------------- `demand()` has been deprecated, please instead see [`demandOption()`](#demandOption) and [`demandCommand()`](#demandCommand). <a name="demandOption"></a>.demandOption(key, [msg | boolean]) ------------------------------ .demandOption(key, msg) ------------------------------ If `key` is a string, show the usage information and exit if `key` wasn't specified in `process.argv`. If `key` is an array, demand each element. If a `msg` string is given, it will be printed when the argument is missing, instead of the standard error message. ```javascript // demand an array of keys to be provided require('yargs') .option('run', { alias: 'r', describe: 'run your program' }) .option('path', { alias: 'p', describe: 'provide a path to file' }) .option('spec', { alias: 's', describe: 'program specifications' }) .demandOption(['run', 'path'], 'Please provide both run and path arguments to work with this tool') .help() .argv ``` which will provide the following output: ```bash Options: --run, -r run your program [required] --path, -p provide a path to file [required] --spec, -s program specifications --help Show help [boolean] Missing required arguments: run, path Please provide both run and path arguments to work with this tool ``` If a `boolean` value is given, it controls whether the option is demanded; this is useful when using `.options()` to specify command line parameters. ```javascript // demand individual options within the option constructor require('yargs') .options({ 'run': { alias: 'r', describe: 'run your program', demandOption: true }, 'path': { alias: 'p', describe: 'provide a path to file', demandOption: true }, 'spec': { alias: 's', describe: 'program specifications' } }) .help() .argv ``` which will provide the following output: ```bash Options: --run, -r run your program [required] --path, -p provide a path to file [required] --spec, -s program specifications --help Show help [boolean] Missing required arguments: run, path ``` <a name="demandCommand"></a>.demandCommand([min=1], [minMsg]) ------------------------------ .demandCommand([min=1], [max], [minMsg], [maxMsg]) ------------------------------ Demand in context of commands. You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met. ```javascript require('yargs') .command({ command: 'configure <key> [value]', aliases: ['config', 'cfg'], desc: 'Set a config variable', builder: (yargs) => yargs.default('value', 'true'), handler: (argv) => { console.log(`setting ${argv.key} to ${argv.value}`) } }) // provide a minimum demand and a minimum demand message .demandCommand(1, 'You need at least one command before moving on') .help() .argv ``` which will provide the following output: ```bash Commands: configure <key> [value] Set a config variable [aliases: config, cfg] Options: --help Show help [boolean] You need at least one command before moving on ``` _Note: in `minMsg` and `maxMsg`, every occurrence of `$0` will be replaced with the observed value, and every instance of `$1` will be replaced with the expected value._ <a name="describe"></a>.describe(key, desc) -------------------- Describe a `key` for the generated usage information. Optionally `.describe()` can take an object that maps keys to descriptions. .detectLocale(boolean) ----------- Should yargs attempt to detect the os' locale? Defaults to `true`. .env([prefix]) -------------- Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments. Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo) If this method is called with no argument or with an empty string or with `true`, then all env vars will be applied to argv. Program arguments are defined in this order of precedence: 1. Command line args 2. Env vars 3. Config file/objects 4. Configured defaults ```js var argv = require('yargs') .env('MY_PROGRAM') .option('f', { alias: 'fruit-thing', default: 'apple' }) .argv console.log(argv) ``` ``` $ node fruity.js { _: [], f: 'apple', 'fruit-thing': 'apple', fruitThing: 'apple', '$0': 'fruity.js' } ``` ``` $ MY_PROGRAM_FRUIT_THING=banana node fruity.js { _: [], fruitThing: 'banana', f: 'banana', 'fruit-thing': 'banana', '$0': 'fruity.js' } ``` ``` $ MY_PROGRAM_FRUIT_THING=banana node fruity.js -f cat { _: [], f: 'cat', 'fruit-thing': 'cat', fruitThing: 'cat', '$0': 'fruity.js' } ``` Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration. .epilog(str) ------------ .epilogue(str) -------------- A message to print at the end of the usage instructions, e.g. ```js var argv = require('yargs') .epilogue('for more information, find our manual at http://example.com'); ``` .example(cmd, desc) ------------------- Give some example invocations of your program. Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. Examples will be printed out as part of the help message. <a name="exitprocess"></a>.exitProcess(enable) ---------------------------------- By default, yargs exits the process when the user passes a help flag, uses the `.version` functionality, or when validation fails. Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated. <a name="fail"></a>.fail(fn) --------- Method to execute when a failure occurs, rather than printing the failure message. `fn` is called with the failure message that would have been printed, the `Error` instance originally thrown and yargs state when the failure occured. ```js var argv = require('yargs') .fail(function (msg, err, yargs) { if (err) throw err // preserve stack console.error('You broke it!') console.error(msg) console.error('You should be doing', yargs.help()) process.exit(1) }) .argv ``` .getCompletion(args, done); --------------------------- Allows to programmatically get completion choices for any line. `args`: An array of the words in the command line to complete. `done`: The callback to be called with the resulting completions. For example: ```js require('yargs') .option('foobar') .option('foobaz') .completion() .getCompletion(['./test.js', '--foo'], function (completions) { console.log(completions) }) ``` Outputs the same completion choices as `./test.js --foo`<kbd>TAB</kbd>: `--foobar` and `--foobaz` <a name="global"></a>.global(globals, [global=true]) ------------ Indicate that an option (or group of options) should not be reset when a command is executed, as an example: ```js var argv = require('yargs') .option('a', { alias: 'all', default: true, global: false }) .option('n', { alias: 'none', default: true, global: false }) .command('foo', 'foo command', function (yargs) { return yargs.option('b', { alias: 'bar' }) }) .help('help') .global('a') .argv ``` If the `foo` command is executed the `all` option will remain, but the `none` option will have been eliminated. Options default to being global. <a name="group"></a>.group(key(s), groupName) -------------------- Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions, e.g., ```js var yargs = require('yargs')(['--help']) .help() .group('batman', 'Heroes:') .describe('batman', "world's greatest detective") .wrap(null) .argv ``` *** Heroes: --batman world's greatest detective Options: --help Show help [boolean] <a name="help"></a>.help() ----------------------------------------- .help([option | boolean]) ----------------------------------------- .help([option, [description | boolean]]) ----------------------------------------- .help([option, [description, [boolean]]]) ----------------------------------------- Add an option (e.g. `--help`) and implicit command that displays the usage string and exits the process. If present, the `description` parameter customizes the description of the help option in the usage string. If a boolean argument is provided, it will enable or disable the use of an implicit command. The implicit command is enabled by default, but it can be disabled by passing `false`. Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command. If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command. If invoked without parameters, `.help()` will use `--help` as the option and `help` as the implicit command to trigger help output. Example: ```js var yargs = require("yargs")(['--help']) .usage("$0 -operand1 number -operand2 number -operation [add|subtract]") .help() .argv ``` Later on, `argv` can be retrieved with `yargs.argv`. <a name="implies"></a>.implies(x, y) -------------- Given the key `x` is set, it is required that the key `y` is set. Optionally `.implies()` can accept an object specifying multiple implications. .locale() --------- Return the locale that yargs is currently using. By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language. To override this behavior with a static locale, pass the desired locale as a string to this method (see below). .locale(locale) --------------- Override the auto-detected locale from the user's operating system with a static locale. Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable. ```js var argv = require('yargs') .usage('./$0 - follow ye instructions true') .option('option', { alias: 'o', describe: "'tis a mighty fine option", demandOption: true }) .command('run', "Arrr, ya best be knowin' what yer doin'") .example('$0 run foo', "shiver me timbers, here's an example for ye") .help('help') .wrap(70) .locale('pirate') .argv ``` *** ```shell ./test.js - follow ye instructions true Choose yer command: run Arrr, ya best be knowin' what yer doin' Options for me hearties! --option, -o 'tis a mighty fine option [requi-yar-ed] --help Parlay this here code of conduct [boolean] Ex. marks the spot: test.js run foo shiver me timbers, here's an example for ye Ye be havin' to set the followin' argument land lubber: option ``` Locales currently supported: * **de:** German. * **en:** American English. * **es:** Spanish. * **fr:** French. * **hi:** Hindi. * **hu:** Hungarian. * **id:** Indonesian. * **it:** Italian. * **ja:** Japanese. * **ko:** Korean. * **nb:** Norwegian Bokmål. * **pirate:** American Pirate. * **pl:** Polish. * **pt:** Portuguese. * **pt_BR:** Brazilian Portuguese. * **ru:** Russian. * **th:** Thai. * **tr:** Turkish. * **zh_CN:** Chinese. To submit a new translation for yargs: 1. use `./locales/en.json` as a starting point. 2. submit a pull request with the new locale file. *The [Microsoft Terminology Search](http://www.microsoft.com/Language/en-US/Search.aspx) can be useful for finding the correct terminology in your locale.* <a name="nargs"></a>.nargs(key, count) ----------- The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity. For example: ```js var argv = require('yargs') .nargs('token', 1) .parse(['--token', '-my-token']); ``` parses as: `{ _: [], token: '-my-token', '$0': 'node test' }` Optionally `.nargs()` can take an object of `key`/`narg` pairs. <a name="normalize"></a>.normalize(key) --------------- The key provided represents a path and should have `path.normalize()` applied. <a name="number"></a>.number(key) ------------ Tell the parser to always interpret `key` as a number. If `key` is an array, all elements will be parsed as numbers. If the option is given on the command line without a value, `argv` will be populated with `undefined`. If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`. Note that decimals, hexadecimals, and scientific notation are all accepted. ```js var argv = require('yargs') .number('n') .number(['width', 'height']) .argv ``` .option(key, [opt]) ----------------- .options(key, [opt]) ------------------ This method can be used to make yargs aware of options that _could_ exist. You can also pass an `opt` object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option. For example: ````javascript var argv = require('yargs') .option('f', { alias: 'file', demandOption: true, default: '/etc/passwd', describe: 'x marks the spot', type: 'string' }) .argv ; ```` is the same as ````javascript var argv = require('yargs') .alias('f', 'file') .demandOption('f') .default('f', '/etc/passwd') .describe('f', 'x marks the spot') .string('f') .argv ; ```` Optionally `.options()` can take an object that maps keys to `opt` parameters. ````javascript var argv = require('yargs') .options({ 'f': { alias: 'file', demandOption: true, default: '/etc/passwd', describe: 'x marks the spot', type: 'string' } }) .argv ; ```` Valid `opt` keys include: - `alias`: string or array of strings, alias(es) for the canonical option key, see [`alias()`](#alias) - `array`: boolean, interpret option as an array, see [`array()`](#array) - `boolean`: boolean, interpret option as a boolean flag, see [`boolean()`](#boolean) - `choices`: value or array of values, limit valid option arguments to a predefined set, see [`choices()`](#choices) - `coerce`: function, coerce or transform parsed command line values into another value, see [`coerce()`](#coerce) - `config`: boolean, interpret option as a path to a JSON config file, see [`config()`](#config) - `configParser`: function, provide a custom config parsing function, see [`config()`](#config) - `conflicts`: string or object, require certain keys not to be set, see [`conflicts()`](#conflicts) - `count`: boolean, interpret option as a count of boolean flags, see [`count()`](#count) - `default`: value, set a default value for the option, see [`default()`](#default) - `defaultDescription`: string, use this description for the default value in help content, see [`default()`](#default) - `demandOption`: boolean or string, demand the option be given, with optional error message, see [`demandOption()`](#demandOption) - `desc`/`describe`/`description`: string, the option description for help content, see [`describe()`](#describe) - `global`: boolean, indicate that this key should not be [reset](#reset) when a command is invoked, see [`global()`](#global) - `group`: string, when displaying usage instructions place the option under an alternative group heading, see [`group()`](#group) - `implies`: string or object, require certain keys to be set, see [`implies()`](#implies) - `nargs`: number, specify how many arguments should be consumed for the option, see [`nargs()`](#nargs) - `normalize`: boolean, apply `path.normalize()` to the option, see [`normalize()`](#normalize) - `number`: boolean, interpret option as a number, [`number()`](#number) - `requiresArg`: boolean, require the option be specified with a value, see [`requiresArg()`](#requiresArg) - `skipValidation`: boolean, skips validation if the option is present, see [`skipValidation()`](#skipValidation) - `string`: boolean, interpret option as a string, see [`string()`](#string) - `type`: one of the following strings - `'array'`: synonymous for `array: true`, see [`array()`](#array) - `'boolean'`: synonymous for `boolean: true`, see [`boolean()`](#boolean) - `'count'`: synonymous for `count: true`, see [`count()`](#count) - `'number'`: synonymous for `number: true`, see [`number()`](#number) - `'string'`: synonymous for `string: true`, see [`string()`](#string) .parse(args, [context], [parseCallback]) ------------ Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string. A `context` object can optionally be given as the second argument to `parse()`, providing a useful mechanism for passing state information to commands: ```js const parser = yargs .command('lunch-train <restaurant>', 'start lunch train', function () {}, function (argv) { console.log(argv.restaurant, argv.time) }) .parse("lunch-train rudy's", {time: '12:15'}) ``` A `parseCallback` can also be provided to `.parse()`. If a callback is given, it will be invoked with three arguments: 1. `err`: populated if any validation errors raised while parsing. 2. `argv`: the parsed argv object. 3. `output`: any text that would have been output to the terminal, had a callback not been provided. ```js // providing the `fn` argument to `parse()` runs yargs in headless mode, this // makes it easy to use yargs in contexts other than the CLI, e.g., writing // a chat-bot. const parser = yargs .command('lunch-train <restaurant> <time>', 'start lunch train', function () {}, function (argv) { api.scheduleLunch(argv.restaurant, moment(argv.time)) }) .help() parser.parse(bot.userText, function (err, argv, output) { if (output) bot.respond(output) }) ``` ***Note:*** Providing a callback to `parse()` disables the [`exitProcess` setting](#exitprocess) until after the callback is invoked. .pkgConf(key, [cwd]) ------------ Similar to [`config()`](#config), indicates that yargs should interpret the object from the specified key in package.json as a configuration object. `cwd` can optionally be provided, the package.json will be read from this location. Note that a configuration stanza in package.json may extend from an identically keyed stanza in another package.json file using the `"extends"` property. When doing so, the `"extends"` value should be a path (relative or absolute) to the extended package.json file. .recommendCommands() --------------------------- Should yargs provide suggestions regarding similar commands if no matching command is found? .require(key, [msg | boolean]) ------------------------------ .required(key, [msg | boolean]) ------------------------------ An alias for [`demand()`](#demand). See docs there. <a name="requiresArg"></a>.requiresArg(key) ----------------- Specifies either a single option key (string), or an array of options that must be followed by option values. If any option value is missing, show the usage information and exit. The default behavior is to set the value of any key not followed by an option value to `true`. <a name="reset"></a>.reset() -------- Reset the argument object built up so far. This is useful for creating nested command line interfaces. Use [global](#global) to specify keys that should not be reset. ```js var yargs = require('yargs') .usage('$0 command') .command('hello', 'hello command') .command('world', 'world command') .demandCommand(1, 'must provide a valid command'), argv = yargs.argv, command = argv._[0]; if (command === 'hello') { yargs.reset() .usage('$0 hello') .help('h') .example('$0 hello', 'print the hello message!') .argv console.log('hello!'); } else if (command === 'world'){ yargs.reset() .usage('$0 world') .help('h') .example('$0 world', 'print the world message!') .argv console.log('world!'); } else { yargs.showHelp(); } ``` .showCompletionScript() ---------------------- Generate a bash completion script. Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options. .showHelp(consoleLevel='error') --------------------------- Print the usage data using the [`console`](https://nodejs.org/api/console.html) function `consoleLevel` for printing. Example: ```js var yargs = require("yargs") .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); yargs.showHelp(); //prints to stderr using console.error() ``` Or, to print the usage data to `stdout` instead, you can specify the use of `console.log`: ```js yargs.showHelp("log"); //prints to stdout using console.log() ``` Later on, `argv` can be retrieved with `yargs.argv`. .showHelpOnFail(enable, [message]) ---------------------------------- By default, yargs outputs a usage string if any error is detected. Use the `.showHelpOnFail()` method to customize this behavior. If `enable` is `false`, the usage string is not output. If the `message` parameter is present, this message is output after the error message. line_count.js: ````javascript #!/usr/bin/env node var argv = require('yargs') .usage('Count the lines in a file.\nUsage: $0 -f <file>') .demandOption('f') .alias('f', 'file') .describe('f', 'Load a file') .string('f') .showHelpOnFail(false, 'Specify --help for available options') .help('help') .argv; // etc. ```` *** ``` $ node line_count.js Missing argument value: f Specify --help for available options ``` <a name="skipValidation"></a>.skipValidation(key) ----------------- Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. .strict([global=true]) --------- Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error. `global` indicates whether `strict()` should be enabled both at the top-level and for each sub-command. <a name="string"></a>.string(key) ------------ Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input. If `key` is an array, interpret all the elements as strings. `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers. .updateLocale(obj) ------------------ .updateStrings(obj) ------------------ Override the default strings used by yargs with the key/value pairs provided in `obj`: ```js var argv = require('yargs') .command('run', 'the run command') .help('help') .updateStrings({ 'Commands:': 'My Commands -->\n' }) .wrap(null) .argv ``` *** ```shell My Commands --> run the run command Options: --help Show help [boolean] ``` If you explicitly specify a `locale()`, you should do so *before* calling `updateStrings()`. .usage(message, [opts]) --------------------- Set a usage message to show which commands to use. Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl. `opts` is optional and acts like calling `.options(opts)`. <a name="version"></a>.version([option], [description], [version]) ---------------------------------------- Add an option (e.g. `--version`) that displays the version number (given by the `version` parameter) and exits the process. If no arguments are passed to `version` (`.version()`), yargs will parse the `package.json` of your module and use its `version` value. The default value of `option` is `--version`. You can provide a `function` for version, rather than a string. This is useful if you want to use a version stored in a location other than package.json: ```js var argv = require('yargs') .version(function() { return require('../lib/version').version; }) .argv; ``` <a name="wrap"></a>.wrap(columns) -------------- Format usage output to wrap at `columns` many columns. By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align). Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions. parsing tricks ============== stop parsing ------------ Use `--` to stop parsing flags and stuff the remainder into `argv._`. $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4 { _: [ '-c', '3', '-d', '4' ], a: 1, b: 2, '$0': 'examples/reflect.js' } negate fields ------------- If you want to explicitly set a field to false instead of just leaving it undefined or to override a default you can do `--no-key`. $ node examples/reflect.js -a --no-b { _: [], a: true, b: false, '$0': 'examples/reflect.js' } numbers ------- Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to one. This way you can just `net.createConnection(argv.port)` and you can add numbers out of `argv` with `+` without having that mean concatenation, which is super frustrating. duplicates ---------- If you specify a flag multiple times it will get turned into an array containing all the values in order. $ node examples/reflect.js -x 5 -x 8 -x 0 { _: [], x: [ 5, 8, 0 ], '$0': 'examples/reflect.js' } dot notation ------------ When you use dots (`.`s) in argument names, an implicit object path is assumed. This lets you organize arguments into nested objects. $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5 { _: [], foo: { bar: { baz: 33 }, quux: 5 }, '$0': 'examples/reflect.js' } short numbers ------------- Short numeric `-n5` style arguments work too: $ node examples/reflect.js -n123 -m456 { _: [], n: 123, m: 456, '$0': 'examples/reflect.js' } installation ============ With [npm](https://github.com/npm/npm), just do: npm install yargs or clone this project on github: git clone http://github.com/yargs/yargs.git To run the tests with npm, just do: npm test configuration ============= Using the `yargs` stanza in your `package.json` you can turn on and off some of yargs' parsing features: ```json { "yargs": { "short-option-groups": true, "camel-case-expansion": true, "dot-notation": true, "parse-numbers": true, "boolean-negation": true } } ``` See the [yargs-parser](https://github.com/yargs/yargs-parser#configuration) module for detailed documentation of this feature. inspired by =========== This module is loosely inspired by Perl's [Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm). [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [coveralls-url]: https://coveralls.io/github/yargs/yargs [coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf [windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [gitter-image]: https://img.shields.io/gitter/room/nwjs/nw.js.svg?maxAge=2592000 [gitter-url]: https://gitter.im/yargs/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # is-typedarray [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) Detect whether or not an object is a [Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). ## Usage [![NPM](https://nodei.co/npm/is-typedarray.png)](https://nodei.co/npm/is-typedarray/) ### isTypedArray(array) Returns `true` when array is a Typed Array, and `false` when it is not. ## License MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. The package exports an array of strings. Each string is an identifier for a license exception under the [Software Package Data Exchange (SPDX)][SPDX] software license metadata standard. [SPDX]: https://spdx.org ## Copyright and Licensing ### SPDX "SPDX" is a federally registered United States trademark of The Linux Foundation Corporation. From version 2.0 of the [SPDX] specification: > Copyright © 2010-2015 Linux Foundation and its Contributors. Licensed > under the Creative Commons Attribution License 3.0 Unported. All other > rights are expressly reserved. The Linux Foundation and the SPDX working groups are good people. Only they decide what "SPDX" means, as a standard and otherwise. I respect their work and their rights. You should, too. ### This Package > I created this package by copying exception identifiers out of the > SPDX specification. That work was mechanical, routine, and required no > creativity whatsoever. - Kyle Mitchell, package author United States users concerned about intellectual property may wish to discuss the following Supreme Court decisions with their attorneys: - _Baker v. Selden_, 101 U.S. 99 (1879) - _Feist Publications, Inc., v. Rural Telephone Service Co._, 499 U.S. 340 (1991) semver(1) -- The semantic versioner for npm =========================================== ## Usage $ npm install semver $ node var semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true As a command-line utility: $ semver -h SemVer 5.1.0 A JavaScript implementation of the http://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ## Versions A "version" is described by the `v2.0.0` specification found at <http://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript > semver.inc('1.2.3', 'prerelease', 'beta') '1.2.4-beta.0' ``` command-line example: ```shell $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```shell $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero digit in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' | ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `loose` boolean argument that, if true, will be more forgiving about not-quite-valid semver strings. The resulting output will always be 100% strict, of course. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. [![Build Status](https://travis-ci.org/samccone/chrome-trace-event.svg?branch=master)](https://travis-ci.org/samccone/chrome-trace-event) chrome-trace-event: A node library for creating trace event logs of program execution according to [Google's Trace Event format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU). These logs can then be visualized with [trace-viewer](https://github.com/google/trace-viewer) or chrome devtools to grok one's programs. # Install npm install chrome-trace-event # Usage ```javascript const Trace = require("chrome-trace-event").Tracer; const trace = new Trace({ noStream: true }); trace.pipe(fs.createWriteStream(outPath)); trace.flush(); ``` # Links * https://github.com/google/trace-viewer/wiki * https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU # License MIT. See LICENSE.txt. # date-now [![build status][1]][2] [![browser support][3]][4] A requirable version of Date.now() Use-case is to be able to mock out Date.now() using require interception. ## Example ```js var now = require("date-now") var ts = now() var ts2 = Date.now() assert.equal(ts, ts2) ``` ## example of seed ``` var now = require("date-now/seed")(timeStampFromServer) // ts is in "sync" with the seed value from the server // useful if your users have their local time being a few minutes // out of your server time. var ts = now() ``` ## Installation `npm install date-now` ## Contributors - Raynos ## MIT Licenced [1]: https://secure.travis-ci.org/Colingo/date-now.png [2]: http://travis-ci.org/Colingo/date-now [3]: http://ci.testling.com/Colingo/date-now.png [4]: http://ci.testling.com/Colingo/date-now # create-hmac [![NPM Package](https://img.shields.io/npm/v/create-hmac.svg?style=flat-square)](https://www.npmjs.org/package/create-hmac) [![Build Status](https://img.shields.io/travis/crypto-browserify/createHmac.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/createHmac) [![Dependency status](https://img.shields.io/david/crypto-browserify/createHmac.svg?style=flat-square)](https://david-dm.org/crypto-browserify/createHmac#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style HMACs for use in the browser, with native HMAC functions in node. API is the same as HMACs in node: ```js var createHmac = require('create-hmac') var hmac = createHmac('sha224', Buffer.from('secret key')) hmac.update('synchronous write') //optional encoding parameter hmac.digest() // synchronously get result with optional encoding parameter hmac.write('write to it as a stream') hmac.end() //remember it's a stream hmac.read() //only if you ended it as a stream though ``` gauge ===== A nearly stateless terminal based horizontal gauge / progress bar. ```javascript var Gauge = require("gauge") var gauge = new Gauge() gauge.show("test", 0.20) gauge.pulse("this") gauge.hide() ``` ![](gauge-demo.gif) ### CHANGES FROM 1.x Gauge 2.x is breaking release, please see the [changelog] for details on what's changed if you were previously a user of this module. [changelog]: CHANGELOG.md ### THE GAUGE CLASS This is the typical interface to the module– it provides a pretty fire-and-forget interface to displaying your status information. ``` var Gauge = require("gauge") var gauge = new Gauge([stream], [options]) ``` * **stream** – *(optional, default STDERR)* A stream that progress bar updates are to be written to. Gauge honors backpressure and will pause most writing if it is indicated. * **options** – *(optional)* An option object. Constructs a new gauge. Gauges are drawn on a single line, and are not drawn if **stream** isn't a tty and a tty isn't explicitly provided. If **stream** is a terminal or if you pass in **tty** to **options** then we will detect terminal resizes and redraw to fit. We do this by watching for `resize` events on the tty. (To work around a bug in verisons of Node prior to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to larger window sizes will be clean, but shrinking the window will always result in some cruft. **IMPORTANT:** If you prevously were passing in a non-tty stream but you still want output (for example, a stream wrapped by the `ansi` module) then you need to pass in the **tty** option below, as `gauge` needs access to the underlying tty in order to do things like terminal resizes and terminal width detection. The **options** object can have the following properties, all of which are optional: * **updateInterval**: How often gauge updates should be drawn, in miliseconds. * **fixedFramerate**: Defaults to false on node 0.8, true on everything else. When this is true a timer is created to trigger once every `updateInterval` ms, when false, updates are printed as soon as they come in but updates more often than `updateInterval` are ignored. The reason 0.8 doesn't have this set to true is that it can't `unref` its timer and so it would stop your program from exiting– if you want to use this feature with 0.8 just make sure you call `gauge.disable()` before you expect your program to exit. * **themes**: A themeset to use when selecting the theme to use. Defaults to `gauge/themes`, see the [themes] documentation for details. * **theme**: Select a theme for use, it can be a: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. * **template**: Describes what you want your gauge to look like. The default is what npm uses. Detailed [documentation] is later in this document. * **hideCursor**: Defaults to true. If true, then the cursor will be hidden while the gauge is displayed. * **tty**: The tty that you're ultimately writing to. Defaults to the same as **stream**. This is used for detecting the width of the terminal and resizes. The width used is `tty.columns - 1`. If no tty is available then a width of `79` is assumed. * **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true the gauge starts enabled. If disabled then all update commands are ignored and no gauge will be printed until you call `.enable()`. * **Plumbing**: The class to use to actually generate the gauge for printing. This defaults to `require('gauge/plumbing')` and ordinarly you shouldn't need to override this. * **cleanupOnExit**: Defaults to true. Ordinarily we register an exit handler to make sure your cursor is turned back on and the progress bar erased when your process exits, even if you Ctrl-C out or otherwise exit unexpectedly. You can disable this and it won't register the exit handler. [has-unicode]: https://www.npmjs.com/package/has-unicode [themes]: #themes [documentation]: #templates #### `gauge.show(section | status, [completed])` The first argument is either the section, the name of the current thing contributing to progress, or an object with keys like **section**, **subsection** & **completed** (or any others you have types for in a custom template). If you don't want to update or set any of these you can pass `null` and it will be ignored. The second argument is the percent completed as a value between 0 and 1. Without it, completion is just not updated. You'll also note that completion can be passed in as part of a status object as the first argument. If both it and the completed argument are passed in, the completed argument wins. #### `gauge.hide([cb])` Removes the gauge from the terminal. Optionally, callback `cb` after IO has had an opportunity to happen (currently this just means after `setImmediate` has called back.) It turns out this is important when you're pausing the progress bar on one filehandle and printing to another– otherwise (with a big enough print) node can end up printing the "end progress bar" bits to the progress bar filehandle while other stuff is printing to another filehandle. These getting interleaved can cause corruption in some terminals. #### `gauge.pulse([subsection])` * **subsection** – *(optional)* The specific thing that triggered this pulse Spins the spinner in the gauge to show output. If **subsection** is included then it will be combined with the last name passed to `gauge.show`. #### `gauge.disable()` Hides the gauge and ignores further calls to `show` or `pulse`. #### `gauge.enable()` Shows the gauge and resumes updating when `show` or `pulse` is called. #### `gauge.isEnabled()` Returns true if the gauge is enabled. #### `gauge.setThemeset(themes)` Change the themeset to select a theme from. The same as the `themes` option used in the constructor. The theme will be reselected from this themeset. #### `gauge.setTheme(theme)` Change the active theme, will be displayed with the next show or pulse. This can be: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. #### `gauge.setTemplate(template)` Change the active template, will be displayed with the next show or pulse ### Tracking Completion If you have more than one thing going on that you want to track completion of, you may find the related [are-we-there-yet] helpful. It's `change` event can be wired up to the `show` method to get a more traditional progress bar interface. [are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet ### THEMES ``` var themes = require('gauge/themes') // fetch the default color unicode theme for this platform var ourTheme = themes({hasUnicode: true, hasColor: true}) // fetch the default non-color unicode theme for osx var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) // create a new theme based on the color ascii theme for this platform // that brackets the progress bar with arrows var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), { preProgressbar: '→', postProgressbar: '←' }) ``` The object returned by `gauge/themes` is an instance of the `ThemeSet` class. ``` var ThemeSet = require('gauge/theme-set') var themes = new ThemeSet() // or var themes = require('gauge/themes') var mythemes = themes.newThemeset() // creates a new themeset based on the default themes ``` #### themes(opts) #### themes.getDefault(opts) Theme objects are a function that fetches the default theme based on platform, unicode and color support. Options is an object with the following properties: * **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is available then a non-unicode theme will be used. * **hasColor** - If true, fetch a color theme, if no color theme is available a non-color theme will be used. * **platform** (optional) - Defaults to `process.platform`. If no platform match is available then `fallback` is used instead. If no compatible theme can be found then an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.addTheme(themeName, themeObj) #### themes.addTheme(themeName, [parentTheme], newTheme) Adds a named theme to the themeset. You can pass in either a theme object, as returned by `themes.newTheme` or the arguments you'd pass to `themes.newTheme`. #### themes.getThemeNames() Return a list of all of the names of the themes in this themeset. Suitable for use in `themes.getTheme(…)`. #### themes.getTheme(name) Returns the theme object from this theme set named `name`. If `name` does not exist in this themeset an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.setDefault([opts], themeName) `opts` is an object with the following properties. * **platform** - Defaults to `'fallback'`. If your theme is platform specific, specify that here with the platform from `process.platform`, eg, `win32`, `darwin`, etc. * **hasUnicode** - Defaults to `false`. If your theme uses unicode you should set this to true. * **hasColor** - Defaults to `false`. If your theme uses color you should set this to true. `themeName` is the name of the theme (as given to `addTheme`) to use for this set of `opts`. #### themes.newTheme([parentTheme,] newTheme) Create a new theme object based on `parentTheme`. If no `parentTheme` is provided then a minimal parentTheme that defines functions for rendering the activity indicator (spinner) and progress bar will be defined. (This fallback parent is defined in `gauge/base-theme`.) newTheme should be a bare object– we'll start by discussing the properties defined by the default themes: * **preProgressbar** - displayed prior to the progress bar, if the progress bar is displayed. * **postProgressbar** - displayed after the progress bar, if the progress bar is displayed. * **progressBarTheme** - The subtheme passed through to the progress bar renderer, it's an object with `complete` and `remaining` properties that are the strings you want repeated for those sections of the progress bar. * **activityIndicatorTheme** - The theme for the activity indicator (spinner), this can either be a string, in which each character is a different step, or an array of strings. * **preSubsection** - Displayed as a separator between the `section` and `subsection` when the latter is printed. More generally, themes can have any value that would be a valid value when rendering templates. The properties in the theme are used when their name matches a type in the template. Their values can be: * **strings & numbers** - They'll be included as is * **function (values, theme, width)** - Should return what you want in your output. *values* is an object with values provided via `gauge.show`, *theme* is the theme specific to this item (see below) or this theme object, and *width* is the number of characters wide your result should be. There are a couple of special prefixes: * **pre** - Is shown prior to the property, if its displayed. * **post** - Is shown after the property, if its displayed. And one special suffix: * **Theme** - Its value is passed to a function-type item as the theme. #### themes.addToAllThemes(theme) This *mixes-in* `theme` into all themes currently defined. It also adds it to the default parent theme for this themeset, so future themes added to this themeset will get the values from `theme` by default. #### themes.newThemeset() Copy the current themeset into a new one. This allows you to easily inherit one themeset from another. ### TEMPLATES A template is an array of objects and strings that, after being evaluated, will be turned into the gauge line. The default template is: ```javascript [ {type: 'progressbar', length: 20}, {type: 'activityIndicator', kerning: 1, length: 1}, {type: 'section', kerning: 1, default: ''}, {type: 'subsection', kerning: 1, default: ''} ] ``` The various template elements can either be **plain strings**, in which case they will be be included verbatum in the output, or objects with the following properties: * *type* can be any of the following plus any keys you pass into `gauge.show` plus any keys you have on a custom theme. * `section` – What big thing you're working on now. * `subsection` – What component of that thing is currently working. * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` from your active theme. * `progressbar` – A progress bar representing your current `completed` using the `progressbarTheme` from your active theme. * *kerning* – Number of spaces that must be between this item and other items, if this item is displayed at all. * *maxLength* – The maximum length for this element. If its value is longer it will be truncated. * *minLength* – The minimum length for this element. If its value is shorter it will be padded according to the *align* value. * *align* – (Default: left) Possible values "left", "right" and "center". Works as you'd expect from word processors. * *length* – Provides a single value for both *minLength* and *maxLength*. If both *length* and *minLength or *maxLength* are specifed then the latter take precedence. * *value* – A literal value to use for this template item. * *default* – A default value to use for this template item if a value wasn't otherwise passed in. ### PLUMBING This is the super simple, assume nothing, do no magic internals used by gauge to implement its ordinary interface. ``` var Plumbing = require('gauge/plumbing') var gauge = new Plumbing(theme, template, width) ``` * **theme**: The theme to use. * **template**: The template to use. * **width**: How wide your gauge should be #### `gauge.setTheme(theme)` Change the active theme. #### `gauge.setTemplate(template)` Change the active template. #### `gauge.setWidth(width)` Change the width to render at. #### `gauge.hide()` Return the string necessary to hide the progress bar #### `gauge.hideCursor()` Return a string to hide the cursor. #### `gauge.showCursor()` Return a string to show the cursor. #### `gauge.show(status)` Using `status` for values, render the provided template with the theme and return a string that is suitable for printing to update the gauge. # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) A robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) and [io.js v1.0.0+](https://github.com/iojs/io.js/blob/v1.x/lib/punycode.js). ## Installation Via [npm](https://www.npmjs.com/) (only required for Node.js releases older than v0.6.2): ```bash npm install punycode ``` Via [Bower](http://bower.io/): ```bash bower install punycode ``` Via [Component](https://github.com/component/component): ```bash component install bestiejs/punycode.js ``` In a browser: ```html <script src="punycode.js"></script> ``` In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/): ```js var punycode = require('punycode'); ``` In [Rhino](http://www.mozilla.org/rhino/): ```js load('punycode.js'); ``` Using an AMD loader like [RequireJS](http://requirejs.org/): ```js require( { 'paths': { 'punycode': 'path/to/punycode' } }, ['punycode'], function(punycode) { console.log(punycode); } ); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Unit tests & code coverage After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. To generate the code coverage report, use `grunt cover`. Feel free to fork if you see possible improvements! ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## Contributors | [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | |---| | [John-David Dalton](http://allyoucanleet.com/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. [![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) ```js var colors = require('color-name'); colors.red //[255,0,0] ``` <a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a> # Brorand #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2014. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # react-lifecycles-compat ## What is this project? React version 17 will deprecate several of the class component API lifecycles: `componentWillMount`, `componentWillReceiveProps`, and `componentWillUpdate`. (Read the [Update on Async rendering blog post](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html) to learn more about why.) A couple of new lifecycles are also being added to better support [async rendering mode](https://reactjs.org/blog/2018/03/01/sneak-peek-beyond-react-16.html). Typically, this type of change would require third party libraries to release a new major version in order to adhere to semver. However, the `react-lifecycles-compat` polyfill offers a way to use the new lifecycles with older versions of React as well (0.14.9+) so no breaking release is required. This enables shared libraries to support both older and newer versions of React simultaneously. ## How can I use the polyfill First, install the polyfill from NPM: ```sh # Yarn yarn add react-lifecycles-compat # NPM npm install react-lifecycles-compat --save ``` Next, update your component and replace any of the deprecated lifecycles with new ones introduced with React 16.3. (Refer to the React docs for [examples of how to use the new lifecycles](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html).) Lastly, use the polyfill to make the new lifecycles work with older versions of React: ```js import React from 'react'; import {polyfill} from 'react-lifecycles-compat'; class ExampleComponent extends React.Component { static getDerivedStateFromProps(nextProps, prevState) { // Normally this method would only work for React 16.3 and newer, // But the polyfill will make it work for older versions also! } getSnapshotBeforeUpdate(prevProps, prevState) { // Normally this method would only work for React 16.3 and newer, // But the polyfill will make it work for older versions also! } // render() and other methods ... } // Polyfill your component so the new lifecycles will work with older versions of React: polyfill(ExampleComponent); export default ExampleComponent; ``` ## Which lifecycles are supported? Currently, this polyfill supports [static `getDerivedStateFromProps`](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops) and [`getSnapshotBeforeUpdate`](https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate)- both introduced in version 16.3. ## Validation Note that in order for the polyfill to work, none of the following lifecycles can be defined by your component: `componentWillMount`, `componentWillReceiveProps`, or `componentWillUpdate`. Note also that if your component contains `getSnapshotBeforeUpdate`, `componentDidUpdate` must be defined as well. An error will be thrown if any of the above conditions are not met. # PostCSS [![Gitter][chat-img]][chat] <img align="right" width="95" height="95" alt="Philosopher’s stone, logo of PostCSS" src="http://postcss.github.io/postcss/logo.svg"> [chat-img]: https://img.shields.io/badge/Gitter-Join_the_PostCSS_chat-brightgreen.svg [chat]: https://gitter.im/postcss/postcss PostCSS is a tool for transforming styles with JS plugins. These plugins can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more. PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, and JetBrains. The [Autoprefixer] PostCSS plugin is one of the most popular CSS processors. PostCSS takes a CSS file and provides an API to analyze and modify its rules (by transforming them into an [Abstract Syntax Tree]). This API can then be used by [plugins] to do a lot of useful things, e.g. to find errors automatically insert vendor prefixes. **Support / Discussion:** [Gitter](https://gitter.im/postcss/postcss)<br> **Twitter account:** [@postcss](https://twitter.com/postcss)<br> **VK.com page:** [postcss](https://vk.com/postcss)<br> **中文翻译**: [`README-cn.md`](./README-cn.md) For PostCSS commercial support (consulting, improving the front-end culture of your company, PostCSS plugins), contact [Evil Martians] at <[email protected]>. [Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree [Evil Martians]: https://evilmartians.com/?utm_source=postcss [Autoprefixer]: https://github.com/postcss/autoprefixer [plugins]: https://github.com/postcss/postcss#plugins <a href="https://evilmartians.com/?utm_source=postcss"> <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg" alt="Sponsored by Evil Martians" width="236" height="54"> </a> ## Plugins Currently, PostCSS has more than 200 plugins. You can find all of the plugins in the [plugins list] or in the [searchable catalog]. Below is a list of our favorite plugins — the best demonstrations of what can be built on top of PostCSS. If you have any new ideas, [PostCSS plugin development] is really easy. [searchable catalog]: http://postcss.parts [plugins list]: https://github.com/postcss/postcss/blob/master/docs/plugins.md ### Solve Global CSS Problem * [`postcss-use`] allows you to explicitly set PostCSS plugins within CSS and execute them only for the current file. * [`postcss-modules`] and [`react-css-modules`] automatically isolate selectors within components. * [`postcss-autoreset`] is an alternative to using a global reset that is better for isolatable components. * [`postcss-initial`] adds `all: initial` support, which resets all inherited styles. * [`cq-prolyfill`] adds container query support, allowing styles that respond to the width of the parent. ### Use Future CSS, Today * [`autoprefixer`] adds vendor prefixes, using data from Can I Use. * [`postcss-preset-env`] allows you to use future CSS features today. ### Better CSS Readability * [`precss`] contains plugins for Sass-like features, like variables, nesting, and mixins. * [`postcss-sorting`] sorts the content of rules and at-rules. * [`postcss-utilities`] includes the most commonly used shortcuts and helpers. * [`short`] adds and extends numerous shorthand properties. ### Images and Fonts * [`postcss-assets`] inserts image dimensions and inlines files. * [`postcss-sprites`] generates image sprites. * [`font-magician`] generates all the `@font-face` rules needed in CSS. * [`postcss-inline-svg`] allows you to inline SVG and customize its styles. * [`postcss-write-svg`] allows you to write simple SVG directly in your CSS. ### Linters * [`stylelint`] is a modular stylesheet linter. * [`stylefmt`] is a tool that automatically formats CSS according `stylelint` rules. * [`doiuse`] lints CSS for browser support, using data from Can I Use. * [`colorguard`] helps you maintain a consistent color palette. ### Other * [`postcss-rtl`] combines both-directional (left-to-right and right-to-left) styles in one CSS file. * [`cssnano`] is a modular CSS minifier. * [`lost`] is a feature-rich `calc()` grid system. * [`rtlcss`] mirrors styles for right-to-left locales. [PostCSS plugin development]: https://github.com/postcss/postcss/blob/master/docs/writing-a-plugin.md [`postcss-inline-svg`]: https://github.com/TrySound/postcss-inline-svg [`postcss-preset-env`]: https://github.com/jonathantneal/postcss-preset-env [`react-css-modules`]: https://github.com/gajus/react-css-modules [`postcss-autoreset`]: https://github.com/maximkoretskiy/postcss-autoreset [`postcss-write-svg`]: https://github.com/jonathantneal/postcss-write-svg [`postcss-utilities`]: https://github.com/ismamz/postcss-utilities [`postcss-initial`]: https://github.com/maximkoretskiy/postcss-initial [`postcss-sprites`]: https://github.com/2createStudio/postcss-sprites [`postcss-modules`]: https://github.com/outpunk/postcss-modules [`postcss-sorting`]: https://github.com/hudochenkov/postcss-sorting [`postcss-assets`]: https://github.com/assetsjs/postcss-assets [`font-magician`]: https://github.com/jonathantneal/postcss-font-magician [`autoprefixer`]: https://github.com/postcss/autoprefixer [`cq-prolyfill`]: https://github.com/ausi/cq-prolyfill [`postcss-rtl`]: https://github.com/vkalinichev/postcss-rtl [`postcss-use`]: https://github.com/postcss/postcss-use [`css-modules`]: https://github.com/css-modules/css-modules [`colorguard`]: https://github.com/SlexAxton/css-colorguard [`stylelint`]: https://github.com/stylelint/stylelint [`stylefmt`]: https://github.com/morishitter/stylefmt [`cssnano`]: http://cssnano.co [`precss`]: https://github.com/jonathantneal/precss [`doiuse`]: https://github.com/anandthakker/doiuse [`rtlcss`]: https://github.com/MohammadYounes/rtlcss [`short`]: https://github.com/jonathantneal/postcss-short [`lost`]: https://github.com/peterramsing/lost ## Syntaxes PostCSS can transform styles in any syntax, not just CSS. If there is not yet support for your favorite syntax, you can write a parser and/or stringifier to extend PostCSS. * [`sugarss`] is a indent-based syntax like Sass or Stylus. * [`postcss-syntax`] switch syntax automatically by file extensions. * [`postcss-html`] parsing styles in `<style>` tags of HTML-like files. * [`postcss-markdown`] parsing styles in code blocks of Markdown files. * [`postcss-jsx`] parsing CSS in template / object literals of source files. * [`postcss-styled`] parsing CSS in template literals of source files. * [`postcss-scss`] allows you to work with SCSS *(but does not compile SCSS to CSS)*. * [`postcss-sass`] allows you to work with Sass *(but does not compile Sass to CSS)*. * [`postcss-less`] allows you to work with Less *(but does not compile LESS to CSS)*. * [`postcss-less-engine`] allows you to work with Less *(and DOES compile LESS to CSS using true Less.js evaluation)*. * [`postcss-js`] allows you to write styles in JS or transform React Inline Styles, Radium or JSS. * [`postcss-safe-parser`] finds and fixes CSS syntax errors. * [`midas`] converts a CSS string to highlighted HTML. [`postcss-less-engine`]: https://github.com/Crunch/postcss-less [`postcss-safe-parser`]: https://github.com/postcss/postcss-safe-parser [`postcss-syntax`]: https://github.com/gucong3000/postcss-syntax [`postcss-html`]: https://github.com/gucong3000/postcss-html [`postcss-markdown`]: https://github.com/gucong3000/postcss-markdown [`postcss-jsx`]: https://github.com/gucong3000/postcss-jsx [`postcss-styled`]: https://github.com/gucong3000/postcss-styled [`postcss-scss`]: https://github.com/postcss/postcss-scss [`postcss-sass`]: https://github.com/AleshaOleg/postcss-sass [`postcss-less`]: https://github.com/webschik/postcss-less [`postcss-js`]: https://github.com/postcss/postcss-js [`sugarss`]: https://github.com/postcss/sugarss [`midas`]: https://github.com/ben-eb/midas ## Articles * [Some things you may think about PostCSS… and you might be wrong](http://julian.io/some-things-you-may-think-about-postcss-and-you-might-be-wrong) * [What PostCSS Really Is; What It Really Does](http://davidtheclark.com/its-time-for-everyone-to-learn-about-postcss) * [PostCSS Guides](http://webdesign.tutsplus.com/series/postcss-deep-dive--cms-889) More articles and videos you can find on [awesome-postcss](https://github.com/jjaderg/awesome-postcss) list. ## Books * [Mastering PostCSS for Web Design](https://www.packtpub.com/web-development/mastering-postcss-web-design) by Alex Libby, Packt. (June 2016) ## Usage You can start using PostCSS in just two steps: 1. Find and add PostCSS extensions for your build tool. 2. [Select plugins] and add them to your PostCSS process. [Select plugins]: http://postcss.parts ### Webpack Use [`postcss-loader`] in `webpack.config.js`: ```js module.exports = { module: { rules: [ { test: /\.css$/, exclude: /node_modules/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', options: { importLoaders: 1, } }, { loader: 'postcss-loader' } ] } ] } } ``` Then create `postcss.config.js`: ```js module.exports = { plugins: [ require('precss'), require('autoprefixer') ] } ``` [`postcss-loader`]: https://github.com/postcss/postcss-loader ### CSS-in-JS The best way to use PostCSS with CSS-in-JS is [`astroturf`]. Add its loader to your `webpack.config.js`: ```js module.exports = { module: { rules: [ { test: /\.css$/, use: ['style-loader', 'postcss-loader'], }, { test: /\.jsx?$/, use: ['babel-loader', 'astroturf/loader'], } ] } } ``` Then create `postcss.config.js`: ```js module.exports = { plugins: [ require('autoprefixer'), require('postcss-nested') ] } ``` [`astroturf`]: https://github.com/4Catalyzer/astroturf ### Gulp Use [`gulp-postcss`] and [`gulp-sourcemaps`]. ```js gulp.task('css', () => { const postcss = require('gulp-postcss') const sourcemaps = require('gulp-sourcemaps') return gulp.src('src/**/*.css') .pipe( sourcemaps.init() ) .pipe( postcss([ require('precss'), require('autoprefixer') ]) ) .pipe( sourcemaps.write('.') ) .pipe( gulp.dest('build/') ) }) ``` [`gulp-sourcemaps`]: https://github.com/floridoo/gulp-sourcemaps [`gulp-postcss`]: https://github.com/postcss/gulp-postcss ### npm run / CLI To use PostCSS from your command-line interface or with npm scripts there is [`postcss-cli`]. ```sh postcss --use autoprefixer -c options.json -o main.css css/*.css ``` [`postcss-cli`]: https://github.com/postcss/postcss-cli ### Browser If you want to compile CSS string in browser (for instance, in live edit tools like CodePen), just use [Browserify] or [webpack]. They will pack PostCSS and plugins files into a single file. To apply PostCSS plugins to React Inline Styles, JSS, Radium and other [CSS-in-JS], you can use [`postcss-js`] and transforms style objects. ```js var postcss = require('postcss-js') var prefixer = postcss.sync([ require('autoprefixer') ]) prefixer({ display: 'flex' }) //=> { display: ['-webkit-box', '-webkit-flex', '-ms-flexbox', 'flex'] } ``` [`postcss-js`]: https://github.com/postcss/postcss-js [Browserify]: http://browserify.org/ [CSS-in-JS]: https://github.com/MicheleBertoli/css-in-js [webpack]: https://webpack.github.io/ ### Runners * **Grunt**: [`grunt-postcss`](https://github.com/nDmitry/grunt-postcss) * **HTML**: [`posthtml-postcss`](https://github.com/posthtml/posthtml-postcss) * **Stylus**: [`poststylus`](https://github.com/seaneking/poststylus) * **Rollup**: [`rollup-plugin-postcss`](https://github.com/egoist/rollup-plugin-postcss) * **Brunch**: [`postcss-brunch`](https://github.com/brunch/postcss-brunch) * **Broccoli**: [`broccoli-postcss`](https://github.com/jeffjewiss/broccoli-postcss) * **Meteor**: [`postcss`](https://atmospherejs.com/juliancwirko/postcss) * **ENB**: [`enb-postcss`](https://github.com/awinogradov/enb-postcss) * **Taskr**: [`taskr-postcss`](https://github.com/lukeed/taskr/tree/master/packages/postcss) * **Start**: [`start-postcss`](https://github.com/start-runner/postcss) * **Connect/Express**: [`postcss-middleware`](https://github.com/jedmao/postcss-middleware) ### JS API For other environments, you can use the JS API: ```js const autoprefixer = require('autoprefixer') const postcss = require('postcss') const precss = require('precss') const fs = require('fs') fs.readFile('src/app.css', (err, css) => { postcss([precss, autoprefixer]) .process(css, { from: 'src/app.css', to: 'dest/app.css' }) .then(result => { fs.writeFile('dest/app.css', result.css, () => true) if ( result.map ) { fs.writeFile('dest/app.css.map', result.map, () => true) } }) }) ``` Read the [PostCSS API documentation] for more details about the JS API. All PostCSS runners should pass [PostCSS Runner Guidelines]. [PostCSS Runner Guidelines]: https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md [PostCSS API documentation]: http://api.postcss.org/postcss.html ### Options Most PostCSS runners accept two parameters: * An array of plugins. * An object of options. Common options: * `syntax`: an object providing a syntax parser and a stringifier. * `parser`: a special syntax parser (for example, [SCSS]). * `stringifier`: a special syntax output generator (for example, [Midas]). * `map`: [source map options]. * `from`: the input file name (most runners set it automatically). * `to`: the output file name (most runners set it automatically). [source map options]: https://github.com/postcss/postcss/blob/master/docs/source-maps.md [Midas]: https://github.com/ben-eb/midas [SCSS]: https://github.com/postcss/postcss-scss ### Treat Warnings as Errors In some situations it might be helpful to fail the build on any warning from PostCSS or one of its plugins. This guarantees that no warnings go unnoticed, and helps to avoid bugs. While there is no option to enable treating warnings as errors, it can easily be done by adding `postcss-fail-on-warn` plugin in the end of PostCSS plugins: ```js module.exports = { plugins: [ require('autoprefixer'), require('postcss-fail-on-warn') ] } ``` ## Editors & IDE Integration ### Atom * [`language-postcss`] adds PostCSS and [SugarSS] highlight. * [`source-preview-postcss`] previews your output CSS in a separate, live pane. [SugarSS]: https://github.com/postcss/sugarss ### Sublime Text * [`Syntax-highlighting-for-PostCSS`] adds PostCSS highlight. [`Syntax-highlighting-for-PostCSS`]: https://github.com/hudochenkov/Syntax-highlighting-for-PostCSS [`source-preview-postcss`]: https://atom.io/packages/source-preview-postcss [`language-postcss`]: https://atom.io/packages/language-postcss ### Vim * [`postcss.vim`] adds PostCSS highlight. [`postcss.vim`]: https://github.com/stephenway/postcss.vim ### WebStorm WebStorm 2016.3 [has] built-in PostCSS support. [has]: https://blog.jetbrains.com/webstorm/2016/08/webstorm-2016-3-early-access-preview/ # to-object-path [![NPM version](https://badge.fury.io/js/to-object-path.svg)](http://badge.fury.io/js/to-object-path) > Create an object path from a list or array of strings. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i to-object-path --save ``` ## Usage ```js var toPath = require('to-object-path'); toPath('foo', 'bar', 'baz'); toPath('foo', ['bar', 'baz']); //=> 'foo.bar.baz' ``` Also supports passing an arguments object (without having to slice args): ```js function foo() return toPath(arguments); } foo('foo', 'bar', 'baz'); foo('foo', ['bar', 'baz']); //=> 'foo.bar.baz' ``` Visit the [example](./example.js) to see how this could be used in an application. ## Related projects * [get-value](https://www.npmjs.com/package/get-value): Use property paths (` a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value) * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://www.npmjs.com/package/has-value) | [homepage](https://github.com/jonschlinkert/has-value) * [omit-value](https://www.npmjs.com/package/omit-value): Omit properties from an object or deeply nested property of an object using object path… [more](https://www.npmjs.com/package/omit-value) | [homepage](https://github.com/jonschlinkert/omit-value) * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value) * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/to-object-path/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on October 28, 2015._ # object-visit [![NPM version](https://img.shields.io/npm/v/object-visit.svg?style=flat)](https://www.npmjs.com/package/object-visit) [![NPM monthly downloads](https://img.shields.io/npm/dm/object-visit.svg?style=flat)](https://npmjs.org/package/object-visit) [![NPM total downloads](https://img.shields.io/npm/dt/object-visit.svg?style=flat)](https://npmjs.org/package/object-visit) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/object-visit.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/object-visit) > Call a specified method on each value in the given object. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save object-visit ``` ## Usage ```js var visit = require('object-visit'); var ctx = { data: {}, set: function (key, value) { if (typeof key === 'object') { visit(ctx, 'set', key); } else { ctx.data[key] = value; } } }; ctx.set('a', 'a'); ctx.set('b', 'b'); ctx.set('c', 'c'); ctx.set({d: {e: 'f'}}); console.log(ctx.data); //=> {a: 'a', b: 'b', c: 'c', d: { e: 'f' }}; ``` ## About ### Related projects * [base-methods](https://www.npmjs.com/package/base-methods): base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/jonschlinkert/base-methods) | [homepage](https://github.com/jonschlinkert/base-methods "base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [collection-visit](https://www.npmjs.com/package/collection-visit): Visit a method over the items in an object, or map visit over the objects… [more](https://github.com/jonschlinkert/collection-visit) | [homepage](https://github.com/jonschlinkert/collection-visit "Visit a method over the items in an object, or map visit over the objects in an array.") * [define-property](https://www.npmjs.com/package/define-property): Define a non-enumerable property on an object. | [homepage](https://github.com/jonschlinkert/define-property "Define a non-enumerable property on an object.") * [map-visit](https://www.npmjs.com/package/map-visit): Map `visit` over an array of objects. | [homepage](https://github.com/jonschlinkert/map-visit "Map `visit` over an array of objects.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 30, 2017._ <p align="center"> <a href="http://gulpjs.com"> <img height="257" width="114" src="https://raw.githubusercontent.com/gulpjs/artwork/master/gulp-2x.png"> </a> </p> # interpret [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Travis Build Status][travis-image]][travis-url] [![AppVeyor Build Status][appveyor-image]][appveyor-url] [![Coveralls Status][coveralls-image]][coveralls-url] [![Gitter chat][gitter-image]][gitter-url] A dictionary of file extensions and associated module loaders. ## What is it This is used by [Liftoff](http://github.com/tkellen/node-liftoff) to automatically require dependencies for configuration files, and by [rechoir](http://github.com/tkellen/node-rechoir) for registering module loaders. ## API ### extensions Map file types to modules which provide a [require.extensions] loader. ```js { '.babel.js': [ { module: '@babel/register', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) hook({ extensions: '.js' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.js' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.js' }); }, }, ], '.babel.ts': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.buble.js': 'buble/register', '.cirru': 'cirru-script/lib/register', '.cjsx': 'node-cjsx/register', '.co': 'coco', '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.coffee.md': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.csv': 'require-csv', '.eg': 'earlgrey/register', '.esm.js': { module: 'esm', register: function(hook) { // register on .js extension due to https://github.com/joyent/node/blob/v0.12.0/lib/module.js#L353 // which only captures the final extension (.babel.js -> .js) var esmLoader = hook(module); require.extensions['.js'] = esmLoader('module')._extensions['.js']; }, }, '.iced': ['iced-coffee-script/register', 'iced-coffee-script'], '.iced.md': 'iced-coffee-script/register', '.ini': 'require-ini', '.js': null, '.json': null, '.json5': 'json5/lib/require', '.jsx': [ { module: '@babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel-core/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'babel/register', register: function(hook) { hook({ extensions: '.jsx' }); }, }, { module: 'node-jsx', register: function(hook) { hook.install({ extension: '.jsx', harmony: true }); }, }, ], '.litcoffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], '.liticed': 'iced-coffee-script/register', '.ls': ['livescript', 'LiveScript'], '.node': null, '.toml': { module: 'toml-require', register: function(hook) { hook.install(); }, }, '.ts': [ 'ts-node/register', 'typescript-node/register', 'typescript-register', 'typescript-require', { module: '@babel/register', register: function(hook) { hook({ extensions: '.ts' }); }, }, ], '.tsx': [ 'ts-node/register', 'typescript-node/register', { module: '@babel/register', register: function(hook) { hook({ extensions: '.tsx' }); }, }, ], '.wisp': 'wisp/engine/node', '.xml': 'require-xml', '.yaml': 'require-yaml', '.yml': 'require-yaml', } ``` ### jsVariants Same as above, but only include the extensions which are javascript variants. ## How to use it Consumers should use the exported `extensions` or `jsVariants` object to determine which module should be loaded for a given extension. If a matching extension is found, consumers should do the following: 1. If the value is null, do nothing. 2. If the value is a string, try to require it. 3. If the value is an object, try to require the `module` property. If successful, the `register` property (a function) should be called with the module passed as the first argument. 4. If the value is an array, iterate over it, attempting step #2 or #3 until one of the attempts does not throw. [require.extensions]: http://nodejs.org/api/globals.html#globals_require_extensions [downloads-image]: http://img.shields.io/npm/dm/interpret.svg [npm-url]: https://www.npmjs.com/package/interpret [npm-image]: http://img.shields.io/npm/v/interpret.svg [travis-url]: https://travis-ci.org/gulpjs/interpret [travis-image]: http://img.shields.io/travis/gulpjs/interpret.svg?label=travis-ci [appveyor-url]: https://ci.appveyor.com/project/gulpjs/interpret [appveyor-image]: https://img.shields.io/appveyor/ci/gulpjs/interpret.svg?label=appveyor [coveralls-url]: https://coveralls.io/r/gulpjs/interpret [coveralls-image]: http://img.shields.io/coveralls/gulpjs/interpret/master.svg [gitter-url]: https://gitter.im/gulpjs/gulp [gitter-image]: https://badges.gitter.im/gulpjs/gulp.svg # arr-flatten [![NPM version](https://img.shields.io/npm/v/arr-flatten.svg?style=flat)](https://www.npmjs.com/package/arr-flatten) [![NPM monthly downloads](https://img.shields.io/npm/dm/arr-flatten.svg?style=flat)](https://npmjs.org/package/arr-flatten) [![NPM total downloads](https://img.shields.io/npm/dt/arr-flatten.svg?style=flat)](https://npmjs.org/package/arr-flatten) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/arr-flatten.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/arr-flatten) [![Windows Build Status](https://img.shields.io/appveyor/ci/jonschlinkert/arr-flatten.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/jonschlinkert/arr-flatten) > Recursively flatten an array or arrays. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save arr-flatten ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install arr-flatten --save ``` ## Usage ```js var flatten = require('arr-flatten'); flatten(['a', ['b', ['c']], 'd', ['e']]); //=> ['a', 'b', 'c', 'd', 'e'] ``` ## Why another flatten utility? I wanted the fastest implementation I could find, with implementation choices that should work for 95% of use cases, but no cruft to cover the other 5%. ## About ### Related projects * [arr-filter](https://www.npmjs.com/package/arr-filter): Faster alternative to javascript's native filter method. | [homepage](https://github.com/jonschlinkert/arr-filter "Faster alternative to javascript's native filter method.") * [arr-union](https://www.npmjs.com/package/arr-union): Combines a list of arrays, returning a single array with unique values, using strict equality… [more](https://github.com/jonschlinkert/arr-union) | [homepage](https://github.com/jonschlinkert/arr-union "Combines a list of arrays, returning a single array with unique values, using strict equality for comparisons.") * [array-each](https://www.npmjs.com/package/array-each): Loop over each item in an array and call the given function on every element. | [homepage](https://github.com/jonschlinkert/array-each "Loop over each item in an array and call the given function on every element.") * [array-unique](https://www.npmjs.com/package/array-unique): Remove duplicate values from an array. Fastest ES5 implementation. | [homepage](https://github.com/jonschlinkert/array-unique "Remove duplicate values from an array. Fastest ES5 implementation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 20 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [lukeed](https://github.com/lukeed) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 05, 2017._ Needle ====== [![NPM](https://nodei.co/npm/needle.png)](https://nodei.co/npm/needle/) The leanest and most handsome HTTP client in the Nodelands. ```js var needle = require('needle'); needle.get('http://www.google.com', function(error, response) { if (!error && response.statusCode == 200) console.log(response.body); }); ``` Callbacks not floating your boat? Needle got your back. ``` js var data = { file: '/home/johnlennon/walrus.png', content_type: 'image/png' }; // the callback is optional, and needle returns a `readableStream` object // that triggers a 'done' event when the request/response process is complete. needle .post('https://my.server.com/foo', data, { multipart: true }) .on('readable', function() { /* eat your chunks */ }) .on('done', function(err, resp) { console.log('Ready-o!'); }) ``` From version 2.0.x up, Promises are also supported. Just call `needle()` directly and you'll get a native Promise object. ```js needle('put', 'https://hacking.the.gibson/login', { password: 'god' }, { json: true }) .then(function(response) { return doSomethingWith(response) }) .catch(function(err) { console.log('Call the locksmith!') }) ``` With only two real dependencies, Needle supports: - HTTP/HTTPS requests, with the usual verbs you would expect - All of Node's native TLS options, such as 'rejectUnauthorized' (see below) - Basic & Digest authentication with auto-detection - Multipart form-data (e.g. file uploads) - HTTP Proxy forwarding, optionally with authentication - Streaming gzip or deflate decompression - Automatic XML & JSON parsing - 301/302/303 redirect following, with fine-grained tuning, and - Streaming non-UTF-8 charset decoding, via `iconv-lite` And yes, Mr. Wayne, it does come in black. This makes Needle an ideal alternative for performing quick HTTP requests in Node, either for API interaction, downloading or uploading streams of data, and so on. If you need OAuth, AWS support or anything fancier, you should check out mikeal's request module. Install ------- ``` $ npm install needle ``` Usage ----- ```js // using promises needle('get', 'https://server.com/posts/12') .then(function(resp) { // ... }) .catch(function(err) { // ... }) }); // with callback needle.get('ifconfig.me/all.json', function(error, response, body) { if (error) throw error; // body is an alias for `response.body`, // that in this case holds a JSON-decoded object. console.log(body.ip_addr); }); // no callback, using streams var out = fs.createWriteStream('logo.png'); needle.get('https://google.com/images/logo.png').pipe(out).on('finish', function() { console.log('Pipe finished!'); }); ``` As you can see, you can use Needle with Promises or without them. When using Promises or when a callback is passed, the response's body will be buffered and written to `response.body`, and the callback will be fired when all of the data has been collected and processed (e.g. decompressed, decoded and/or parsed). When no callback is passed, however, the buffering logic will be skipped but the response stream will still go through Needle's processing pipeline, so you get all the benefits of post-processing while keeping the streamishness we all love from Node. Response pipeline ----------------- Depending on the response's Content-Type, Needle will either attempt to parse JSON or XML streams, or, if a text response was received, will ensure that the final encoding you get is UTF-8. You can also request a gzip/deflated response, which, if sent by the server, will be processed before parsing or decoding is performed. ```js needle.get('http://stackoverflow.com/feeds', { compressed: true }, function(err, resp) { console.log(resp.body); // this little guy won't be a Gzipped binary blob // but a nice object containing all the latest entries }); ``` Or in anti-callback mode, using a few other options: ```js var options = { compressed : true, // sets 'Accept-Encoding' to 'gzip,deflate' follow_max : 5, // follow up to five redirects rejectUnauthorized : true // verify SSL certificate } var stream = needle.get('https://backend.server.com/everything.html', options); // read the chunks from the 'readable' event, so the stream gets consumed. stream.on('readable', function() { while (data = this.read()) { console.log(data.toString()); } }) stream.on('done', function(err) { // if our request had an error, our 'done' event will tell us. if (!err) console.log('Great success!'); }) ``` API --- ### needle(method, url[, data][, options][, callback]) `(> 2.0.x)` Calling `needle()` directly returns a Promise. Besides `method` and `url`, all parameters are optional, although when sending a `post`, `put` or `patch` request you will get an error if `data` is not present. ```js needle('get', 'http://some.url.com') .then(function(resp) { console.log(resp.body) }) .catch(function(err) { console.error(err) }) }) ``` Except from the above, all of Needle's request methods return a Readable stream, and both `options` and `callback` are optional. If passed, the callback will return three arguments: `error`, `response` and `body`, which is basically an alias for `response.body`. ### needle.head(url[, options][, callback]) ```js needle.head('https://my.backend.server.com', { open_timeout: 5000 // if we're not able to open a connection in 5 seconds, boom. }, function(err, resp) { if (err) console.log('Shoot! Something is wrong: ' + err.message) else console.log('Yup, still alive.') }) ``` ### needle.get(url[, options][, callback]) ```js needle.get('google.com/search?q=syd+barrett', function(err, resp) { // if no http:// is found, Needle will automagically prepend it. }); ``` ### needle.post(url, data[, options][, callback]) ```js var options = { headers: { 'X-Custom-Header': 'Bumbaway atuna' } } needle.post('https://my.app.com/endpoint', 'foo=bar', options, function(err, resp) { // you can pass params as a string or as an object. }); ``` ### needle.put(url, data[, options][, callback]) ```js var nested = { params: { are: { also: 'supported' } } } needle.put('https://api.app.com/v2', nested, function(err, resp) { console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella. }); ``` ### needle.patch(url, data[, options][, callback]) Same behaviour as PUT. ### needle.delete(url, data[, options][, callback]) ```js var options = { username: 'fidelio', password: 'x' } needle.delete('https://api.app.com/messages/123', null, options, function(err, resp) { // in this case, data may be null, but you need to explicity pass it. }); ``` ### needle.request(method, url, data[, options][, callback]) Generic request. This not only allows for flexibility, but also lets you perform a GET request with data, in which case will be appended to the request as a query string, unless you pass a `json: true` option (read below). ```js var params = { q : 'a very smart query', page : 2 } needle.request('get', 'forum.com/search', params, function(err, resp) { if (!err && resp.statusCode == 200) console.log(resp.body); // here you go, mister. }); ``` Now, if you set pass `json: true` among the options, Needle won't set your params as a querystring but instead send a JSON representation of your data through the request's body, as well as set the `Content-Type` and `Accept` headers to `application/json`. ```js needle.request('get', 'forum.com/search', params, { json: true }, function(err, resp) { if (resp.statusCode == 200) console.log('It worked!'); }); ``` Events ------ The [Readable stream](https://nodejs.org/api/stream.html#stream_class_stream_readable) object returned by the above request methods emits the following events, in addition to the regular ones (e.g. `end`, `close`, `data`, `pipe`, `readable`). ### Event: `'response'` - `response <http.IncomingMessage>` Emitted when the underlying [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest) emits a response event. This is after the connection is established and the header received, but before any of it is processed (e.g. authorization required or redirect to be followed). No data has been consumed at this point. ### Event: `'redirect'` - `location <String>` Indicates that the a redirect is being followed. This means that the response code was a redirect (`301`, `302`, `303`, `307`) and the given [redirect options](#redirect-options) allowed following the URL received in the `Location` header. ### Event: `'header'` - `statusCode <Integer>` - `headers <Object>` Triggered after the header has been processed, and just before the data is to be consumed. This implies that no redirect was followed and/or authentication header was received. In other words, we got a "valid" response. ### Event: `'done'` (previously 'end') - `exception <Error>` (optional) Emitted when the request/response process has finished, either because all data was consumed or an error ocurred somewhere in between. Unlike a regular stream's `end` event, Needle's `done` will be fired either on success or on failure, which is why the first argument may be an Error object. In other words: ```js var resp = needle.get('something.worthy/of/being/streamed/by/needle'); resp.pipe(someWritableStream); resp.on('done', function(err) { if (err) console.log('An error ocurred: ' + err.message); else console.log('Great success!'); }) ``` ### Event: `'err'` - `exception <Error>` Emitted when an error ocurrs. This should only happen once in the lifecycle of a Needle request. ### Event: `'timeout'` - `type <String>` Emitted when an timeout error occurs. Type can be either 'open', 'response', or 'read'. This will called right before aborting the request, which will also trigger an `err` event, a described above, with an `ECONNRESET` (Socket hang up) exception. Request options --------------- For information about options that've changed, there's always [the changelog](https://github.com/tomas/needle/releases). - `agent` : Uses an [http.Agent](https://nodejs.org/api/http.html#http_class_http_agent) of your choice, instead of the global, default one. Useful for tweaking the behaviour at the connection level, such as when doing tunneling (see below for an example). - `json` : When `true`, sets content type to `application/json` and sends request body as JSON string, instead of a query string. - `open_timeout`: (or `timeout`) Returns error if connection takes longer than X milisecs to establish. Defaults to `10000` (10 secs). `0` means no timeout. - `response_timeout`: Returns error if no response headers are received in X milisecs, counting from when the connection is opened. Defaults to `0` (no response timeout). - `read_timeout`: Returns error if data transfer takes longer than X milisecs, once response headers are received. Defaults to `0` (no timeout). - `follow_max` : (or `follow`) Number of redirects to follow. Defaults to `0`. See below for more redirect options. - `multipart` : Enables multipart/form-data encoding. Defaults to `false`. Use it when uploading files. - `proxy` : Forwards request through HTTP(s) proxy. Eg. `proxy: 'http://user:[email protected]:3128'`. For more advanced proxying/tunneling use a custom `agent`, as described below. - `headers` : Object containing custom HTTP headers for request. Overrides defaults described below. - `auth` : Determines what to do with provided username/password. Options are `auto`, `digest` or `basic` (default). `auto` will detect the type of authentication depending on the response headers. - `stream_length`: When sending streams, this lets you manually set the Content-Length header --if the stream's bytecount is known beforehand--, preventing ECONNRESET (socket hang up) errors on some servers that misbehave when receiving payloads of unknown size. Set it to `0` and Needle will get and set the stream's length for you, or leave unset for the default behaviour, which is no Content-Length header for stream payloads. - `localAddress` : <string>, IP address. Passed to http/https request. Local interface from witch the request should be emitted. Response options ---------------- - `decode_response` : (or `decode`) Whether to decode the text responses to UTF-8, if Content-Type header shows a different charset. Defaults to `true`. - `parse_response` : (or `parse`) Whether to parse XML or JSON response bodies automagically. Defaults to `true`. You can also set this to 'xml' or 'json' in which case Needle will *only* parse the response if the content type matches. - `output` : Dump response output to file. This occurs after parsing and charset decoding is done. - `parse_cookies` : Whether to parse response’s `Set-Cookie` header. Defaults to `true`. If parsed, response cookies will be available at `resp.cookies`. HTTP Header options ------------------- These are basically shortcuts to the `headers` option described above. - `cookies` : Builds and sets a Cookie header from a `{ key: 'value' }` object. - `compressed`: If `true`, sets 'Accept-Encoding' header to 'gzip,deflate', and inflates content if zipped. Defaults to `false`. - `username` : For HTTP basic auth. - `password` : For HTTP basic auth. Requires username to be passed, but is optional. - `accept` : Sets 'Accept' HTTP header. Defaults to `*/*`. - `connection`: Sets 'Connection' HTTP header. Not set by default, unless running Node < 0.11.4 in which case it defaults to `close`. More info about this below. - `user_agent`: Sets the 'User-Agent' HTTP header. Defaults to `Needle/{version} (Node.js {node_version})`. - `content_type`: Sets the 'Content-Type' header. Unset by default, unless you're sending data in which case it's set accordingly to whatever is being sent (`application/x-www-form-urlencoded`, `application/json` or `multipart/form-data`). That is, of course, unless the option is passed, either here or through `options.headers`. You're the boss. Node.js TLS Options ------------------- These options are passed directly to `https.request` if present. Taken from the [original documentation](http://nodejs.org/docs/latest/api/https.html): - `pfx` : Certificate, Private key and CA certificates to use for SSL. - `key` : Private key to use for SSL. - `passphrase` : A string of passphrase for the private key or pfx. - `cert` : Public x509 certificate to use. - `ca` : An authority certificate or array of authority certificates to check the remote host against. - `ciphers` : A string describing the ciphers to use or exclude. - `rejectUnauthorized` : If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. - `secureProtocol` : The SSL method to use, e.g. SSLv3_method to force SSL version 3. Redirect options ---------------- These options only apply if the `follow_max` (or `follow`) option is higher than 0. - `follow_set_cookies` : Sends the cookies received in the `set-cookie` header as part of the following request. `false` by default. - `follow_set_referer` : Sets the 'Referer' header to the requested URI when following a redirect. `false` by default. - `follow_keep_method` : If enabled, resends the request using the original verb instead of being rewritten to `get` with no data. `false` by default. - `follow_if_same_host` : When true, Needle will only follow redirects that point to the same host as the original request. `false` by default. - `follow_if_same_protocol` : When true, Needle will only follow redirects that point to the same protocol as the original request. `false` by default. Overriding Defaults ------------------- Yes sir, we have it. Needle includes a `defaults()` method, that lets you override some of the defaults for all future requests. Like this: ```js needle.defaults({ open_timeout: 60000, user_agent: 'MyApp/1.2.3', parse_response: false }); ``` This will override Needle's default user agent and 10-second timeout, and disable response parsing, so you don't need to pass those options in every other request. More advanced Proxy support --------------------------- Since you can pass a custom HTTPAgent to Needle you can do all sorts of neat stuff. For example, if you want to use the [`tunnel`](https://github.com/koichik/node-tunnel) module for HTTPS proxying, you can do this: ```js var tunnel = require('tunnel'); var myAgent = tunnel.httpOverHttp({ proxy: { host: 'localhost' } }); needle.get('foobar.com', { agent: myAgent }); ``` Regarding the 'Connection' header --------------------------------- Unless you're running an old version of Node (< 0.11.4), by default Needle won't set the Connection header on requests, yielding Node's default behaviour of keeping the connection alive with the target server. This speeds up inmensely the process of sending several requests to the same host. On older versions, however, this has the unwanted behaviour of preventing the runtime from exiting, either because of a bug or 'feature' that was changed on 0.11.4. To overcome this Needle does set the 'Connection' header to 'close' on those versions, however this also means that making new requests to the same host doesn't benefit from Keep-Alive. So if you're stuck on 0.10 or even lower and want full speed, you can simply set the Connection header to 'Keep-Alive' by using `{ connection: 'Keep-Alive' }`. Please note, though, that an event loop handler will prevent the runtime from exiting so you'll need to manually call `process.exit()` or the universe will collapse. Examples Galore --------------- ### HTTPS GET with Basic Auth ```js needle.get('https://api.server.com', { username: 'you', password: 'secret' }, function(err, resp) { // used HTTP auth }); ``` Or use [RFC-1738](http://tools.ietf.org/html/rfc1738#section-3.1) basic auth URL syntax: ```js needle.get('https://username:[email protected]', function(err, resp) { // used HTTP auth from URL }); ``` ### Digest Auth ```js needle.get('other.server.com', { username: 'you', password: 'secret', auth: 'digest' }, function(err, resp, body) { // needle prepends 'http://' to your URL, if missing }); ``` ### Custom Accept header, deflate ```js var options = { compressed : true, follow : 10, accept : 'application/vnd.github.full+json' } needle.get('api.github.com/users/tomas', options, function(err, resp, body) { // body will contain a JSON.parse(d) object // if parsing fails, you'll simply get the original body }); ``` ### GET XML object ```js needle.get('https://news.ycombinator.com/rss', function(err, resp, body) { // you'll get a nice object containing the nodes in the RSS }); ``` ### GET binary, output to file ```js needle.get('http://upload.server.com/tux.png', { output: '/tmp/tux.png' }, function(err, resp, body) { // you can dump any response to a file, not only binaries. }); ``` ### GET through proxy ```js needle.get('http://search.npmjs.org', { proxy: 'http://localhost:1234' }, function(err, resp, body) { // request passed through proxy }); ``` ### GET a very large document in a stream (from 0.7+) ```js var stream = needle.get('http://www.as35662.net/100.log'); stream.on('readable', function() { var chunk; while (chunk = this.read()) { console.log('got data: ', chunk); } }); ``` ### GET JSON object in a stream (from 0.7+) ```js var stream = needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }); stream.on('readable', function() { var node; // our stream will only emit a single JSON root node. while (node = this.read()) { console.log('got data: ', node); } }); ``` ### GET JSONStream flexible parser with search query (from 0.7+) ```js // The 'data' element of this stream will be the string representation // of the titles of all posts. needle.get('http://jsonplaceholder.typicode.com/db', { parse: true }) .pipe(new JSONStream.parse('posts.*.title')); .on('data', function (obj) { console.log('got post title: %s', obj); }); ``` ### File upload using multipart, passing file path ```js var data = { foo: 'bar', image: { file: '/home/tomas/linux.png', content_type: 'image/png' } } needle.post('http://my.other.app.com', data, { multipart: true }, function(err, resp, body) { // needle will read the file and include it in the form-data as binary }); ``` ### Stream upload, PUT or POST ``` js needle.put('https://api.app.com/v2', fs.createReadStream('myfile.txt'), function(err, resp, body) { // stream content is uploaded verbatim }); ``` ### Multipart POST, passing data buffer ```js var buffer = fs.readFileSync('/path/to/package.zip'); var data = { zip_file: { buffer : buffer, filename : 'mypackage.zip', content_type : 'application/octet-stream' } } needle.post('http://somewhere.com/over/the/rainbow', data, { multipart: true }, function(err, resp, body) { // if you see, when using buffers we need to pass the filename for the multipart body. // you can also pass a filename when using the file path method, in case you want to override // the default filename to be received on the other end. }); ``` ### Multipart with custom Content-Type ```js var data = { token: 'verysecret', payload: { value: JSON.stringify({ title: 'test', version: 1 }), content_type: 'application/json' } } needle.post('http://test.com/', data, { timeout: 5000, multipart: true }, function(err, resp, body) { // in this case, if the request takes more than 5 seconds // the callback will return a [Socket closed] error }); ``` For even more examples, check out the examples directory in the repo. ### Testing To run tests, you need to generate a self-signed SSL certificate in the `test` directory. After cloning the repository, run the following commands: $ mkdir -p test/keys $ openssl genrsa -out test/keys/ssl.key 2048 $ openssl req -new -key test/keys/ssl.key -x509 -days 999 -out test/keys/ssl.cert Then you should be able to run `npm test` once you have the dependencies in place. > Note: Tests currently only work on linux-based environments that have `/proc/self/fd`. They *do not* work on MacOS environments. > You can use Docker to run tests by creating a container and mounting the needle project directory on `/app` > `docker create --name Needle -v /app -w /app -v /app/node_modules -i node:argon` Credits ------- Written by Tomás Pollak, with the help of contributors. Copyright --------- (c) Fork Ltd. Licensed under the MIT license. # iferr Higher-order functions for easier error handling. `if (err) return cb(err);` be gone! ## Install ```bash npm install iferr ``` ## Use ### JavaScript example ```js var iferr = require('iferr'); function get_friends_count(id, cb) { User.load_user(id, iferr(cb, function(user) { user.load_friends(iferr(cb, function(friends) { cb(null, friends.length); })); })); } ``` ### CoffeeScript example ```coffee iferr = require 'iferr' get_friends_count = (id, cb) -> User.load_user id, iferr cb, (user) -> user.load_friends iferr cb, (friends) -> cb null, friends.length ``` (TODO: document tiferr, throwerr and printerr) ## License MIT # SockJS-client [![npm version](https://img.shields.io/npm/v/sockjs-client.svg?style=flat-square)](https://www.npmjs.com/package/sockjs-client)[![Build Status](https://img.shields.io/travis/sockjs/sockjs-client/master.svg?style=flat-square)](https://travis-ci.org/sockjs/sockjs-client)[![Dependencies](https://img.shields.io/david/sockjs/sockjs-client.svg?style=flat-square)](https://david-dm.org/sockjs/sockjs-client)[![Chat](https://img.shields.io/badge/Chat-gitter.im-blue.svg?style=flat-square)](https://gitter.im/sockjs/sockjs-client) [![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=dW9YdlFsSEI5VzNBVVk5ZS9XT0xaTjJVQkhQMkRkNlZBQURiSWNWMC9jaz0tLXRJM05RbW1tTCt5TlhHaVgycFJUYmc9PQ==--e3ef9b9a9fa071084e6d87874b5fc65b71273821)](https://www.browserstack.com/automate/public-build/dW9YdlFsSEI5VzNBVVk5ZS9XT0xaTjJVQkhQMkRkNlZBQURiSWNWMC9jaz0tLXRJM05RbW1tTCt5TlhHaVgycFJUYmc9PQ==--e3ef9b9a9fa071084e6d87874b5fc65b71273821) SockJS is a browser JavaScript library that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server. Under the hood SockJS tries to use native WebSockets first. If that fails it can use a variety of browser-specific transport protocols and presents them through WebSocket-like abstractions. SockJS is intended to work for all modern browsers and in environments which don't support the WebSocket protocol -- for example, behind restrictive corporate proxies. SockJS-client does require a server counterpart: * [SockJS-node](https://github.com/sockjs/sockjs-node) is a SockJS server for Node.js. Philosophy: * The API should follow [HTML5 Websockets API](https://www.w3.org/TR/websockets/) as closely as possible. * All the transports must support cross domain connections out of the box. It's possible and recommended to host a SockJS server on a different server than your main web site. * There is support for at least one streaming protocol for every major browser. * Streaming transports should work cross-domain and should support cookies (for cookie-based sticky sessions). * Polling transports are used as a fallback for old browsers and hosts behind restrictive proxies. * Connection establishment should be fast and lightweight. * No Flash inside (no need to open port 843 - which doesn't work through proxies, no need to host 'crossdomain.xml', no need [to wait for 3 seconds](https://github.com/gimite/web-socket-js/issues/49) in order to detect problems) Subscribe to [SockJS mailing list](https://groups.google.com/forum/#!forum/sockjs) for discussions and support. SockJS family: * [SockJS-client](https://github.com/sockjs/sockjs-client) JavaScript client library * [SockJS-node](https://github.com/sockjs/sockjs-node) Node.js server * [SockJS-erlang](https://github.com/sockjs/sockjs-erlang) Erlang server * [SockJS-cyclone](https://github.com/flaviogrossi/sockjs-cyclone) Python/Cyclone/Twisted server * [SockJS-tornado](https://github.com/MrJoes/sockjs-tornado) Python/Tornado server * [SockJS-twisted](https://github.com/DesertBus/sockjs-twisted/) Python/Twisted server * [SockJS-aiohttp](https://github.com/aio-libs/sockjs/) Python/Aiohttp server * [Spring Framework](https://projects.spring.io/spring-framework) Java [client](https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/web.html#websocket-fallback-sockjs-client) & server * [vert.x](https://github.com/vert-x/vert.x) Java/vert.x server * [Xitrum](https://xitrum-framework.github.io/) Scala server * [Atmosphere Framework](https://github.com/Atmosphere/atmosphere) JavaEE Server, Play Framework, Netty, Vert.x * [Actix SockJS](https://github.com/fafhrd91/actix-sockjs) Rust Server, Actix Framework Work in progress: * [SockJS-ruby](https://github.com/nyarly/sockjs-ruby) * [SockJS-netty](https://github.com/cgbystrom/sockjs-netty) * [SockJS-gevent](https://github.com/ksava/sockjs-gevent) ([SockJS-gevent fork](https://github.com/njoyce/sockjs-gevent)) * [pyramid-SockJS](https://github.com/fafhrd91/pyramid_sockjs) * [wildcloud-websockets](https://github.com/wildcloud/wildcloud-websockets) * [wai-SockJS](https://github.com/Palmik/wai-sockjs) * [SockJS-perl](https://github.com/vti/sockjs-perl) * [SockJS-go](https://github.com/igm/sockjs-go/) Getting Started ------- SockJS mimics the [WebSockets API](https://www.w3.org/TR/websockets/), but instead of `WebSocket` there is a `SockJS` Javascript object. First, you need to load the SockJS JavaScript library. For example, you can put that in your HTML head: ```html <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> ``` After the script is loaded you can establish a connection with the SockJS server. Here's a simple example: ```javascript var sock = new SockJS('https://mydomain.com/my_prefix'); sock.onopen = function() { console.log('open'); sock.send('test'); }; sock.onmessage = function(e) { console.log('message', e.data); sock.close(); }; sock.onclose = function() { console.log('close'); }; ``` SockJS-client API ----------------- ### SockJS class Similar to the 'WebSocket' API, the 'SockJS' constructor takes one, or more arguments: ```javascript var sockjs = new SockJS(url, _reserved, options); ``` `url` may contain a query string, if one is desired. Where `options` is a hash which can contain: * **server (string)** String to append to url for actual data connection. Defaults to a random 4 digit number. * **transports (string OR array of strings)** Sometimes it is useful to disable some fallback transports. This option allows you to supply a list transports that may be used by SockJS. By default all available transports will be used. * **sessionId (number OR function)** Both client and server use session identifiers to distinguish connections. If you specify this option as a number, SockJS will use its random string generator function to generate session ids that are N-character long (where N corresponds to the number specified by **sessionId**). When you specify this option as a function, the function must return a randomly generated string. Every time SockJS needs to generate a session id it will call this function and use the returned string directly. If you don't specify this option, the default is to use the default random string generator to generate 8-character long session ids. Although the 'SockJS' object tries to emulate the 'WebSocket' behaviour, it's impossible to support all of its features. An important SockJS limitation is the fact that you're not allowed to open more than one SockJS connection to a single domain at a time. This limitation is caused by an in-browser limit of outgoing connections - usually [browsers don't allow opening more than two outgoing connections to a single domain](https://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser). A single SockJS session requires those two connections - one for downloading data, the other for sending messages. Opening a second SockJS session at the same time would most likely block, and can result in both sessions timing out. Opening more than one SockJS connection at a time is generally a bad practice. If you absolutely must do it, you can use multiple subdomains, using a different subdomain for every SockJS connection. Supported transports, by browser (html served from http:// or https://) ----------------------------------------------------------------------- _Browser_ | _Websockets_ | _Streaming_ | _Polling_ ----------------|------------------|-------------|------------------- IE 6, 7 | no | no | jsonp-polling IE 8, 9 (cookies=no) | no | xdr-streaming &dagger; | xdr-polling &dagger; IE 8, 9 (cookies=yes)| no | iframe-htmlfile | iframe-xhr-polling IE 10 | rfc6455 | xhr-streaming | xhr-polling Chrome 6-13 | hixie-76 | xhr-streaming | xhr-polling Chrome 14+ | hybi-10 / rfc6455| xhr-streaming | xhr-polling Firefox <10 | no &Dagger; | xhr-streaming | xhr-polling Firefox 10+ | hybi-10 / rfc6455| xhr-streaming | xhr-polling Safari 5.x | hixie-76 | xhr-streaming | xhr-polling Safari 6+ | rfc6455 | xhr-streaming | xhr-polling Opera 10.70+ | no &Dagger; | iframe-eventsource | iframe-xhr-polling Opera 12.10+ | rfc6455 | xhr-streaming | xhr-polling Konqueror | no | no | jsonp-polling * **&dagger;**: IE 8+ supports [XDomainRequest][^9], which is essentially a modified AJAX/XHR that can do requests across domains. But unfortunately it doesn't send any cookies, which makes it inappropriate for deployments when the load balancer uses JSESSIONID cookie to do sticky sessions. * **&Dagger;**: Firefox 4.0 and Opera 11.00 and shipped with disabled Websockets "hixie-76". They can still be enabled by manually changing a browser setting. Supported transports, by browser (html served from file://) ----------------------------------------------------------- Sometimes you may want to serve your html from "file://" address - for development or if you're using PhoneGap or similar technologies. But due to the Cross Origin Policy files served from "file://" have no Origin, and that means some of SockJS transports won't work. For this reason the SockJS transport table is different than usually, major differences are: _Browser_ | _Websockets_ | _Streaming_ | _Polling_ ----------------|---------------|--------------------|------------------- IE 8, 9 | same as above | iframe-htmlfile | iframe-xhr-polling Other | same as above | iframe-eventsource | iframe-xhr-polling Supported transports, by name ----------------------------- _Transport_ | _References_ ---------------------|--------------- websocket (rfc6455) | [rfc 6455][^10] websocket (hixie-76) | [draft-hixie-thewebsocketprotocol-76][^1] websocket (hybi-10) | [draft-ietf-hybi-thewebsocketprotocol-10][^2] xhr-streaming | Transport using [Cross domain XHR][^5] [streaming][^7] capability (readyState=3). xdr-streaming | Transport using [XDomainRequest][^9] [streaming][^7] capability (readyState=3). eventsource | [EventSource/Server-sent events][^4]. iframe-eventsource | [EventSource/Server-sent events][^4] used from an [iframe via postMessage][^3]. htmlfile | [HtmlFile][^8]. iframe-htmlfile | [HtmlFile][^8] used from an [iframe via postMessage][^3]. xhr-polling | Long-polling using [cross domain XHR][^5]. xdr-polling | Long-polling using [XDomainRequest][^9]. iframe-xhr-polling | Long-polling using normal AJAX from an [iframe via postMessage][^3]. jsonp-polling | Slow and old fashioned [JSONP polling][^6]. This transport will show "busy indicator" (aka: "spinning wheel") when sending data. [^1]: https://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76 [^2]: https://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10 [^3]: https://developer.mozilla.org/en/DOM/window.postMessage [^4]: https://html.spec.whatwg.org/multipage/comms.html#server-sent-events [^5]: https://secure.wikimedia.org/wikipedia/en/wiki/XMLHttpRequest#Cross-domain_requests [^6]: https://secure.wikimedia.org/wikipedia/en/wiki/JSONP [^7]: http://www.debugtheweb.com/test/teststreaming.aspx [^8]: http://cometdaily.com/2007/11/18/ie-activexhtmlfile-transport-part-ii/ [^9]: https://blogs.msdn.microsoft.com/ieinternals/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds/ [^10]: https://www.rfc-editor.org/rfc/rfc6455.txt Connecting to SockJS without the client --------------------------------------- Although the main point of SockJS is to enable browser-to-server connectivity, it is possible to connect to SockJS from an external application. Any SockJS server complying with 0.3 protocol does support a raw WebSocket url. The raw WebSocket url for the test server looks like: * ws://localhost:8081/echo/websocket You can connect any WebSocket RFC 6455 compliant WebSocket client to this url. This can be a command line client, external application, third party code or even a browser (though I don't know why you would want to do so). Deployment ---------- You should use a version of sockjs-client that supports the protocol used by your server. For example: ```html <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script> ``` For server-side deployment tricks, especially about load balancing and session stickiness, take a look at the [SockJS-node readme](https://github.com/sockjs/sockjs-node#readme). Development and testing ----------------------- SockJS-client needs [node.js](https://nodejs.org/) for running a test server and JavaScript minification. If you want to work on SockJS-client source code, checkout the git repo and follow these steps: cd sockjs-client npm install To generate JavaScript, run: gulp browserify To generate minified JavaScript, run: gulp browserify:min Both commands output into the `build` directory. ### Testing Automated testing provided by: <a href="https://browserstack.com"><img src="img/[email protected]" height="50"></a> Once you've compiled the SockJS-client you may want to check if your changes pass all the tests. npm run test:browser_local This will start [karma](https://karma-runner.github.io) and a test support server. Browser Quirks -------------- There are various browser quirks which we don't intend to address: * Pressing ESC in Firefox, before Firefox 20, closes the SockJS connection. For a workaround and discussion see [#18](https://github.com/sockjs/sockjs-client/issues/18). * `jsonp-polling` transport will show a "spinning wheel" (aka. "busy indicator") when sending data. * You can't open more than one SockJS connection to one domain at the same time due to [the browser's limit of concurrent connections](https://stackoverflow.com/questions/985431/max-parallel-http-connections-in-a-browser) (this limit is not counting native WebSocket connections). * Although SockJS is trying to escape any strange Unicode characters (even invalid ones - [like surrogates \xD800-\xDBFF](https://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates) or [\xFFFE and \xFFFF](https://en.wikipedia.org/wiki/Unicode#Character_General_Category)) it's advisable to use only valid characters. Using invalid characters is a bit slower, and may not work with SockJS servers that have proper Unicode support. * Having a global function called `onmessage` or such is probably a bad idea, as it could be called by the built-in `postMessage` API. * From SockJS' point of view there is nothing special about SSL/HTTPS. Connecting between unencrypted and encrypted sites should work just fine. * Although SockJS does its best to support both prefix and cookie based sticky sessions, the latter may not work well cross-domain with browsers that don't accept third-party cookies by default (Safari). In order to get around this make sure you're connecting to SockJS from the same parent domain as the main site. For example 'sockjs.a.com' is able to set cookies if you're connecting from 'www.a.com' or 'a.com'. * Trying to connect from secure "https://" to insecure "http://" is not a good idea. The other way around should be fine. * Long polling is known to cause problems on Heroku, but a [workaround for SockJS is available](https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187). * SockJS [websocket transport is more stable over SSL](https://github.com/sockjs/sockjs-client/issues/94). If you're a serious SockJS user then consider using SSL ([more info](https://www.ietf.org/mail-archive/web/hybi/current/msg01605.html)). # unicode-match-property-value-ecmascript [![Build status](https://travis-ci.org/mathiasbynens/unicode-match-property-value-ecmascript.svg?branch=master)](https://travis-ci.org/mathiasbynens/unicode-match-property-value-ecmascript) _unicode-match-property-value-ecmascript_ matches a given Unicode property value or [property value alias](https://github.com/mathiasbynens/unicode-property-value-aliases) to its canonical property value without applying [loose matching](https://github.com/mathiasbynens/unicode-loose-match), per the algorithm used for [RegExp Unicode property escapes in ECMAScript](https://github.com/tc39/proposal-regexp-unicode-property-escapes). Consider it a strict alternative to loose matching. ## Installation To use _unicode-match-property-value-ecmascript_ programmatically, install it as a dependency via [npm](https://www.npmjs.com/): ```bash $ npm install unicode-match-property-value-ecmascript ``` Then, `require` it: ```js const matchPropertyValue = require('unicode-match-property-value-ecmascript'); ``` ## API This module exports a single function named `matchPropertyValue`. ### `matchPropertyValue(property, value)` This function takes a string `property` that is a canonical/unaliased Unicode property name, and a string `value`. It attemps to match `value` to a canonical Unicode property value for the given property. If there’s a match, it returns the canonical property value. Otherwise, it throws an exception. ```js // Find the canonical property value: matchPropertyValue('Script_Extensions', 'Aghb') // → 'Caucasian_Albanian' matchPropertyValue('Script_Extensions', 'Caucasian_Albanian') // → 'Caucasian_Albanian' matchPropertyValue('script_extensions', 'Caucasian_Albanian') // Note: incorrect casing. // → throws matchPropertyValue('Script_Extensions', 'caucasian_albanian') // Note: incorrect casing. // → throws ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _unicode-match-property-value-ecmascript_ is available under the [MIT](https://mths.be/mit) license. These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv-keywords folder. # arr-union [![NPM version](https://img.shields.io/npm/v/arr-union.svg)](https://www.npmjs.com/package/arr-union) [![Build Status](https://img.shields.io/travis/jonschlinkert/arr-union.svg)](https://travis-ci.org/jonschlinkert/arr-union) > Combines a list of arrays, returning a single array with unique values, using strict equality for comparisons. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm i arr-union --save ``` ## Benchmarks This library is **10-20 times faster** and more performant than [array-union](https://github.com/sindresorhus/array-union). See the [benchmarks](./benchmark). ```sh #1: five-arrays array-union x 511,121 ops/sec ±0.80% (96 runs sampled) arr-union x 5,716,039 ops/sec ±0.86% (93 runs sampled) #2: ten-arrays array-union x 245,196 ops/sec ±0.69% (94 runs sampled) arr-union x 1,850,786 ops/sec ±0.84% (97 runs sampled) #3: two-arrays array-union x 563,869 ops/sec ±0.97% (94 runs sampled) arr-union x 9,602,852 ops/sec ±0.87% (92 runs sampled) ``` ## Usage ```js var union = require('arr-union'); union(['a'], ['b', 'c'], ['d', 'e', 'f']); //=> ['a', 'b', 'c', 'd', 'e', 'f'] ``` Returns only unique elements: ```js union(['a', 'a'], ['b', 'c']); //=> ['a', 'b', 'c'] ``` ## Related projects * [arr-diff](https://www.npmjs.com/package/arr-diff): Returns an array with only the unique values from the first array, by excluding all… [more](https://www.npmjs.com/package/arr-diff) | [homepage](https://github.com/jonschlinkert/arr-diff) * [arr-filter](https://www.npmjs.com/package/arr-filter): Faster alternative to javascript's native filter method. | [homepage](https://github.com/jonschlinkert/arr-filter) * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten) * [arr-map](https://www.npmjs.com/package/arr-map): Faster, node.js focused alternative to JavaScript's native array map. | [homepage](https://github.com/jonschlinkert/arr-map) * [arr-pluck](https://www.npmjs.com/package/arr-pluck): Retrieves the value of a specified property from all elements in the collection. | [homepage](https://github.com/jonschlinkert/arr-pluck) * [arr-reduce](https://www.npmjs.com/package/arr-reduce): Fast array reduce that also loops over sparse elements. | [homepage](https://github.com/jonschlinkert/arr-reduce) * [array-unique](https://www.npmjs.com/package/array-unique): Return an array free of duplicate values. Fastest ES5 implementation. | [homepage](https://github.com/jonschlinkert/array-unique) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/arr-union/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm i verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016 [Jon Schlinkert](https://github.com/jonschlinkert) Released under the [MIT license](https://github.com/jonschlinkert/arr-union/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on February 23, 2016._ sshpk ========= Parse, convert, fingerprint and use SSH keys (both public and private) in pure node -- no `ssh-keygen` or other external dependencies. Supports RSA, DSA, ECDSA (nistp-\*) and ED25519 key types, in PEM (PKCS#1, PKCS#8) and OpenSSH formats. This library has been extracted from [`node-http-signature`](https://github.com/joyent/node-http-signature) (work by [Mark Cavage](https://github.com/mcavage) and [Dave Eddy](https://github.com/bahamas10)) and [`node-ssh-fingerprint`](https://github.com/bahamas10/node-ssh-fingerprint) (work by Dave Eddy), with additions (including ECDSA support) by [Alex Wilson](https://github.com/arekinath). Install ------- ``` npm install sshpk ``` Examples -------- ```js var sshpk = require('sshpk'); var fs = require('fs'); /* Read in an OpenSSH-format public key */ var keyPub = fs.readFileSync('id_rsa.pub'); var key = sshpk.parseKey(keyPub, 'ssh'); /* Get metadata about the key */ console.log('type => %s', key.type); console.log('size => %d bits', key.size); console.log('comment => %s', key.comment); /* Compute key fingerprints, in new OpenSSH (>6.7) format, and old MD5 */ console.log('fingerprint => %s', key.fingerprint().toString()); console.log('old-style fingerprint => %s', key.fingerprint('md5').toString()); ``` Example output: ``` type => rsa size => 2048 bits comment => [email protected] fingerprint => SHA256:PYC9kPVC6J873CSIbfp0LwYeczP/W4ffObNCuDJ1u5w old-style fingerprint => a0:c8:ad:6c:32:9a:32:fa:59:cc:a9:8c:0a:0d:6e:bd ``` More examples: converting between formats: ```js /* Read in a PEM public key */ var keyPem = fs.readFileSync('id_rsa.pem'); var key = sshpk.parseKey(keyPem, 'pem'); /* Convert to PEM PKCS#8 public key format */ var pemBuf = key.toBuffer('pkcs8'); /* Convert to SSH public key format (and return as a string) */ var sshKey = key.toString('ssh'); ``` Signing and verifying: ```js /* Read in an OpenSSH/PEM *private* key */ var keyPriv = fs.readFileSync('id_ecdsa'); var key = sshpk.parsePrivateKey(keyPriv, 'pem'); var data = 'some data'; /* Sign some data with the key */ var s = key.createSign('sha1'); s.update(data); var signature = s.sign(); /* Now load the public key (could also use just key.toPublic()) */ var keyPub = fs.readFileSync('id_ecdsa.pub'); key = sshpk.parseKey(keyPub, 'ssh'); /* Make a crypto.Verifier with this key */ var v = key.createVerify('sha1'); v.update(data); var valid = v.verify(signature); /* => true! */ ``` Matching fingerprints with keys: ```js var fp = sshpk.parseFingerprint('SHA256:PYC9kPVC6J873CSIbfp0LwYeczP/W4ffObNCuDJ1u5w'); var keys = [sshpk.parseKey(...), sshpk.parseKey(...), ...]; keys.forEach(function (key) { if (fp.matches(key)) console.log('found it!'); }); ``` Usage ----- ## Public keys ### `parseKey(data[, format = 'auto'[, options]])` Parses a key from a given data format and returns a new `Key` object. Parameters - `data` -- Either a Buffer or String, containing the key - `format` -- String name of format to use, valid options are: - `auto`: choose automatically from all below - `pem`: supports both PKCS#1 and PKCS#8 - `ssh`: standard OpenSSH format, - `pkcs1`, `pkcs8`: variants of `pem` - `rfc4253`: raw OpenSSH wire format - `openssh`: new post-OpenSSH 6.5 internal format, produced by `ssh-keygen -o` - `dnssec`: `.key` file format output by `dnssec-keygen` etc - `putty`: the PuTTY `.ppk` file format (supports truncated variant without all the lines from `Private-Lines:` onwards) - `options` -- Optional Object, extra options, with keys: - `filename` -- Optional String, name for the key being parsed (eg. the filename that was opened). Used to generate Error messages - `passphrase` -- Optional String, encryption passphrase used to decrypt an encrypted PEM file ### `Key.isKey(obj)` Returns `true` if the given object is a valid `Key` object created by a version of `sshpk` compatible with this one. Parameters - `obj` -- Object to identify ### `Key#type` String, the type of key. Valid options are `rsa`, `dsa`, `ecdsa`. ### `Key#size` Integer, "size" of the key in bits. For RSA/DSA this is the size of the modulus; for ECDSA this is the bit size of the curve in use. ### `Key#comment` Optional string, a key comment used by some formats (eg the `ssh` format). ### `Key#curve` Only present if `this.type === 'ecdsa'`, string containing the name of the named curve used with this key. Possible values include `nistp256`, `nistp384` and `nistp521`. ### `Key#toBuffer([format = 'ssh'])` Convert the key into a given data format and return the serialized key as a Buffer. Parameters - `format` -- String name of format to use, for valid options see `parseKey()` ### `Key#toString([format = 'ssh])` Same as `this.toBuffer(format).toString()`. ### `Key#fingerprint([algorithm = 'sha256'[, hashType = 'ssh']])` Creates a new `Fingerprint` object representing this Key's fingerprint. Parameters - `algorithm` -- String name of hash algorithm to use, valid options are `md5`, `sha1`, `sha256`, `sha384`, `sha512` - `hashType` -- String name of fingerprint hash type to use, valid options are `ssh` (the type of fingerprint used by OpenSSH, e.g. in `ssh-keygen`), `spki` (used by HPKP, some OpenSSL applications) ### `Key#createVerify([hashAlgorithm])` Creates a `crypto.Verifier` specialized to use this Key (and the correct public key algorithm to match it). The returned Verifier has the same API as a regular one, except that the `verify()` function takes only the target signature as an argument. Parameters - `hashAlgorithm` -- optional String name of hash algorithm to use, any supported by OpenSSL are valid, usually including `sha1`, `sha256`. `v.verify(signature[, format])` Parameters - `signature` -- either a Signature object, or a Buffer or String - `format` -- optional String, name of format to interpret given String with. Not valid if `signature` is a Signature or Buffer. ### `Key#createDiffieHellman()` ### `Key#createDH()` Creates a Diffie-Hellman key exchange object initialized with this key and all necessary parameters. This has the same API as a `crypto.DiffieHellman` instance, except that functions take `Key` and `PrivateKey` objects as arguments, and return them where indicated for. This is only valid for keys belonging to a cryptosystem that supports DHE or a close analogue (i.e. `dsa`, `ecdsa` and `curve25519` keys). An attempt to call this function on other keys will yield an `Error`. ## Private keys ### `parsePrivateKey(data[, format = 'auto'[, options]])` Parses a private key from a given data format and returns a new `PrivateKey` object. Parameters - `data` -- Either a Buffer or String, containing the key - `format` -- String name of format to use, valid options are: - `auto`: choose automatically from all below - `pem`: supports both PKCS#1 and PKCS#8 - `ssh`, `openssh`: new post-OpenSSH 6.5 internal format, produced by `ssh-keygen -o` - `pkcs1`, `pkcs8`: variants of `pem` - `rfc4253`: raw OpenSSH wire format - `dnssec`: `.private` format output by `dnssec-keygen` etc. - `options` -- Optional Object, extra options, with keys: - `filename` -- Optional String, name for the key being parsed (eg. the filename that was opened). Used to generate Error messages - `passphrase` -- Optional String, encryption passphrase used to decrypt an encrypted PEM file ### `generatePrivateKey(type[, options])` Generates a new private key of a certain key type, from random data. Parameters - `type` -- String, type of key to generate. Currently supported are `'ecdsa'` and `'ed25519'` - `options` -- optional Object, with keys: - `curve` -- optional String, for `'ecdsa'` keys, specifies the curve to use. If ECDSA is specified and this option is not given, defaults to using `'nistp256'`. ### `PrivateKey.isPrivateKey(obj)` Returns `true` if the given object is a valid `PrivateKey` object created by a version of `sshpk` compatible with this one. Parameters - `obj` -- Object to identify ### `PrivateKey#type` String, the type of key. Valid options are `rsa`, `dsa`, `ecdsa`. ### `PrivateKey#size` Integer, "size" of the key in bits. For RSA/DSA this is the size of the modulus; for ECDSA this is the bit size of the curve in use. ### `PrivateKey#curve` Only present if `this.type === 'ecdsa'`, string containing the name of the named curve used with this key. Possible values include `nistp256`, `nistp384` and `nistp521`. ### `PrivateKey#toBuffer([format = 'pkcs1'])` Convert the key into a given data format and return the serialized key as a Buffer. Parameters - `format` -- String name of format to use, valid options are listed under `parsePrivateKey`. Note that ED25519 keys default to `openssh` format instead (as they have no `pkcs1` representation). ### `PrivateKey#toString([format = 'pkcs1'])` Same as `this.toBuffer(format).toString()`. ### `PrivateKey#toPublic()` Extract just the public part of this private key, and return it as a `Key` object. ### `PrivateKey#fingerprint([algorithm = 'sha256'])` Same as `this.toPublic().fingerprint()`. ### `PrivateKey#createVerify([hashAlgorithm])` Same as `this.toPublic().createVerify()`. ### `PrivateKey#createSign([hashAlgorithm])` Creates a `crypto.Sign` specialized to use this PrivateKey (and the correct key algorithm to match it). The returned Signer has the same API as a regular one, except that the `sign()` function takes no arguments, and returns a `Signature` object. Parameters - `hashAlgorithm` -- optional String name of hash algorithm to use, any supported by OpenSSL are valid, usually including `sha1`, `sha256`. `v.sign()` Parameters - none ### `PrivateKey#derive(newType)` Derives a related key of type `newType` from this key. Currently this is only supported to change between `ed25519` and `curve25519` keys which are stored with the same private key (but usually distinct public keys in order to avoid degenerate keys that lead to a weak Diffie-Hellman exchange). Parameters - `newType` -- String, type of key to derive, either `ed25519` or `curve25519` ## Fingerprints ### `parseFingerprint(fingerprint[, options])` Pre-parses a fingerprint, creating a `Fingerprint` object that can be used to quickly locate a key by using the `Fingerprint#matches` function. Parameters - `fingerprint` -- String, the fingerprint value, in any supported format - `options` -- Optional Object, with properties: - `algorithms` -- Array of strings, names of hash algorithms to limit support to. If `fingerprint` uses a hash algorithm not on this list, throws `InvalidAlgorithmError`. - `hashType` -- String, the type of hash the fingerprint uses, either `ssh` or `spki` (normally auto-detected based on the format, but can be overridden) - `type` -- String, the entity this fingerprint identifies, either `key` or `certificate` ### `Fingerprint.isFingerprint(obj)` Returns `true` if the given object is a valid `Fingerprint` object created by a version of `sshpk` compatible with this one. Parameters - `obj` -- Object to identify ### `Fingerprint#toString([format])` Returns a fingerprint as a string, in the given format. Parameters - `format` -- Optional String, format to use, valid options are `hex` and `base64`. If this `Fingerprint` uses the `md5` algorithm, the default format is `hex`. Otherwise, the default is `base64`. ### `Fingerprint#matches(keyOrCertificate)` Verifies whether or not this `Fingerprint` matches a given `Key` or `Certificate`. This function uses double-hashing to avoid leaking timing information. Returns a boolean. Note that a `Key`-type Fingerprint will always return `false` if asked to match a `Certificate` and vice versa. Parameters - `keyOrCertificate` -- a `Key` object or `Certificate` object, the entity to match this fingerprint against ## Signatures ### `parseSignature(signature, algorithm, format)` Parses a signature in a given format, creating a `Signature` object. Useful for converting between the SSH and ASN.1 (PKCS/OpenSSL) signature formats, and also returned as output from `PrivateKey#createSign().sign()`. A Signature object can also be passed to a verifier produced by `Key#createVerify()` and it will automatically be converted internally into the correct format for verification. Parameters - `signature` -- a Buffer (binary) or String (base64), data of the actual signature in the given format - `algorithm` -- a String, name of the algorithm to be used, possible values are `rsa`, `dsa`, `ecdsa` - `format` -- a String, either `asn1` or `ssh` ### `Signature.isSignature(obj)` Returns `true` if the given object is a valid `Signature` object created by a version of `sshpk` compatible with this one. Parameters - `obj` -- Object to identify ### `Signature#toBuffer([format = 'asn1'])` Converts a Signature to the given format and returns it as a Buffer. Parameters - `format` -- a String, either `asn1` or `ssh` ### `Signature#toString([format = 'asn1'])` Same as `this.toBuffer(format).toString('base64')`. ## Certificates `sshpk` includes basic support for parsing certificates in X.509 (PEM) format and the OpenSSH certificate format. This feature is intended to be used mainly to access basic metadata about certificates, extract public keys from them, and also to generate simple self-signed certificates from an existing key. Notably, there is no implementation of CA chain-of-trust verification, and only very minimal support for key usage restrictions. Please do the security world a favour, and DO NOT use this code for certificate verification in the traditional X.509 CA chain style. ### `parseCertificate(data, format)` Parameters - `data` -- a Buffer or String - `format` -- a String, format to use, one of `'openssh'`, `'pem'` (X.509 in a PEM wrapper), or `'x509'` (raw DER encoded) ### `createSelfSignedCertificate(subject, privateKey[, options])` Parameters - `subject` -- an Identity, the subject of the certificate - `privateKey` -- a PrivateKey, the key of the subject: will be used both to be placed in the certificate and also to sign it (since this is a self-signed certificate) - `options` -- optional Object, with keys: - `lifetime` -- optional Number, lifetime of the certificate from now in seconds - `validFrom`, `validUntil` -- optional Dates, beginning and end of certificate validity period. If given `lifetime` will be ignored - `serial` -- optional Buffer, the serial number of the certificate - `purposes` -- optional Array of String, X.509 key usage restrictions ### `createCertificate(subject, key, issuer, issuerKey[, options])` Parameters - `subject` -- an Identity, the subject of the certificate - `key` -- a Key, the public key of the subject - `issuer` -- an Identity, the issuer of the certificate who will sign it - `issuerKey` -- a PrivateKey, the issuer's private key for signing - `options` -- optional Object, with keys: - `lifetime` -- optional Number, lifetime of the certificate from now in seconds - `validFrom`, `validUntil` -- optional Dates, beginning and end of certificate validity period. If given `lifetime` will be ignored - `serial` -- optional Buffer, the serial number of the certificate - `purposes` -- optional Array of String, X.509 key usage restrictions ### `Certificate#subjects` Array of `Identity` instances describing the subject of this certificate. ### `Certificate#issuer` The `Identity` of the Certificate's issuer (signer). ### `Certificate#subjectKey` The public key of the subject of the certificate, as a `Key` instance. ### `Certificate#issuerKey` The public key of the signing issuer of this certificate, as a `Key` instance. May be `undefined` if the issuer's key is unknown (e.g. on an X509 certificate). ### `Certificate#serial` The serial number of the certificate. As this is normally a 64-bit or wider integer, it is returned as a Buffer. ### `Certificate#purposes` Array of Strings indicating the X.509 key usage purposes that this certificate is valid for. The possible strings at the moment are: * `'signature'` -- key can be used for digital signatures * `'identity'` -- key can be used to attest about the identity of the signer (X.509 calls this `nonRepudiation`) * `'codeSigning'` -- key can be used to sign executable code * `'keyEncryption'` -- key can be used to encrypt other keys * `'encryption'` -- key can be used to encrypt data (only applies for RSA) * `'keyAgreement'` -- key can be used for key exchange protocols such as Diffie-Hellman * `'ca'` -- key can be used to sign other certificates (is a Certificate Authority) * `'crl'` -- key can be used to sign Certificate Revocation Lists (CRLs) ### `Certificate#getExtension(nameOrOid)` Retrieves information about a certificate extension, if present, or returns `undefined` if not. The string argument `nameOrOid` should be either the OID (for X509 extensions) or the name (for OpenSSH extensions) of the extension to retrieve. The object returned will have the following properties: * `format` -- String, set to either `'x509'` or `'openssh'` * `name` or `oid` -- String, only one set based on value of `format` * `data` -- Buffer, the raw data inside the extension ### `Certificate#getExtensions()` Returns an Array of all present certificate extensions, in the same manner and format as `getExtension()`. ### `Certificate#isExpired([when])` Tests whether the Certificate is currently expired (i.e. the `validFrom` and `validUntil` dates specify a range of time that does not include the current time). Parameters - `when` -- optional Date, if specified, tests whether the Certificate was or will be expired at the specified time instead of now Returns a Boolean. ### `Certificate#isSignedByKey(key)` Tests whether the Certificate was validly signed by the given (public) Key. Parameters - `key` -- a Key instance Returns a Boolean. ### `Certificate#isSignedBy(certificate)` Tests whether this Certificate was validly signed by the subject of the given certificate. Also tests that the issuer Identity of this Certificate and the subject Identity of the other Certificate are equivalent. Parameters - `certificate` -- another Certificate instance Returns a Boolean. ### `Certificate#fingerprint([hashAlgo])` Returns the X509-style fingerprint of the entire certificate (as a Fingerprint instance). This matches what a web-browser or similar would display as the certificate fingerprint and should not be confused with the fingerprint of the subject's public key. Parameters - `hashAlgo` -- an optional String, any hash function name ### `Certificate#toBuffer([format])` Serializes the Certificate to a Buffer and returns it. Parameters - `format` -- an optional String, output format, one of `'openssh'`, `'pem'` or `'x509'`. Defaults to `'x509'`. Returns a Buffer. ### `Certificate#toString([format])` - `format` -- an optional String, output format, one of `'openssh'`, `'pem'` or `'x509'`. Defaults to `'pem'`. Returns a String. ## Certificate identities ### `identityForHost(hostname)` Constructs a host-type Identity for a given hostname. Parameters - `hostname` -- the fully qualified DNS name of the host Returns an Identity instance. ### `identityForUser(uid)` Constructs a user-type Identity for a given UID. Parameters - `uid` -- a String, user identifier (login name) Returns an Identity instance. ### `identityForEmail(email)` Constructs an email-type Identity for a given email address. Parameters - `email` -- a String, email address Returns an Identity instance. ### `identityFromDN(dn)` Parses an LDAP-style DN string (e.g. `'CN=foo, C=US'`) and turns it into an Identity instance. Parameters - `dn` -- a String Returns an Identity instance. ### `identityFromArray(arr)` Constructs an Identity from an array of DN components (see `Identity#toArray()` for the format). Parameters - `arr` -- an Array of Objects, DN components with `name` and `value` Returns an Identity instance. Supported attributes in DNs: | Attribute name | OID | | -------------- | --- | | `cn` | `2.5.4.3` | | `o` | `2.5.4.10` | | `ou` | `2.5.4.11` | | `l` | `2.5.4.7` | | `s` | `2.5.4.8` | | `c` | `2.5.4.6` | | `sn` | `2.5.4.4` | | `postalCode` | `2.5.4.17` | | `serialNumber` | `2.5.4.5` | | `street` | `2.5.4.9` | | `x500UniqueIdentifier` | `2.5.4.45` | | `role` | `2.5.4.72` | | `telephoneNumber` | `2.5.4.20` | | `description` | `2.5.4.13` | | `dc` | `0.9.2342.19200300.100.1.25` | | `uid` | `0.9.2342.19200300.100.1.1` | | `mail` | `0.9.2342.19200300.100.1.3` | | `title` | `2.5.4.12` | | `gn` | `2.5.4.42` | | `initials` | `2.5.4.43` | | `pseudonym` | `2.5.4.65` | ### `Identity#toString()` Returns the identity as an LDAP-style DN string. e.g. `'CN=foo, O=bar corp, C=us'` ### `Identity#type` The type of identity. One of `'host'`, `'user'`, `'email'` or `'unknown'` ### `Identity#hostname` ### `Identity#uid` ### `Identity#email` Set when `type` is `'host'`, `'user'`, or `'email'`, respectively. Strings. ### `Identity#cn` The value of the first `CN=` in the DN, if any. It's probably better to use the `#get()` method instead of this property. ### `Identity#get(name[, asArray])` Returns the value of a named attribute in the Identity DN. If there is no attribute of the given name, returns `undefined`. If multiple components of the DN contain an attribute of this name, an exception is thrown unless the `asArray` argument is given as `true` -- then they will be returned as an Array in the same order they appear in the DN. Parameters - `name` -- a String - `asArray` -- an optional Boolean ### `Identity#toArray()` Returns the Identity as an Array of DN component objects. This looks like: ```js [ { "name": "cn", "value": "Joe Bloggs" }, { "name": "o", "value": "Organisation Ltd" } ] ``` Each object has a `name` and a `value` property. The returned objects may be safely modified. Errors ------ ### `InvalidAlgorithmError` The specified algorithm is not valid, either because it is not supported, or because it was not included on a list of allowed algorithms. Thrown by `Fingerprint.parse`, `Key#fingerprint`. Properties - `algorithm` -- the algorithm that could not be validated ### `FingerprintFormatError` The fingerprint string given could not be parsed as a supported fingerprint format, or the specified fingerprint format is invalid. Thrown by `Fingerprint.parse`, `Fingerprint#toString`. Properties - `fingerprint` -- if caused by a fingerprint, the string value given - `format` -- if caused by an invalid format specification, the string value given ### `KeyParseError` The key data given could not be parsed as a valid key. Properties - `keyName` -- `filename` that was given to `parseKey` - `format` -- the `format` that was trying to parse the key (see `parseKey`) - `innerErr` -- the inner Error thrown by the format parser ### `KeyEncryptedError` The key is encrypted with a symmetric key (ie, it is password protected). The parsing operation would succeed if it was given the `passphrase` option. Properties - `keyName` -- `filename` that was given to `parseKey` - `format` -- the `format` that was trying to parse the key (currently can only be `"pem"`) ### `CertificateParseError` The certificate data given could not be parsed as a valid certificate. Properties - `certName` -- `filename` that was given to `parseCertificate` - `format` -- the `format` that was trying to parse the key (see `parseCertificate`) - `innerErr` -- the inner Error thrown by the format parser Friends of sshpk ---------------- * [`sshpk-agent`](https://github.com/arekinath/node-sshpk-agent) is a library for speaking the `ssh-agent` protocol from node.js, which uses `sshpk` # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # gaze [![Build Status](http://img.shields.io/travis/shama/gaze.svg)](https://travis-ci.org/shama/gaze) [![Build status](https://ci.appveyor.com/api/projects/status/vtx65w9eg511tgo4)](https://ci.appveyor.com/project/shama/gaze) A globbing `fs.watch` wrapper built from the best parts of other fine watch libs. Compatible with Node.js >= 4.x, Windows, macOS, and Linux. ![gaze](http://dontkry.com/images/repos/gaze.png) [![NPM](https://nodei.co/npm/gaze.png?downloads=true)](https://nodei.co/npm/gaze/) ## Usage Install the module with: `npm install gaze` or place into your `package.json` and run `npm install`. ```javascript var gaze = require('gaze'); // Watch all .js files/dirs in process.cwd() gaze('**/*.js', function(err, watcher) { // Files have all started watching // watcher === this // Get all watched files var watched = this.watched(); // On file changed this.on('changed', function(filepath) { console.log(filepath + ' was changed'); }); // On file added this.on('added', function(filepath) { console.log(filepath + ' was added'); }); // On file deleted this.on('deleted', function(filepath) { console.log(filepath + ' was deleted'); }); // On changed/added/deleted this.on('all', function(event, filepath) { console.log(filepath + ' was ' + event); }); // Get watched files with relative paths var files = this.relative(); }); // Also accepts an array of patterns gaze(['stylesheets/*.css', 'images/**/*.png'], function() { // Add more patterns later to be watched this.add(['js/*.js']); }); ``` ### Alternate Interface ```javascript var Gaze = require('gaze').Gaze; var gaze = new Gaze('**/*'); // Files have all started watching gaze.on('ready', function(watcher) { }); // A file has been added/changed/deleted has occurred gaze.on('all', function(event, filepath) { }); ``` ### Errors ```javascript gaze('**/*', function(error, watcher) { if (error) { // Handle error if it occurred while starting up } }); // Or with the alternative interface var gaze = new Gaze(); gaze.on('error', function(error) { // Handle error here }); gaze.add('**/*'); ``` ### Minimatch / Glob See [isaacs's `minimatch`](https://github.com/isaacs/minimatch) for more information on glob patterns. ## Documentation ### gaze([patterns, options, callback]) * `patterns` {`String`|`Array`} File patterns to be matched * `options` {`Object`} * `callback` {`Function`} * `err` {`Error` | `null`} * `watcher` {`Object`} Instance of the `Gaze` watcher ### Class: `gaze.Gaze` Create a `Gaze` object by instancing the `gaze.Gaze` class. ```javascript var Gaze = require('gaze').Gaze; var gaze = new Gaze(pattern, options, callback); ``` #### Properties * `options` The options object passed in. * `interval` {integer} Interval to pass to `fs.watchFile` * `debounceDelay` {integer} Delay for events called in succession for the same file/event in milliseconds * `mode` {string} Force the watch mode. Either `'auto'` (default), `'watch'` (force native events), or `'poll'` (force stat polling). * `cwd` {string} The current working directory to base file patterns from. Default is `process.cwd()`. #### Events * `ready(watcher)` When files have been globbed and watching has begun. * `all(event, filepath)` When an `added`, `changed`, `renamed`, or `deleted` event occurs. * `added(filepath)` When a file has been added to a watch directory. * `changed(filepath)` When a file has been changed. * `deleted(filepath)` When a file has been deleted. * `renamed(newPath, oldPath)` When a file has been renamed. * `end()` When the watcher is closed and watches have been removed. * `error(err)` When an error occurs. * `nomatch` When no files have been matched. #### Methods * `emit(event, [...])` Wrapper for `EventEmitter.emit`. `added`|`changed`|`renamed`|`deleted` events will also trigger the `all` event. * `close()` Unwatch all files and reset the watch instance. * `add(patterns, callback)` Adds file(s) `patterns` to be watched. * `remove(filepath)` Removes a file or directory from being watched. Does not recurse directories. * `watched()` Returns the currently watched files. * `relative([dir, unixify])` Returns the currently watched files with relative paths. * `dir` {string} Only return relative files for this directory. * `unixify` {boolean} Return paths with `/` instead of `\\` if on Windows. ## Similar Projects Other great watch libraries to try are: * [paulmillr's `chokidar`](https://github.com/paulmillr/chokidar) * [amasad's `sane`](https://github.com/amasad/sane) * [mikeal's `watch`](https://github.com/mikeal/watch) * [github's `pathwatcher`](https://github.com/atom/node-pathwatcher) * [bevry's `watchr`](https://github.com/bevry/watchr) ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](http://gruntjs.com/). ## Release History * 1.1.3 - Fix for Node 10 support (@aredridel). Officially dropping support for Node < 4. * 1.1.2 - Prevent more `ENOENT` errors from escaping (@alexgorbatchev). * 1.1.1 - Prevent `fs.watch` errors from escaping error handler (@rosen-vladimirov). Fix `_addToWatched` without `path.sep` (@wyicwx). * 1.1.0 - Update to `[email protected]` with `minimatch >= 3.0.0`. * 1.0.0 - Revert back to 0.5.2. Drop support for Node.js v0.8. Fix for `maxListeners`. Update `globule` to `0.2.0`. * 0.6.4 - Catch and emit `error` from `readdir` (@oconnore). Fix for `0 maxListeners`. Use `graceful-fs` to avoid `EMFILE` errors in other places `fs` is used. Better method to determine if `pathwatcher` was built. Fix keeping process alive too much, only init `pathwatcher` if a file is being watched. Set min required to Windows Vista when building on Windows (@pvolok). * 0.6.3 - Add support for Node.js v0.11 * 0.6.2 - Fix argument error with `watched()`. Fix for erroneous `added` events on folders. Ignore `msvs` build error 4244. * 0.6.1 - Fix for absolute paths. * 0.6.0 - Uses native OS events (fork of `pathwatcher`) but can fall back to stat polling. Everything is async to avoid blocking, including `relative()` and `watched()`. Better error handling. Update to `[email protected]`. No longer watches `cwd` by default. Added `mode` option. Better `EMFILE` message. Avoids `ENOENT` errors with symlinks. All constructor arguments are optional. * 0.5.2 - Fix for `ENOENT` error with non-existent symlinks [BACKPORTED]. * 0.5.1 - Use `setImmediate` (`process.nextTick` for Node.js v0.8) to defer `ready`/`nomatch` events (@amasad). * 0.5.0 - Process is now kept alive while watching files. Emits a `nomatch` event when no files are matching. * 0.4.3 - Track file additions in newly created folders (@brett-shwom). * 0.4.2 - Fix `.remove()` method to remove a single file in a directory (@kaelzhang). Fixing “`Cannot call method 'call' of undefined`” (@krasimir). Track new file additions within folders (@brett-shwom). * 0.4.1 - Fix `watchDir` not respecting close in race condition (@chrisirhc). * 0.4.0 - Drop support for Node.js v0.6. Use `globule` for file matching. Avoid Node.js v0.10 `path.resolve`/`join` errors. Register new files when added to non-existent folder. Multiple instances can now poll the same files (@jpommerening). * 0.3.4 - Code clean up. Fix “`path must be strings`” errors (@groner). Fix incorrect `added` events (@groner). * 0.3.3 - Fix for multiple patterns with negate. * 0.3.2 - Emit `end` before `removeAllListeners`. * 0.3.1 - Fix `added` events within subfolder patterns. * 0.3.0 - Handle safewrite events, `forceWatchMethod` option removed, bug fixes and watch optimizations (@rgaskill). * 0.2.2 - Fix issue where subsequent `add` calls dont get watched (@samcday). `removeAllListeners` on `close`. * 0.2.1 - Fix issue with invalid `added` events in current working dir. * 0.2.0 - Support and mark folders with `path.sep`. Add `forceWatchMethod` option. Support `renamed` events. * 0.1.6 - Recognize the `cwd` option properly * 0.1.5 - Catch “`too many open file`” errors * 0.1.4 - Really fix the race condition with 2 watches * 0.1.3 - Fix race condition with 2 watches * 0.1.2 - Read triggering changed event fix * 0.1.1 - Minor fixes * 0.1.0 - Initial release ## License Copyright (c) 2018 Kyle Robinson Young Licensed under the MIT license. # content-type [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Create and parse HTTP Content-Type header according to RFC 7231 ## Installation ```sh $ npm install content-type ``` ## API ```js var contentType = require('content-type') ``` ### contentType.parse(string) ```js var obj = contentType.parse('image/svg+xml; charset=utf-8') ``` Parse a content type string. This will return an object with the following properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): - `type`: The media type (the type and subtype, always lower case). Example: `'image/svg+xml'` - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` Throws a `TypeError` if the string is missing or invalid. ### contentType.parse(req) ```js var obj = contentType.parse(req) ``` Parse the `content-type` header from the given `req`. Short-cut for `contentType.parse(req.headers['content-type'])`. Throws a `TypeError` if the `Content-Type` header is missing or invalid. ### contentType.parse(res) ```js var obj = contentType.parse(res) ``` Parse the `content-type` header set on the given `res`. Short-cut for `contentType.parse(res.getHeader('content-type'))`. Throws a `TypeError` if the `Content-Type` header is missing or invalid. ### contentType.format(obj) ```js var str = contentType.format({type: 'image/svg+xml'}) ``` Format an object into a content type string. This will return a string of the content type for the given object with the following properties (examples are shown that produce the string `'image/svg+xml; charset=utf-8'`): - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` - `parameters`: An object of the parameters in the media type (name of the parameter will be lower-cased). Example: `{charset: 'utf-8'}` Throws a `TypeError` if the object contains an invalid type or parameter names. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/content-type.svg [npm-url]: https://npmjs.org/package/content-type [node-version-image]: https://img.shields.io/node/v/content-type.svg [node-version-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg [travis-url]: https://travis-ci.org/jshttp/content-type [coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/content-type [downloads-image]: https://img.shields.io/npm/dm/content-type.svg [downloads-url]: https://npmjs.org/package/content-type # set-value [![NPM version](https://img.shields.io/npm/v/set-value.svg?style=flat)](https://www.npmjs.com/package/set-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/set-value.svg?style=flat)](https://npmjs.org/package/set-value) [![NPM total downloads](https://img.shields.io/npm/dt/set-value.svg?style=flat)](https://npmjs.org/package/set-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/set-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/set-value) > Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save set-value ``` ## Usage ```js var set = require('set-value'); var obj = {}; set(obj, 'a.b.c', 'd'); console.log(obj); //=> {a: {b: c: 'd'}} ``` ## About ### Related projects * [assign-value](https://www.npmjs.com/package/assign-value): Assign a value or extend a deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/assign-value) | [homepage](https://github.com/jonschlinkert/assign-value "Assign a value or extend a deeply nested property of an object using object path notation.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value "Returns true if a value exists, false if empty. Works with deeply nested values using object paths.") * [merge-value](https://www.npmjs.com/package/merge-value): Similar to assign-value but deeply merges object values or nested values using object path/dot notation. | [homepage](https://github.com/jonschlinkert/merge-value "Similar to assign-value but deeply merges object values or nested values using object path/dot notation.") * [omit-value](https://www.npmjs.com/package/omit-value): Omit properties from an object or deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/omit-value) | [homepage](https://github.com/jonschlinkert/omit-value "Omit properties from an object or deeply nested property of an object using object path notation.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [union-value](https://www.npmjs.com/package/union-value): Set an array of unique values as the property of an object. Supports setting deeply… [more](https://github.com/jonschlinkert/union-value) | [homepage](https://github.com/jonschlinkert/union-value "Set an array of unique values as the property of an object. Supports setting deeply nested properties using using object-paths/dot notation.") * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value "Delete nested properties from an object using dot notation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 53 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [vadimdemedes](https://github.com/vadimdemedes) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 22, 2017._ [![Build Status](https://travis-ci.org/isaacs/rimraf.svg?branch=master)](https://travis-ci.org/isaacs/rimraf) [![Dependency Status](https://david-dm.org/isaacs/rimraf.svg)](https://david-dm.org/isaacs/rimraf) [![devDependency Status](https://david-dm.org/isaacs/rimraf/dev-status.svg)](https://david-dm.org/isaacs/rimraf#info=devDependencies) The [UNIX command](http://en.wikipedia.org/wiki/Rm_(Unix)) `rm -rf` for node. Install with `npm install rimraf`, or just drop rimraf.js somewhere. ## API `rimraf(f, [opts], callback)` The first parameter will be interpreted as a globbing pattern for files. If you want to disable globbing you can do so with `opts.disableGlob` (defaults to `false`). This might be handy, for instance, if you have filenames that contain globbing wildcard characters. The callback will be called with an error if there is one. Certain errors are handled for you: * Windows: `EBUSY` and `ENOTEMPTY` - rimraf will back off a maximum of `opts.maxBusyTries` times before giving up, adding 100ms of wait between each attempt. The default `maxBusyTries` is 3. * `ENOENT` - If the file doesn't exist, rimraf will return successfully, since your desired outcome is already the case. * `EMFILE` - Since `readdir` requires opening a file descriptor, it's possible to hit `EMFILE` if too many file descriptors are in use. In the sync case, there's nothing to be done for this. But in the async case, rimraf will gradually back off with timeouts up to `opts.emfileWait` ms, which defaults to 1000. ## options * unlink, chmod, stat, lstat, rmdir, readdir, unlinkSync, chmodSync, statSync, lstatSync, rmdirSync, readdirSync In order to use a custom file system library, you can override specific fs functions on the options object. If any of these functions are present on the options object, then the supplied function will be used instead of the default fs method. Sync methods are only relevant for `rimraf.sync()`, of course. For example: ```javascript var myCustomFS = require('some-custom-fs') rimraf('some-thing', myCustomFS, callback) ``` * maxBusyTries If an `EBUSY`, `ENOTEMPTY`, or `EPERM` error code is encountered on Windows systems, then rimraf will retry with a linear backoff wait of 100ms longer on each try. The default maxBusyTries is 3. Only relevant for async usage. * emfileWait If an `EMFILE` error is encountered, then rimraf will retry repeatedly with a linear backoff of 1ms longer on each try, until the timeout counter hits this max. The default limit is 1000. If you repeatedly encounter `EMFILE` errors, then consider using [graceful-fs](http://npm.im/graceful-fs) in your program. Only relevant for async usage. * glob Set to `false` to disable [glob](http://npm.im/glob) pattern matching. Set to an object to pass options to the glob module. The default glob options are `{ nosort: true, silent: true }`. Glob version 6 is used in this module. Relevant for both sync and async usage. * disableGlob Set to any non-falsey value to disable globbing entirely. (Equivalent to setting `glob: false`.) ## rimraf.sync It can remove stuff synchronously, too. But that's not so good. Use the async API. It's better. ## CLI If installed with `npm install rimraf -g` it can be used as a global command `rimraf <path> [<path> ...]` which is useful for cross platform support. ## mkdirp If you need to create a directory recursively, check out [mkdirp](https://github.com/substack/node-mkdirp). ## Caseless -- wrap an object to set and get property with caseless semantics but also preserve caseing. This library is incredibly useful when working with HTTP headers. It allows you to get/set/check for headers in a caseless manner while also preserving the caseing of headers the first time they are set. ## Usage ```javascript var headers = {} , c = caseless(headers) ; c.set('a-Header', 'asdf') c.get('a-header') === 'asdf' ``` ## has(key) Has takes a name and if it finds a matching header will return that header name with the preserved caseing it was set with. ```javascript c.has('a-header') === 'a-Header' ``` ## set(key, value[, clobber=true]) Set is fairly straight forward except that if the header exists and clobber is disabled it will add `','+value` to the existing header. ```javascript c.set('a-Header', 'fdas') c.set('a-HEADER', 'more', false) c.get('a-header') === 'fdsa,more' ``` ## swap(key) Swaps the casing of a header with the new one that is passed in. ```javascript var headers = {} , c = caseless(headers) ; c.set('a-Header', 'fdas') c.swap('a-HEADER') c.has('a-header') === 'a-HEADER' headers === {'a-HEADER': 'fdas'} ``` # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _using tagged template literals_ ```js var __ = require('y18n').__ var str = 'foo' console.log(__`my awesome string ${str}`) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. This function can also be used as a tag for a template literal. You can use it like this: <code>__&#96;hello ${'world'}&#96;</code>. This will be equivalent to `__('hello %s', 'world')`. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard # object.pick [![NPM version](https://img.shields.io/npm/v/object.pick.svg?style=flat)](https://www.npmjs.com/package/object.pick) [![NPM monthly downloads](https://img.shields.io/npm/dm/object.pick.svg?style=flat)](https://npmjs.org/package/object.pick) [![NPM total downloads](https://img.shields.io/npm/dt/object.pick.svg?style=flat)](https://npmjs.org/package/object.pick) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/object.pick.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/object.pick) > Returns a filtered copy of an object with only the specified keys, similar to `_.pick` from lodash / underscore. You might also be interested in [object.omit](https://github.com/jonschlinkert/object.omit). ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save object.pick ``` ## benchmarks This is the [fastest implementation](http://jsperf.com/pick-props) I tested. Pull requests welcome! ## Usage ```js var pick = require('object.pick'); pick({a: 'a', b: 'b'}, 'a') //=> {a: 'a'} pick({a: 'a', b: 'b', c: 'c'}, ['a', 'b']) //=> {a: 'a', b: 'b'} ``` ## About ### Related projects * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/object.pick/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 27, 2016._ glob-parent [![Build Status](https://travis-ci.org/es128/glob-parent.svg)](https://travis-ci.org/es128/glob-parent) [![Coverage Status](https://img.shields.io/coveralls/es128/glob-parent.svg)](https://coveralls.io/r/es128/glob-parent?branch=master) ====== Javascript module to extract the non-magic parent path from a glob string. [![NPM](https://nodei.co/npm/glob-parent.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/glob-parent/) [![NPM](https://nodei.co/npm-dl/glob-parent.png?height=3&months=9)](https://nodei.co/npm-dl/glob-parent/) Usage ----- ```sh npm install glob-parent --save ``` **Examples** ```js var globParent = require('glob-parent'); globParent('path/to/*.js'); // 'path/to' globParent('/root/path/to/*.js'); // '/root/path/to' globParent('/*.js'); // '/' globParent('*.js'); // '.' globParent('**/*.js'); // '.' globParent('path/{to,from}'); // 'path' globParent('path/!(to|from)'); // 'path' globParent('path/?(to|from)'); // 'path' globParent('path/+(to|from)'); // 'path' globParent('path/*(to|from)'); // 'path' globParent('path/@(to|from)'); // 'path' globParent('path/**/*'); // 'path' // if provided a non-glob path, returns the nearest dir globParent('path/foo/bar.js'); // 'path/foo' globParent('path/foo/'); // 'path/foo' globParent('path/foo'); // 'path' (see issue #3 for details) ``` ## Escaping The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: - `?` (question mark) - `*` (star) - `|` (pipe) - `(` (opening parenthesis) - `)` (closing parenthesis) - `{` (opening curly brace) - `}` (closing curly brace) - `[` (opening bracket) - `]` (closing bracket) **Example** ```js globParent('foo/[bar]/') // 'foo' globParent('foo/\\[bar]/') // 'foo/[bar]' ``` ## Limitations #### Braces & Brackets This library attempts a quick and imperfect method of determining which path parts have glob magic without fully parsing/lexing the pattern. There are some advanced use cases that can trip it up, such as nested braces where the outer pair is escaped and the inner one contains a path separator. If you find yourself in the unlikely circumstance of being affected by this or need to ensure higher-fidelity glob handling in your library, it is recommended that you pre-process your input with [expand-braces] and/or [expand-brackets]. #### Windows Backslashes are not valid path separators for globs. If a path with backslashes is provided anyway, for simple cases, glob-parent will replace the path separator for you and return the non-glob parent path (now with forward-slashes, which are still valid as Windows path separators). This cannot be used in conjunction with escape characters. ```js // BAD globParent('C:\\Program Files \\(x86\\)\\*.ext') // 'C:/Program Files /(x86/)' // GOOD globParent('C:/Program Files\\(x86\\)/*.ext') // 'C:/Program Files (x86)' ``` If you are using escape characters for a pattern without path parts (i.e. relative to `cwd`), prefix with `./` to avoid confusing glob-parent. ```js // BAD globParent('foo \\[bar]') // 'foo ' globParent('foo \\[bar]*') // 'foo ' // GOOD globParent('./foo \\[bar]') // 'foo [bar]' globParent('./foo \\[bar]*') // '.' ``` Change Log ---------- [See release notes page on GitHub](https://github.com/es128/glob-parent/releases) License ------- [ISC](https://raw.github.com/es128/glob-parent/master/LICENSE) [expand-braces]: https://github.com/jonschlinkert/expand-braces [expand-brackets]: https://github.com/jonschlinkert/expand-brackets # has-symbols <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] Determine if the JS environment has Symbol support. Supports spec, or shams. ## Example ```js var hasSymbols = require('has-symbols'); hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. var hasSymbolsKinda = require('has-symbols/shams'); hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. ``` ## Supported Symbol shams - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/has-symbols [2]: http://versionbadg.es/ljharb/has-symbols.svg [3]: https://travis-ci.org/ljharb/has-symbols.svg [4]: https://travis-ci.org/ljharb/has-symbols [5]: https://david-dm.org/ljharb/has-symbols.svg [6]: https://david-dm.org/ljharb/has-symbols [7]: https://david-dm.org/ljharb/has-symbols/dev-status.svg [8]: https://david-dm.org/ljharb/has-symbols#info=devDependencies [9]: https://ci.testling.com/ljharb/has-symbols.png [10]: https://ci.testling.com/ljharb/has-symbols [11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/has-symbols.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/has-symbols.svg [downloads-url]: http://npm-stat.com/charts.html?package=has-symbols aws-sign ======== AWS signing. Originally pulled from LearnBoost/knox, maintained as vendor in request, now a standalone module. # clone-deep [![NPM version](https://img.shields.io/npm/v/clone-deep.svg?style=flat)](https://www.npmjs.com/package/clone-deep) [![NPM monthly downloads](https://img.shields.io/npm/dm/clone-deep.svg?style=flat)](https://npmjs.org/package/clone-deep) [![NPM total downloads](https://img.shields.io/npm/dt/clone-deep.svg?style=flat)](https://npmjs.org/package/clone-deep) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/clone-deep.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/clone-deep) > Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save clone-deep ``` ## Usage ```js var cloneDeep = require('clone-deep'); var obj = {a: 'b'}; var arr = [obj]; var copy = cloneDeep(arr); obj.c = 'd'; console.log(copy); //=> [{a: 'b'}] console.log(arr); //=> [{a: 'b', c: 'd'}] ``` ## Heads up! The `instanceClone` function is invoked to clone objects that are not "plain" objects (as defined by [isPlainObject](#isPlainObject)`isPlainObject`) if it is provided. If `instanceClone` is not specified, it will not attempt to clone non-plain objects, and will copy the object reference. ## Attribution Based on [mout's](https://github.com/mout/mout) implementation of deepClone. ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") * [shallow-clone](https://www.npmjs.com/package/shallow-clone): Make a shallow clone of an object, array or primitive. | [homepage](https://github.com/jonschlinkert/shallow-clone "Make a shallow clone of an object, array or primitive.") ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 16, 2017._ # HPACK.js [![Build Status](https://secure.travis-ci.org/indutny/hpack.js.png)](http://travis-ci.org/indutny/hpack.js) [![NPM version](https://badge.fury.io/js/hpack.js.svg)](http://badge.fury.io/js/hpack.js) Plain-JS implementation of [HPACK][0]. ## Usage ```javascript var hpack = require('hpack.js'); var comp = hpack.compressor.create({ table: { size: 256 } }); var decomp = hpack.decompressor.create({ table: { size: 256 } }); comp.write([ { name: 'host', value: 'localhost' } ]); var raw = comp.read(); console.log(raw); // <Buffer 66 86 a0 e4 1d 13 9d 09> decomp.write(raw); decomp.execute(); console.log(decomp.read()); // { name: 'host', value: 'localhost', neverIndex: false } ``` #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: https://tools.ietf.org/html/rfc7541 node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS. Currently BER encoding is supported; at some point I'll likely have to do DER. ## Usage Mostly, if you're *actually* needing to read and write ASN.1, you probably don't need this readme to explain what and why. If you have no idea what ASN.1 is, see this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc The source is pretty much self-explanatory, and has read/write methods for the common types out there. ### Decoding The following reads an ASN.1 sequence with a boolean. var Ber = require('asn1').Ber; var reader = new Ber.Reader(Buffer.from([0x30, 0x03, 0x01, 0x01, 0xff])); reader.readSequence(); console.log('Sequence len: ' + reader.length); if (reader.peek() === Ber.Boolean) console.log(reader.readBoolean()); ### Encoding The following generates the same payload as above. var Ber = require('asn1').Ber; var writer = new Ber.Writer(); writer.startSequence(); writer.writeBoolean(true); writer.endSequence(); console.log(writer.buffer); ## Installation npm install asn1 ## License MIT. ## Bugs See <https://github.com/joyent/node-asn1/issues>. anymatch [![Build Status](https://travis-ci.org/micromatch/anymatch.svg?branch=master)](https://travis-ci.org/micromatch/anymatch) [![Coverage Status](https://img.shields.io/coveralls/micromatch/anymatch.svg?branch=master)](https://coveralls.io/r/micromatch/anymatch?branch=master) ====== Javascript module to match a string against a regular expression, glob, string, or function that takes the string as an argument and returns a truthy or falsy value. The matcher can also be an array of any or all of these. Useful for allowing a very flexible user-defined config to define things like file paths. __Note: This module has Bash-parity, please be aware that Windows-style backslashes are not supported as separators. See https://github.com/micromatch/micromatch#backslashes for more information.__ [![NPM](https://nodei.co/npm/anymatch.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/anymatch/) [![NPM](https://nodei.co/npm-dl/anymatch.png?height=3&months=9)](https://nodei.co/npm-dl/anymatch/) Usage ----- ```sh npm install anymatch --save ``` #### anymatch (matchers, testString, [returnIndex], [startIndex], [endIndex]) * __matchers__: (_Array|String|RegExp|Function_) String to be directly matched, string with glob patterns, regular expression test, function that takes the testString as an argument and returns a truthy value if it should be matched, or an array of any number and mix of these types. * __testString__: (_String|Array_) The string to test against the matchers. If passed as an array, the first element of the array will be used as the `testString` for non-function matchers, while the entire array will be applied as the arguments for function matchers. * __returnIndex__: (_Boolean [optional]_) If true, return the array index of the first matcher that that testString matched, or -1 if no match, instead of a boolean result. * __startIndex, endIndex__: (_Integer [optional]_) Can be used to define a subset out of the array of provided matchers to test against. Can be useful with bound matcher functions (see below). When used with `returnIndex = true` preserves original indexing. Behaves the same as `Array.prototype.slice` (i.e. includes array members up to, but not including endIndex). ```js var anymatch = require('anymatch'); var matchers = [ 'path/to/file.js', 'path/anyjs/**/*.js', /foo\.js$/, function (string) { return string.indexOf('bar') !== -1 && string.length > 10 } ]; anymatch(matchers, 'path/to/file.js'); // true anymatch(matchers, 'path/anyjs/baz.js'); // true anymatch(matchers, 'path/to/foo.js'); // true anymatch(matchers, 'path/to/bar.js'); // true anymatch(matchers, 'bar.js'); // false // returnIndex = true anymatch(matchers, 'foo.js', true); // 2 anymatch(matchers, 'path/anyjs/foo.js', true); // 1 // skip matchers anymatch(matchers, 'path/to/file.js', false, 1); // false anymatch(matchers, 'path/anyjs/foo.js', true, 2, 3); // 2 anymatch(matchers, 'path/to/bar.js', true, 0, 3); // -1 // using globs to match directories and their children anymatch('node_modules', 'node_modules'); // true anymatch('node_modules', 'node_modules/somelib/index.js'); // false anymatch('node_modules/**', 'node_modules/somelib/index.js'); // true anymatch('node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // false anymatch('**/node_modules/**', '/absolute/path/to/node_modules/somelib/index.js'); // true ``` #### anymatch (matchers) You can also pass in only your matcher(s) to get a curried function that has already been bound to the provided matching criteria. This can be used as an `Array.prototype.filter` callback. ```js var matcher = anymatch(matchers); matcher('path/to/file.js'); // true matcher('path/anyjs/baz.js', true); // 1 matcher('path/anyjs/baz.js', true, 2); // -1 ['foo.js', 'bar.js'].filter(matcher); // ['foo.js'] ``` Change Log ---------- [See release notes page on GitHub](https://github.com/micromatch/anymatch/releases) NOTE: As of v2.0.0, [micromatch](https://github.com/jonschlinkert/micromatch) moves away from minimatch-parity and inline with Bash. This includes handling backslashes differently (see https://github.com/micromatch/micromatch#backslashes for more information). NOTE: As of v1.2.0, anymatch uses [micromatch](https://github.com/jonschlinkert/micromatch) for glob pattern matching. Issues with glob pattern matching should be reported directly to the [micromatch issue tracker](https://github.com/jonschlinkert/micromatch/issues). License ------- [ISC](https://raw.github.com/micromatch/anymatch/master/LICENSE) # forwarded [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Parse HTTP X-Forwarded-For header ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install forwarded ``` ## API ```js var forwarded = require('forwarded') ``` ### forwarded(req) ```js var addresses = forwarded(req) ``` Parse the `X-Forwarded-For` header from the request. Returns an array of the addresses, including the socket address for the `req`, in reverse order (i.e. index `0` is the socket address and the last index is the furthest address, typically the end-user). ## Testing ```sh $ npm test ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/forwarded.svg [npm-url]: https://npmjs.org/package/forwarded [node-version-image]: https://img.shields.io/node/v/forwarded.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/forwarded/master.svg [travis-url]: https://travis-ci.org/jshttp/forwarded [coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master [downloads-image]: https://img.shields.io/npm/dm/forwarded.svg [downloads-url]: https://npmjs.org/package/forwarded # watchpack Wrapper library for directory and file watching. [![Build Status](https://travis-ci.org/webpack/watchpack.svg?branch=master)](https://travis-ci.org/webpack/watchpack) [![Build status](https://ci.appveyor.com/api/projects/status/e5u2qvmugtv0r647/branch/master?svg=true)](https://ci.appveyor.com/project/sokra/watchpack/branch/master) [![Test coverage][coveralls-image]][coveralls-url] ## Concept watchpack high level API doesn't map directly to watchers. Instead a three level architecture ensures that for each directory only a single watcher exists. * The high level API requests `DirectoryWatchers` from a `WatcherManager`, which ensures that only a single `DirectoryWatcher` per directory is created. * A user-faced `Watcher` can be obtained from a `DirectoryWatcher` and provides a filtered view on the `DirectoryWatcher`. * Reference-counting is used on the `DirectoryWatcher` and `Watcher` to decide when to close them. * The real watchers (currently chokidar) are created by the `DirectoryWatcher`. * Files are never watched directly. This should keep the watcher count low. * Watching can be started in the past. This way watching can start after file reading. * Symlinks are not followed, instead the symlink is watched. ## API ``` javascript var Watchpack = require("watchpack"); var wp = new Watchpack({ // options: aggregateTimeout: 1000 // fire "aggregated" event when after a change for 1000ms no additional change occurred // aggregated defaults to undefined, which doesn't fire an "aggregated" event poll: true // poll: true - use polling with the default interval // poll: 10000 - use polling with an interval of 10s // poll defaults to undefined, which prefer native watching methods // Note: enable polling when watching on a network path ignored: /node_modules/, // anymatch-compatible definition of files/paths to be ignored // see https://github.com/paulmillr/chokidar#path-filtering }); // Watchpack.prototype.watch(string[] files, string[] directories, [number startTime]) wp.watch(listOfFiles, listOfDirectories, Date.now() - 10000); // starts watching these files and directories // calling this again will override the files and directories wp.on("change", function(filePath, mtime) { // filePath: the changed file // mtime: last modified time for the changed file }); wp.on("aggregated", function(changes) { // changes: an array of all changed files }); // Watchpack.prototype.pause() wp.pause(); // stops emitting events, but keeps watchers open // next "watch" call can reuse the watchers // Watchpack.prototype.close() wp.close(); // stops emitting events and closes all watchers // Watchpack.prototype.getTimes() var fileTimes = wp.getTimes(); // returns an object with all know change times for files // this include timestamps from files not directly watched // key: absolute path, value: timestamp as number ``` [coveralls-url]: https://coveralls.io/r/webpack/watchpack/ [coveralls-image]: https://img.shields.io/coveralls/webpack/watchpack.svg # HTTP Deceiver [![Build Status](https://secure.travis-ci.org/indutny/http-deceiver.png)](http://travis-ci.org/indutny/http-deceiver) [![NPM version](https://badge.fury.io/js/http-deceiver.svg)](http://badge.fury.io/js/http-deceiver) Deceive! ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Dynamic import support in acorn This is plugin for [Acorn](http://marijnhaverbeke.nl/acorn/) - a tiny, fast JavaScript parser, written completely in JavaScript. For more information, check out the [proposal repo](https://github.com/tc39/proposal-dynamic-import). ## Usage Importing this module gives you a plugin that can be used to extend an Acorn parser: ```js import Parser from 'acorn'; import dynamicImport from 'acorn-dynamic-import'; Parser.extend(dynamicImport).parse('import("something");'); ``` To extend the AST walker for dynamic imports, you can injecting the new node type into [`acorn-walk`](https://www.npmjs.com/package/acorn-walk) like this: ```js import inject from 'acorn-dynamic-import/lib/walk'; import * as acornWalk from 'acorn-walk'; const walk = inject(acornWalk); ``` ## License This plugin is issued under the [MIT license](./LICENSE). # once Only call a function once. ## usage ```javascript var once = require('once') function load (file, cb) { cb = once(cb) loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Or add to the Function.prototype in a responsible way: ```javascript // only has to be done once require('once').proto() function load (file, cb) { cb = cb.once() loader.load('file') loader.once('load', cb) loader.once('error', cb) } ``` Ironically, the prototype feature makes this module twice as complicated as necessary. To check whether you function has been called, use `fn.called`. Once the function is called for the first time the return value of the original function is saved in `fn.value` and subsequent calls will continue to return this value. ```javascript var once = require('once') function load (cb) { cb = once(cb) var stream = createStream() stream.once('data', cb) stream.once('end', function () { if (!cb.called) cb(new Error('not found')) }) } ``` ## `once.strict(func)` Throw an error if the function is called twice. Some functions are expected to be called only once. Using `once` for them would potentially hide logical errors. In the example below, the `greet` function has to call the callback only once: ```javascript function greet (name, cb) { // return is missing from the if statement // when no name is passed, the callback is called twice if (!name) cb('Hello anonymous') cb('Hello ' + name) } function log (msg) { console.log(msg) } // this will print 'Hello anonymous' but the logical error will be missed greet(null, once(msg)) // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time greet(null, once.strict(msg)) ``` # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Linux Build Status](https://img.shields.io/travis/micromatch/is-glob.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/is-glob) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/is-glob.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/is-glob) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` ### Default behavior **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob('abc/?.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ### Option strict When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js', {strict: false}); isGlob('*.js', {strict: false}); isGlob('**/abc.js', {strict: false}); isGlob('abc/*.js', {strict: false}); isGlob('abc/(aaa|bbb).js', {strict: false}); isGlob('abc/[a-z].js', {strict: false}); isGlob('abc/{a,b}.js', {strict: false}); //=> true ``` Extglobs ```js isGlob('abc/@(a).js', {strict: false}); isGlob('abc/!(a).js', {strict: false}); isGlob('abc/+(a).js', {strict: false}); isGlob('abc/*(a).js', {strict: false}); isGlob('abc/?(a).js', {strict: false}); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('\\!foo.js', {strict: false}); isGlob('\\*.js', {strict: false}); isGlob('\\*\\*/abc.js', {strict: false}); isGlob('abc/\\*.js', {strict: false}); isGlob('abc/\\(aaa|bbb).js', {strict: false}); isGlob('abc/\\[a-z].js', {strict: false}); isGlob('abc/\\{a,b}.js', {strict: false}); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 47 | [jonschlinkert](https://github.com/jonschlinkert) | | 5 | [doowb](https://github.com/doowb) | | 1 | [phated](https://github.com/phated) | | 1 | [danhper](https://github.com/danhper) | | 1 | [paulmillr](https://github.com/paulmillr) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ # loglevel [![NPM version][npm-image]][npm-url] [![NPM downloads](https://img.shields.io/npm/dw/loglevel.svg)](https://www.npmjs.com/package/loglevel) [![Build status](https://travis-ci.org/pimterry/loglevel.png)](https://travis-ci.org/pimterry/loglevel) [![Coveralls percentage](https://img.shields.io/coveralls/pimterry/loglevel.svg)](https://coveralls.io/r/pimterry/loglevel?branch=master) [npm-image]: https://img.shields.io/npm/v/loglevel.svg?style=flat [npm-url]: https://npmjs.org/package/loglevel Minimal lightweight simple logging for JavaScript. loglevel replaces console.log() and friends with level-based logging and filtering, with none of console's downsides. This is a barebones reliable everyday logging library. It does not do fancy things, it does not let you reconfigure appenders or add complex log filtering rules or boil tea (more's the pity), but it does have the all core functionality that you actually use: ## Features ### Simple * Log things at a given level (trace/debug/info/warn/error) to the console object (as seen in all modern browsers & node.js) * Filter logging by level (all the above or 'silent'), so you can disable all but error logging in production, and then run log.setLevel("trace") in your console to turn it all back on for a furious debugging session * Single file, no dependencies, weighs in at 1.1KB minified and gzipped ### Effective * Log methods gracefully fall back to simpler console logging methods if more specific ones aren't available: so calls to log.debug() go to console.debug() if possible, or console.log() if not * Logging calls still succeed even if there's no console object at all, so your site doesn't break when people visit with old browsers that don't support the console object (here's looking at you IE) and similar * This then comes together giving a consistent reliable API that works in every JavaScript environment with a console available, and never breaks anything anywhere else ### Convenient * Log output keeps line numbers: most JS logging frameworks call console.log methods through wrapper functions, clobbering your stacktrace and making the extra info many browsers provide useless. We'll have none of that thanks. * It works with all the standard JavaScript loading systems out of the box (CommonJS, AMD, or just as a global) * Logging is filtered to "warn" level by default, to keep your live site clean in normal usage (or you can trivially re-enable everything with an initial log.enableAll() call) * Magically handles situations where console logging is not initially available (IE8/9), and automatically enables logging as soon as it does become available (when developer console is opened) * Extensible, to add other log redirection, filtering, or formatting functionality, while keeping all the above (except you will clobber your stacktrace, see Plugins below) ## Downloading loglevel If you're using NPM, you can just run `npm install loglevel`. Alternatively, loglevel is also available via [Bower](https://github.com/bower/bower) (`bower install loglevel`), as a [Webjar](http://www.webjars.org/), or an [Atmosphere package](https://atmospherejs.com/spacejamio/loglevel) (for Meteor) Alternatively if you just want to grab the file yourself, you can download either the current stable [production version][min] or the [development version][max] directly, or reference it remotely on unpkg at [`https://unpkg.com/loglevel/dist/loglevel.min.js`][cdn] (this will redirect to a latest version, use the resulting redirected URL if you want to pin that version). Finally, if you want to tweak loglevel to your own needs or you immediately need the cutting-edge version, clone this repo and see [Developing & Contributing](#developing--contributing) below for build instructions. [min]: https://raw.github.com/pimterry/loglevel/master/dist/loglevel.min.js [max]: https://raw.github.com/pimterry/loglevel/master/dist/loglevel.js [cdn]: https://unpkg.com/loglevel/dist/loglevel.min.js ## Setting it up loglevel supports AMD (e.g. RequireJS), CommonJS (e.g. Node.js) and direct usage (e.g. loading globally with a &lt;script&gt; tag) loading methods. You should be able to do nearly anything, and then skip to the next section anyway and have it work. Just in case though, here's some specific examples that definitely do the right thing: ### CommonsJS (e.g. Node) ```javascript var log = require('loglevel'); log.warn("unreasonably simple"); ``` ### AMD (e.g. RequireJS) ```javascript define(['loglevel'], function(log) { log.warn("dangerously convenient"); }); ``` ### Directly in your web page: ```html <script src="loglevel.min.js"></script> <script> log.warn("too easy"); </script> ``` ### As an ES6 module (assuming some transpilation step): ```javascript import * as log from 'loglevel'; log.warn("ultra-compatible"); ``` ### With noConflict(): If you're using another JavaScript library that exposes a 'log' global, you can run into conflicts with loglevel. Similarly to jQuery, you can solve this by putting loglevel into no-conflict mode immediately after it is loaded onto the page. This resets to 'log' global to its value before loglevel was loaded (typically `undefined`), and returns the loglevel object, which you can then bind to another name yourself. For example: ```html <script src="loglevel.min.js"></script> <script> var logging = log.noConflict(); logging.warn("still pretty easy"); </script> ``` ## Documentation The loglevel API is extremely minimal. All methods are available on the root loglevel object, which it's suggested you name 'log' (this is the default if you import it in globally, and is what's set up in the above examples). The API consists of: * 5 actual logging methods, ordered and available as: * `log.trace(msg)` * `log.debug(msg)` * `log.info(msg)` * `log.warn(msg)` * `log.error(msg)` `log.log(msg)` is also available, as an alias for `log.debug(msg)`, to improve compatibility with `console`, and make migration easier. Exact output formatting of these will depend on the console available in the current context of your application. For example, many environments will include a full stack trace with all trace() calls, and icons or similar to highlight other calls. These methods should never fail in any environment, even if no console object is currently available, and should always fall back to an available log method even if the specific method called (e.g. warn) isn't available. Be aware that all this means that these method won't necessarily always produce exactly the output you expect in every environment; loglevel only guarantees that these methods will never explode on you, and that it will call the most relevant method it can find, with your argument. Firefox is a notable example here: due to a [current Firefox bug](https://bugzilla.mozilla.org/show_bug.cgi?id=1172314) `log.trace(msg)` calls in Firefox will print only the stacktrace, and won't include any passed message arguments. * A `log.setLevel(level, [persist])` method. This disables all logging below the given level, so that after a log.setLevel("warn") call log.warn("something") or log.error("something") will output messages, but log.info("something") will not. This can take either a log level name or 'silent' (which disables everything) in one of a few forms: * As a log level from the internal levels list, e.g. log.levels.SILENT ← _for type safety_ * As a string, like 'error' (case-insensitive) ← _for a reasonable practical balance_ * As a numeric index from 0 (trace) to 5 (silent) ← _deliciously terse, and more easily programmable (...although, why?)_ Where possible the log level will be persisted. LocalStorage will be used if available, falling back to cookies if not. If neither is available in the current environment (i.e. in Node), or if you pass `false` as the optional 'persist' second argument, persistence will be skipped. If log.setLevel() is called when a console object is not available (in IE 8 or 9 before the developer tools have been opened, for example) logging will remain silent until the console becomes available, and then begin logging at the requested level. * A `log.setDefaultLevel(level)` method. This sets the current log level only if one has not been persisted and can’t be loaded. This is useful when initializing scripts; if a developer or user has previously called `setLevel()`, this won’t alter their settings. For example, your application might set the log level to `error` in a production environment, but when debugging an issue, you might call `setLevel("trace")` on the console to see all the logs. If that `error` setting was set using `setDefaultLevel()`, it will still say as `trace` on subsequent page loads and refreshes instead of resetting to `error`. The `level` argument takes is the same values that you might pass to `setLevel()`. Levels set using `setDefaultLevel()` never persist to subsequent page loads. * `log.enableAll()` and `log.disableAll()` methods. These enable or disable all log messages, and are equivalent to log.setLevel("trace") and log.setLevel("silent") respectively. * A `log.getLevel()` method. Returns the current logging level, as a number from 0 (trace) to 5 (silent) It's very unlikely you'll need to use this for normal application logging; it's provided partly to help plugin development, and partly to let you optimize logging code as below, where debug data is only generated if the level is set such that it'll actually be logged. This probably doesn't affect you, unless you've run profiling on your code and you have hard numbers telling you that your log data generation is a real performance problem. ```javascript if (log.getLevel() <= log.levels.DEBUG) { var logData = runExpensiveDataGeneration(); log.debug(logData); } ``` This notably isn't the right solution to avoid the cost of string concatenation in your logging. Firstly, it's very unlikely that string concatenation in your logging is really an important performance problem. Even if you do genuinely have hard metrics showing that it is though, the better solution that wrapping your log statements in this is to use multiple arguments, as below. The underlying console API will automatically concatenate these for you if logging is enabled, and if it isn't then all log methods are no-ops, and no concatenation will be done at all. ```javascript // Prints 'My concatenated log message' log.debug("My ", "concatenated ", "log message"); ``` * A `log.getLogger(loggerName)` method. This gets you a new logger object that works exactly like the root `log` object, but can have its level and logging methods set independently. All loggers must have a name (which is a non-empty string). Calling `getLogger()` multiple times with the same name will return an identical logger object. In large applications, it can be incredibly useful to turn logging on and off for particular modules as you are working with them. Using the `getLogger()` method lets you create a separate logger for each part of your application with its own logging level. Likewise, for small, independent modules, using a named logger instead of the default root logger allows developers using your module to selectively turn on deep, trace-level logging when trying to debug problems, while logging only errors or silencing logging altogether under normal circumstances. Example usage *(using CommonJS modules, but you could do the same with any module system):* ```javascript // In module-one.js: var log = require("loglevel").getLogger("module-one"); function doSomethingAmazing() { log.debug("Amazing message from module one."); } // In module-two.js: var log = require("loglevel").getLogger("module-two"); function doSomethingSpecial() { log.debug("Special message from module two."); } // In your main application module: var log = require("loglevel"); var moduleOne = require("module-one"); var moduleTwo = require("module-two"); log.getLogger("module-two").setLevel("TRACE"); moduleOne.doSomethingAmazing(); moduleTwo.doSomethingSpecial(); // logs "Special message from module two." // (but nothing from module one.) ``` Loggers returned by `getLogger()` support all the same properties and methods as the default root logger, excepting `noConflict()` and the `getLogger()` method itself. Like the root logger, other loggers can have their logging level saved. If a logger’s level has not been saved, it will inherit the root logger’s level when it is first created. If the root logger’s level changes later, the new level will not affect other loggers that have already been created. Likewise, loggers will inherit the root logger’s `methodFactory`. After creation, each logger can have its `methodFactory` independently set. See the *plugins* section below for more about `methodFactory`. * A `log.getLoggers()` method. This will return you the dictionary of all loggers created with `getLogger`, keyed off of their names. ## Plugins ### Existing plugins: [loglevel-plugin-prefix](https://github.com/kutuluk/loglevel-plugin-prefix) - plugin for loglevel message prefixing. [loglevel-plugin-remote](https://github.com/kutuluk/loglevel-plugin-remote) - plugin for sending loglevel messages to a remote log server. ServerSend - https://github.com/artemyarulin/loglevel-serverSend - Forward your log messages to a remote server. Standard Streams - https://github.com/NatLibFi/loglevel-std-streams - Route logging through STDERR in Node for easier log management. Message Prefix - https://github.com/NatLibFi/loglevel-message-prefix - Dynamic (timestamp/level) and static ('foo') message prefixing. Message Buffer - https://github.com/NatLibFi/loglevel-message-buffer - Buffer messages, and flush them on-demand later. DEBUG - https://github.com/vectrlabs/loglevel-debug - Control logging from a DEBUG environmental variable (similar to the classic [Debug](https://github.com/visionmedia/debug) module) ### Writing plugins: Loglevel provides a simple reliable minimal base for console logging that works everywhere. This means it doesn't include lots of fancy functionality that might be useful in some cases, such as log formatting and redirection (e.g. also sending log messages to a server over AJAX) Including that would increase the size and complexity of the library, but more importantly would remove stacktrace information. Currently log methods are either disabled, or enabled with directly bound versions of the console.log methods (where possible). This means your browser shows the log message as coming from your code at the call to `log.info("message!")` not from within loglevel, since it really calls the bound console method directly, without indirection. The indirection required to dynamically format, further filter, or redirect log messages would stop this. There's clearly enough enthusiasm for this even at that cost though that loglevel now includes a plugin API. To use it, redefine log.methodFactory(methodName, logLevel, loggerName) with a function of your own. This will be called for each enabled method each time the level is set (including initially), and should return a function to be used for the given log method, at the given level, for a logger with the given name. If you'd like to retain all the reliability and features of loglevel, it's recommended that this wraps the initially provided value of `log.methodFactory` For example, a plugin to prefix all log messages with "Newsflash: " would look like: ```javascript var originalFactory = log.methodFactory; log.methodFactory = function (methodName, logLevel, loggerName) { var rawMethod = originalFactory(methodName, logLevel, loggerName); return function (message) { rawMethod("Newsflash: " + message); }; }; log.setLevel(log.getLevel()); // Be sure to call setLevel method in order to apply plugin ``` *(The above supports only a single log.warn("") argument for clarity, but it's easy to extend to a [fuller varadic version](http://jsbin.com/xehoye/edit?html,console))* If you develop and release a plugin, please get in contact! I'd be happy to reference it here for future users. Some consistency is helpful; naming your plugin 'loglevel-PLUGINNAME' (e.g. loglevel-newsflash) is preferred, as is giving it the 'loglevel-plugin' keyword in your package.json ## Developing & Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Builds can be run with npm: run `npm run dist` to build a distributable version of the project (in /dist), or `npm test` to just run the tests and linting. During development you can run `npm run watch` and it will monitor source files, and rerun the tests and linting as appropriate when they're changed. _Also, please don't manually edit files in the "dist" subdirectory as they are generated via Grunt. You'll find source code in the "lib" subdirectory!_ #### Release process To do a release of loglevel: * Update the version number in package.json and bower.json * Run `npm run dist` to build a distributable version in dist/ * Update the release history in this file (below) * Commit the built code, tagging it with the version number and a brief message about the release * Push to Github * Run `npm publish .` to publish to NPM ## Release History v0.1.0 - First working release with apparent compatibility with everything tested v0.2.0 - Updated release with various tweaks and polish and real proper documentation attached v0.3.0 - Some bugfixes (#12, #14), cookie-based log level persistence, doc tweaks, support for Bower and JamJS v0.3.1 - Fixed incorrect text in release build banner, various other minor tweaks v0.4.0 - Use LocalStorage for level persistence if available, compatibility improvements for IE, improved error messages, multi-environment tests v0.5.0 - Fix for Modernizr+IE8 issues, improved setLevel error handling, support for auto-activation of desired logging when console eventually turns up in IE8 v0.6.0 - Handle logging in Safari private browsing mode (#33), fix TRACE level persistence bug (#35), plus various minor tweaks v1.0.0 - Official stable release! Fixed a bug with localStorage in Android webviews, improved CommonJS detection, and added noConflict(). v1.1.0 - Added support for including loglevel with preprocessing and .apply() (#50), and fixed QUnit dep version which made tests potentially unstable. v1.2.0 - New plugin API! Plus various bits of refactoring and tidy up, nicely simplifying things and trimming the size down. v1.3.0 - Make persistence optional in setLevel, plus lots of documentation updates and other small tweaks v1.3.1 - With the new optional persistence, stop unnecessarily persisting the initially set default level (warn) v1.4.0 - Add getLevel(), setDefaultLevel() and getLogger() functionality for more fine-grained log level control v1.4.1 - Reorder UMD (#92) to improve bundling tool compatibility v1.5.0 - Fix log.debug (#111) after V8 changes deprecating console.debug, check for `window` upfront (#104), and add `.log` alias for `.debug` (#64) v1.5.1 - Fix bug (#112) in level-persistence cookie fallback, which failed if it wasn't the first cookie present v1.6.0 - Add a name property to loggers and add log.getLoggers() (#114), and recommend unpkg as CDN instead of CDNJS. v1.6.1 - Various small documentation & test updates ## License Copyright (c) 2013 Tim Perry Licensed under the MIT license. # npm-packlist [![Build Status](https://travis-ci.com/npm/npm-packlist.svg?token=hHeDp9pQmz9kvsgRNVHy&branch=master)](https://travis-ci.com/npm/npm-packlist) Get a list of the files to add from a folder into an npm package These can be handed to [tar](http://npm.im/tar) like so to make an npm package tarball: ```js const packlist = require('npm-packlist') const tar = require('tar') const packageDir = '/path/to/package' const packageTarball = '/path/to/package.tgz' packlist({ path: packageDir }) .then(files => tar.create({ prefix: 'package/', cwd: packageDir, file: packageTarball, gzip: true }, files)) .then(_ => { // tarball has been created, continue with your day }) ``` This uses the following rules: 1. If a `package.json` file is found, and it has a `files` list, then ignore everything that isn't in `files`. Always include the readme, license, notice, changes, changelog, and history files, if they exist, and the package.json file itself. 2. If there's no `package.json` file (or it has no `files` list), and there is a `.npmignore` file, then ignore all the files in the `.npmignore` file. 3. If there's no `package.json` with a `files` list, and there's no `.npmignore` file, but there is a `.gitignore` file, then ignore all the files in the `.gitignore` file. 4. Everything in the root `node_modules` is ignored, unless it's a bundled dependency. If it IS a bundled dependency, and it's a symbolic link, then the target of the link is included, not the symlink itself. 4. Unless they're explicitly included (by being in a `files` list, or a `!negated` rule in a relevant `.npmignore` or `.gitignore`), always ignore certain common cruft files: 1. .npmignore and .gitignore files (their effect is in the package already, there's no need to include them in the package) 2. editor junk like `.*.swp`, `._*` and `.*.orig` files 3. `.npmrc` files (these may contain private configs) 4. The `node_modules/.bin` folder 5. Waf and gyp cruft like `/build/config.gypi` and `.lock-wscript` 6. Darwin's `.DS_Store` files because wtf are those even 7. `npm-debug.log` files at the root of a project You can explicitly re-include any of these with a `files` list in `package.json` or a negated ignore file rule. ## API Same API as [ignore-walk](http://npm.im/ignore-walk), just hard-coded file list and rule sets. The `Walker` and `WalkerSync` classes take a `bundled` argument, which is a list of package names to include from node_modules. When calling the top-level `packlist()` and `packlist.sync()` functions, this module calls into `npm-bundled` directly. # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # Hackathon Leaderboard This is the react + firebase app for the NEAR hackathon leaderboard. ## Development For dev `npm start` to launch the hot reloader and do some cool stuff. Go to `localhost:8080` to see it in action. For prod build `npm run build` ## NOTE For firebase to work, you need a config object that is stored in `src/fire.js`. This is notably missing from the public repo. You can use this with any firebase project by dropping the default config and init into `fire.js`. TODO: - Get firebase to work... - Add users and auth - Add Admin dash for adding points # HTTP Parser This library parses HTTP protocol for requests and responses. It was created to replace `http_parser.c` since calling C++ function from JS is really slow in V8. This was further modified by Jimbly to be useable in parsing responses, specifically tested with the "request" module, and addresses issues such as corrupt HTTP headers, which would otherwise cause Node's parser to throw a fatal error (HPE_INVALID_HEADER_TOKEN). Jan Schär (jscissr) made some bigger changes and added tests. This fixed some bugs and added many missing features. This is packaged as a standalone npm module. To use in node, monkeypatch HTTPParser. ```js // Monkey patch before you require http for the first time. process.binding('http_parser').HTTPParser = require('http-parser-js').HTTPParser; var http = require('http'); // ... ``` ## Testing Simply do `npm test`. The tests are copied from node and mscedex/io.js, with some modifcations. ## Status This should now be usable in any node application, it now supports (nearly) everything `http_parser.c` does while still being tolerant with corrupted headers. ## License MIT. See LICENSE.md # readdirp [![Build Status](https://secure.travis-ci.org/thlorenz/readdirp.svg)](http://travis-ci.org/thlorenz/readdirp) [![NPM](https://nodei.co/npm/readdirp.png?downloads=true&stars=true)](https://nodei.co/npm/readdirp/) Recursive version of [fs.readdir](http://nodejs.org/docs/latest/api/fs.html#fs_fs_readdir_path_callback). Exposes a **stream api**. ```javascript var readdirp = require('readdirp') , path = require('path') , es = require('event-stream'); // print out all JavaScript files along with their size var stream = readdirp({ root: path.join(__dirname), fileFilter: '*.js' }); stream .on('warn', function (err) { console.error('non-fatal error', err); // optionally call stream.destroy() here in order to abort and cause 'close' to be emitted }) .on('error', function (err) { console.error('fatal error', err); }) .pipe(es.mapSync(function (entry) { return { path: entry.path, size: entry.stat.size }; })) .pipe(es.stringify()) .pipe(process.stdout); ``` Meant to be one of the recursive versions of [fs](http://nodejs.org/docs/latest/api/fs.html) functions, e.g., like [mkdirp](https://github.com/substack/node-mkdirp). **Table of Contents** *generated with [DocToc](http://doctoc.herokuapp.com/)* - [Installation](#installation) - [API](#api) - [entry stream](#entry-stream) - [options](#options) - [entry info](#entry-info) - [Filters](#filters) - [Callback API](#callback-api) - [allProcessed ](#allprocessed) - [fileProcessed](#fileprocessed) - [More Examples](#more-examples) - [stream api](#stream-api) - [stream api pipe](#stream-api-pipe) - [grep](#grep) - [using callback api](#using-callback-api) - [tests](#tests) # Installation npm install readdirp # API ***var entryStream = readdirp (options)*** Reads given root recursively and returns a `stream` of [entry info](#entry-info)s. ## entry stream Behaves as follows: - `emit('data')` passes an [entry info](#entry-info) whenever one is found - `emit('warn')` passes a non-fatal `Error` that prevents a file/directory from being processed (i.e., if it is inaccessible to the user) - `emit('error')` passes a fatal `Error` which also ends the stream (i.e., when illegal options where passed) - `emit('end')` called when all entries were found and no more will be emitted (i.e., we are done) - `emit('close')` called when the stream is destroyed via `stream.destroy()` (which could be useful if you want to manually abort even on a non fatal error) - at that point the stream is no longer `readable` and no more entries, warning or errors are emitted - to learn more about streams, consult the very detailed [nodejs streams documentation](http://nodejs.org/api/stream.html) or the [stream-handbook](https://github.com/substack/stream-handbook) ## options - **root**: path in which to start reading and recursing into subdirectories - **fileFilter**: filter to include/exclude files found (see [Filters](#filters) for more) - **directoryFilter**: filter to include/exclude directories found and to recurse into (see [Filters](#filters) for more) - **depth**: depth at which to stop recursing even if more subdirectories are found - **entryType**: determines if data events on the stream should be emitted for `'files'`, `'directories'`, `'both'`, or `'all'`. Setting to `'all'` will also include entries for other types of file descriptors like character devices, unix sockets and named pipes. Defaults to `'files'`. - **lstat**: if `true`, readdirp uses `fs.lstat` instead of `fs.stat` in order to stat files and includes symlink entries in the stream along with files. ## entry info Has the following properties: - **parentDir** : directory in which entry was found (relative to given root) - **fullParentDir** : full path to parent directory - **name** : name of the file/directory - **path** : path to the file/directory (relative to given root) - **fullPath** : full path to the file/directory found - **stat** : built in [stat object](http://nodejs.org/docs/v0.4.9/api/fs.html#fs.Stats) - **Example**: (assuming root was `/User/dev/readdirp`) parentDir : 'test/bed/root_dir1', fullParentDir : '/User/dev/readdirp/test/bed/root_dir1', name : 'root_dir1_subdir1', path : 'test/bed/root_dir1/root_dir1_subdir1', fullPath : '/User/dev/readdirp/test/bed/root_dir1/root_dir1_subdir1', stat : [ ... ] ## Filters There are three different ways to specify filters for files and directories respectively. - **function**: a function that takes an entry info as a parameter and returns true to include or false to exclude the entry - **glob string**: a string (e.g., `*.js`) which is matched using [minimatch](https://github.com/isaacs/minimatch), so go there for more information. Globstars (`**`) are not supported since specifying a recursive pattern for an already recursive function doesn't make sense. Negated globs (as explained in the minimatch documentation) are allowed, e.g., `!*.txt` matches everything but text files. - **array of glob strings**: either need to be all inclusive or all exclusive (negated) patterns otherwise an error is thrown. `[ '*.json', '*.js' ]` includes all JavaScript and Json files. `[ '!.git', '!node_modules' ]` includes all directories except the '.git' and 'node_modules'. Directories that do not pass a filter will not be recursed into. ## Callback API Although the stream api is recommended, readdirp also exposes a callback based api. ***readdirp (options, callback1 [, callback2])*** If callback2 is given, callback1 functions as the **fileProcessed** callback, and callback2 as the **allProcessed** callback. If only callback1 is given, it functions as the **allProcessed** callback. ### allProcessed - function with err and res parameters, e.g., `function (err, res) { ... }` - **err**: array of errors that occurred during the operation, **res may still be present, even if errors occurred** - **res**: collection of file/directory [entry infos](#entry-info) ### fileProcessed - function with [entry info](#entry-info) parameter e.g., `function (entryInfo) { ... }` # More Examples `on('error', ..)`, `on('warn', ..)` and `on('end', ..)` handling omitted for brevity ```javascript var readdirp = require('readdirp'); // Glob file filter readdirp({ root: './test/bed', fileFilter: '*.js' }) .on('data', function (entry) { // do something with each JavaScript file entry }); // Combined glob file filters readdirp({ root: './test/bed', fileFilter: [ '*.js', '*.json' ] }) .on('data', function (entry) { // do something with each JavaScript and Json file entry }); // Combined negated directory filters readdirp({ root: './test/bed', directoryFilter: [ '!.git', '!*modules' ] }) .on('data', function (entry) { // do something with each file entry found outside '.git' or any modules directory }); // Function directory filter readdirp({ root: './test/bed', directoryFilter: function (di) { return di.name.length === 9; } }) .on('data', function (entry) { // do something with each file entry found inside directories whose name has length 9 }); // Limiting depth readdirp({ root: './test/bed', depth: 1 }) .on('data', function (entry) { // do something with each file entry found up to 1 subdirectory deep }); // callback api readdirp({ root: '.' }, function(fileInfo) { // do something with file entry here }, function (err, res) { // all done, move on or do final step for all file entries here }); ``` Try more examples by following [instructions](https://github.com/paulmillr/readdirp/blob/master/examples/Readme.md) on how to get going. ## tests The [readdirp tests](https://github.com/paulmillr/readdirp/blob/master/test/readdirp.js) also will give you a good idea on how things work. # fast-json-stable-stringify Deterministic `JSON.stringify()` - a faster version of [@substack](https://github.com/substack)'s json-stable-strigify without [jsonify](https://github.com/substack/jsonify). You can also pass in a custom comparison function. [![Build Status](https://travis-ci.org/epoberezkin/fast-json-stable-stringify.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-json-stable-stringify) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-json-stable-stringify/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-json-stable-stringify?branch=master) # example ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; console.log(stringify(obj)); ``` output: ``` {"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8} ``` # methods ``` js var stringify = require('fast-json-stable-stringify') ``` ## var str = stringify(obj, opts) Return a deterministic stringified string `str` from the object `obj`. ## options ### cmp If `opts` is given, you can supply an `opts.cmp` to have a custom comparison function for object keys. Your function `opts.cmp` is called with these parameters: ``` js opts.cmp({ key: akey, value: avalue }, { key: bkey, value: bvalue }) ``` For example, to sort on the object key names in reverse order you could write: ``` js var stringify = require('fast-json-stable-stringify'); var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; var s = stringify(obj, function (a, b) { return a.key < b.key ? 1 : -1; }); console.log(s); ``` which results in the output string: ``` {"c":8,"b":[{"z":6,"y":5,"x":4},7],"a":3} ``` Or if you wanted to sort on the object values in reverse order, you could write: ``` var stringify = require('fast-json-stable-stringify'); var obj = { d: 6, c: 5, b: [{z:3,y:2,x:1},9], a: 10 }; var s = stringify(obj, function (a, b) { return a.value < b.value ? 1 : -1; }); console.log(s); ``` which outputs: ``` {"d":6,"c":5,"b":[{"z":3,"y":2,"x":1},9],"a":10} ``` ### cycles Pass `true` in `opts.cycles` to stringify circular property as `__cycle__` - the result will not be a valid JSON string in this case. TypeError will be thrown in case of circular object without this option. # install With [npm](https://npmjs.org) do: ``` npm install fast-json-stable-stringify ``` # benchmark To run benchmark (requires Node.js 6+): ``` node benchmark ``` Results: ``` fast-json-stable-stringify x 17,189 ops/sec ±1.43% (83 runs sampled) json-stable-stringify x 13,634 ops/sec ±1.39% (85 runs sampled) fast-stable-stringify x 20,212 ops/sec ±1.20% (84 runs sampled) faster-stable-stringify x 15,549 ops/sec ±1.12% (84 runs sampled) The fastest is fast-stable-stringify ``` # license [MIT](https://github.com/epoberezkin/fast-json-stable-stringify/blob/master/LICENSE) <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![cover][cover]][cover-url] [![chat][chat]][chat-url] [![size][size]][size-url] # terser-webpack-plugin This plugin uses [terser](https://github.com/terser-js/terser) to minify your JavaScript. ## Requirements This module requires a minimum of Node v6.9.0 and Webpack v4.0.0. ## Getting Started To begin, you'll need to install `terser-webpack-plugin`: ```console $ npm install terser-webpack-plugin --save-dev ``` Then add the plugin to your `webpack` config. For example: **webpack.config.js** ```js const TerserPlugin = require('terser-webpack-plugin'); module.exports = { optimization: { minimizer: [new TerserPlugin()], }, }; ``` And run `webpack` via your preferred method. ## Options ### `test` Type: `String|RegExp|Array<String|RegExp>` Default: `/\.m?js(\?.*)?$/i` Test to match files against. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ test: /\.js(\?.*)?$/i, }), ], }, }; ``` ### `include` Type: `String|RegExp|Array<String|RegExp>` Default: `undefined` Files to include. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ include: /\/includes/, }), ], }, }; ``` ### `exclude` Type: `String|RegExp|Array<String|RegExp>` Default: `undefined` Files to exclude. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ exclude: /\/excludes/, }), ], }, }; ``` ### `chunkFilter` Type: `Function<(chunk) -> boolean>` Default: `() => true` Allowing to filter which chunks should be uglified (by default all chunks are uglified). Return `true` to uglify the chunk, `false` otherwise. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ chunkFilter: (chunk) => { // Exclude uglification for the `vendor` chunk if (chunk.name === 'vendor') { return false; } return true; }, }), ], }, }; ``` ### `cache` Type: `Boolean|String` Default: `false` Enable file caching. Default path to cache directory: `node_modules/.cache/terser-webpack-plugin`. > ℹ️ If you use your own `minify` function please read the `minify` section for cache invalidation correctly. #### `Boolean` Enable/disable file caching. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ cache: true, }), ], }, }; ``` #### `String` Enable file caching and set path to cache directory. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ cache: 'path/to/cache', }), ], }, }; ``` ### `cacheKeys` Type: `Function<(defaultCacheKeys, file) -> Object>` Default: `defaultCacheKeys => defaultCacheKeys` Allows you to override default cache keys. Default cache keys: ```js ({ terser: require('terser/package.json').version, // terser version 'terser-webpack-plugin': require('../package.json').version, // plugin version 'terser-webpack-plugin-options': this.options, // plugin options path: compiler.outputPath ? `${compiler.outputPath}/${file}` : file, // asset path hash: crypto .createHash('md4') .update(input) .digest('hex'), // source file hash }); ``` **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ cache: true, cacheKeys: (defaultCacheKeys, file) => { defaultCacheKeys.myCacheKey = 'myCacheKeyValue'; return defaultCacheKeys; }, }), ], }, }; ``` ### `parallel` Type: `Boolean|Number` Default: `false` Use multi-process parallel running to improve the build speed. Default number of concurrent runs: `os.cpus().length - 1`. > ℹ️ Parallelization can speedup your build significantly and is therefore **highly recommended**. #### `Boolean` Enable/disable multi-process parallel running. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ parallel: true, }), ], }, }; ``` #### `Number` Enable multi-process parallel running and set number of concurrent runs. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ parallel: 4, }), ], }, }; ``` ### `sourceMap` Type: `Boolean` Default: `false` Use source maps to map error message locations to modules (this slows down the compilation). If you use your own `minify` function please read the `minify` section for handling source maps correctly. > ⚠️ **`cheap-source-map` options don't work with this plugin**. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ sourceMap: true, }), ], }, }; ``` ### `minify` Type: `Function` Default: `undefined` Allows you to override default minify function. By default plugin uses [terser](https://github.com/terser-js/terser) package. Useful for using and testing unpublished versions or forks. > ⚠️ **Always use `require` inside `minify` function when `parallel` option enabled**. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ minify: (file, sourceMap) => { const extractedComments = []; // Custom logic for extract comments const { error, map, code, warnings } = require('uglify-module') // Or require('./path/to/uglify-module') .minify(file, { /* Your options for minification */ }); return { error, map, code, warnings, extractedComments }; }, }), ], }, }; ``` ### `terserOptions` Type: `Object` Default: [default](https://github.com/terser-js/terser#minify-options) Terser minify [options](https://github.com/terser-js/terser#minify-options). **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ terserOptions: { ecma: undefined, warnings: false, parse: {}, compress: {}, mangle: true, // Note `mangle.properties` is `false` by default. module: false, output: null, toplevel: false, nameCache: null, ie8: false, keep_classnames: undefined, keep_fnames: false, safari10: false, }, }), ], }, }; ``` ### `extractComments` Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>|Object` Default: `false` Whether comments shall be extracted to a separate file, (see [details](https://github.com/webpack/webpack/commit/71933e979e51c533b432658d5e37917f9e71595a)). By default extract only comments using `/^\**!|@preserve|@license|@cc_on/i` regexp condition and remove remaining comments. If the original file is named `foo.js`, then the comments will be stored to `foo.js.LICENSE`. The `terserOptions.output.comments` option specifies whether the comment will be preserved, i.e. it is possible to preserve some comments (e.g. annotations) while extracting others or even preserving comments that have been extracted. #### `Boolean` Enable/disable extracting comments. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: true, }), ], }, }; ``` #### `String` Extract `all` or `some` (use `/^\**!|@preserve|@license|@cc_on/i` RegExp) comments. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: 'all', }), ], }, }; ``` #### `RegExp` All comments that match the given expression will be extracted to the separate file. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: /@extract/i, }), ], }, }; ``` #### `Function<(node, comment) -> Boolean>` All comments that match the given expression will be extracted to the separate file. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: (astNode, comment) => { if (/@extract/i.test(comment.value)) { return true; } return false; }, }), ], }, }; ``` #### `Object` Allow to customize condition for extract comments, specify extracted file name and banner. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: { condition: /^\**!|@preserve|@license|@cc_on/i, filename: (file) => { return `${file}.LICENSE`; }, banner: (licenseFile) => { return `License information can be found in ${licenseFile}`; }, }, }), ], }, }; ``` ##### `condition` Type: `Boolean|String|RegExp|Function<(node, comment) -> Boolean|Object>` Condition what comments you need extract. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: { condition: 'some', filename: (file) => { return `${file}.LICENSE`; }, banner: (licenseFile) => { return `License information can be found in ${licenseFile}`; }, }, }), ], }, }; ``` ##### `filename` Type: `String|Function<(string) -> String>` Default: `${file}.LICENSE` The file where the extracted comments will be stored. Default is to append the suffix `.LICENSE` to the original filename. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: { condition: /^\**!|@preserve|@license|@cc_on/i, filename: 'extracted-comments.js', banner: (licenseFile) => { return `License information can be found in ${licenseFile}`; }, }, }), ], }, }; ``` ##### `banner` Type: `Boolean|String|Function<(string) -> String>` Default: `/*! For license information please see ${commentsFile} */` The banner text that points to the extracted file and will be added on top of the original file. Can be `false` (no banner), a `String`, or a `Function<(string) -> String>` that will be called with the filename where extracted comments have been stored. Will be wrapped into comment. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ extractComments: { condition: true, filename: (file) => { return `${file}.LICENSE`; }, banner: (commentsFile) => { return `My custom banner about license information ${commentsFile}`; }, }, }), ], }, }; ``` ### `warningsFilter` Type: `Function<(warning, source) -> Boolean>` Default: `() => true` Allow to filter [terser](https://github.com/terser-js/terser) warnings. Return `true` to keep the warning, `false` otherwise. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ warningsFilter: (warning, source) => { if (/Dropping unreachable code/i.test(warning)) { return true; } if (/filename\.js/i.test(source)) { return true; } return false; }, }), ], }, }; ``` ## Examples ### Cache And Parallel Enable cache and multi-process parallel running. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ cache: true, parallel: true, }), ], }, }; ``` ### Preserve Comments Extract all legal comments (i.e. `/^\**!|@preserve|@license|@cc_on/i`) and preserve `/@license/i` comments. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ terserOptions: { output: { comments: /@license/i, }, }, extractComments: true, }), ], }, }; ``` ### Remove Comments If you avoid building with comments, set **terserOptions.output.comments** to **false** as in this config: **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ terserOptions: { output: { comments: false, }, }, }), ], }, }; ``` ### Custom Minify Function Override default minify function - use `uglify-js` for minification. **webpack.config.js** ```js module.exports = { optimization: { minimizer: [ new TerserPlugin({ // Uncomment lines below for cache invalidation correctly // cache: true, // cacheKeys: (defaultCacheKeys) => { // delete defaultCacheKeys.terser; // // return Object.assign( // {}, // defaultCacheKeys, // { 'uglify-js': require('uglify-js/package.json').version }, // ); // }, minify: (file, sourceMap) => { // https://github.com/mishoo/UglifyJS2#minify-options const uglifyJsOptions = { /* your `uglify-js` package options */ }; if (sourceMap) { uglifyJsOptions.sourceMap = { content: sourceMap, }; } return require('uglify-js').minify(file, uglifyJsOptions); }, }), ], }, }; ``` ## Contributing Please take a moment to read our contributing guidelines if you haven't yet done so. [CONTRIBUTING](./.github/CONTRIBUTING.md) ## License [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/terser-webpack-plugin.svg [npm-url]: https://npmjs.com/package/terser-webpack-plugin [node]: https://img.shields.io/node/v/terser-webpack-plugin.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack-contrib/terser-webpack-plugin.svg [deps-url]: https://david-dm.org/webpack-contrib/terser-webpack-plugin [tests]: https://img.shields.io/circleci/project/github/webpack-contrib/terser-webpack-plugin.svg [tests-url]: https://circleci.com/gh/webpack-contrib/terser-webpack-plugin [cover]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/terser-webpack-plugin [chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg [chat-url]: https://gitter.im/webpack/webpack [size]: https://packagephobia.now.sh/badge?p=terser-webpack-plugin [size-url]: https://packagephobia.now.sh/result?p=terser-webpack-plugin # websocket-driver [![Build Status](https://travis-ci.org/faye/websocket-driver-node.svg)](https://travis-ci.org/faye/websocket-driver-node) This module provides a complete implementation of the WebSocket protocols that can be hooked up to any I/O stream. It aims to simplify things by decoupling the protocol details from the I/O layer, such that users only need to implement code to stream data in and out of it without needing to know anything about how the protocol actually works. Think of it as a complete WebSocket system with pluggable I/O. Due to this design, you get a lot of things for free. In particular, if you hook this module up to some I/O object, it will do all of this for you: * Select the correct server-side driver to talk to the client * Generate and send both server- and client-side handshakes * Recognize when the handshake phase completes and the WS protocol begins * Negotiate subprotocol selection based on `Sec-WebSocket-Protocol` * Negotiate and use extensions via the [websocket-extensions](https://github.com/faye/websocket-extensions-node) module * Buffer sent messages until the handshake process is finished * Deal with proxies that defer delivery of the draft-76 handshake body * Notify you when the socket is open and closed and when messages arrive * Recombine fragmented messages * Dispatch text, binary, ping, pong and close frames * Manage the socket-closing handshake process * Automatically reply to ping frames with a matching pong * Apply masking to messages sent by the client This library was originally extracted from the [Faye](http://faye.jcoglan.com) project but now aims to provide simple WebSocket support for any Node-based project. ## Installation ``` $ npm install websocket-driver ``` ## Usage This module provides protocol drivers that have the same interface on the server and on the client. A WebSocket driver is an object with two duplex streams attached; one for incoming/outgoing messages and one for managing the wire protocol over an I/O stream. The full API is described below. ### Server-side with HTTP A Node webserver emits a special event for 'upgrade' requests, and this is where you should handle WebSockets. You first check whether the request is a WebSocket, and if so you can create a driver and attach the request's I/O stream to it. ```js var http = require('http'), websocket = require('websocket-driver'); var server = http.createServer(); server.on('upgrade', function(request, socket, body) { if (!websocket.isWebSocket(request)) return; var driver = websocket.http(request); driver.io.write(body); socket.pipe(driver.io).pipe(socket); driver.messages.on('data', function(message) { console.log('Got a message', message); }); driver.start(); }); ``` Note the line `driver.io.write(body)` - you must pass the `body` buffer to the socket driver in order to make certain versions of the protocol work. ### Server-side with TCP You can also handle WebSocket connections in a bare TCP server, if you're not using an HTTP server and don't want to implement HTTP parsing yourself. The driver will emit a `connect` event when a request is received, and at this point you can detect whether it's a WebSocket and handle it as such. Here's an example using the Node `net` module: ```js var net = require('net'), websocket = require('websocket-driver'); var server = net.createServer(function(connection) { var driver = websocket.server(); driver.on('connect', function() { if (websocket.isWebSocket(driver)) { driver.start(); } else { // handle other HTTP requests } }); driver.on('close', function() { connection.end() }); connection.on('error', function() {}); connection.pipe(driver.io).pipe(connection); driver.messages.pipe(driver.messages); }); server.listen(4180); ``` In the `connect` event, the driver gains several properties to describe the request, similar to a Node request object, such as `method`, `url` and `headers`. However you should remember it's not a real request object; you cannot write data to it, it only tells you what request data we parsed from the input. If the request has a body, it will be in the `driver.body` buffer, but only as much of the body as has been piped into the driver when the `connect` event fires. ### Client-side Similarly, to implement a WebSocket client you just need to make a driver by passing in a URL. After this you use the driver API as described below to process incoming data and send outgoing data. ```js var net = require('net'), websocket = require('websocket-driver'); var driver = websocket.client('ws://www.example.com/socket'), tcp = net.connect(80, 'www.example.com'); tcp.pipe(driver.io).pipe(tcp); tcp.on('connect', function() { driver.start(); }); driver.messages.on('data', function(message) { console.log('Got a message', message); }); ``` Client drivers have two additional properties for reading the HTTP data that was sent back by the server: * `driver.statusCode` - the integer value of the HTTP status code * `driver.headers` - an object containing the response headers ### HTTP Proxies The client driver supports connections via HTTP proxies using the `CONNECT` method. Instead of sending the WebSocket handshake immediately, it will send a `CONNECT` request, wait for a `200` response, and then proceed as normal. To use this feature, call `driver.proxy(url)` where `url` is the origin of the proxy, including a username and password if required. This produces a duplex stream that you should pipe in and out of your TCP connection to the proxy server. When the proxy emits `connect`, you can then pipe `driver.io` to your TCP stream and call `driver.start()`. ```js var net = require('net'), websocket = require('websocket-driver'); var driver = websocket.client('ws://www.example.com/socket'), proxy = driver.proxy('http://username:[email protected]'), tcp = net.connect(80, 'proxy.example.com'); tcp.pipe(proxy).pipe(tcp, {end: false}); tcp.on('connect', function() { proxy.start(); }); proxy.on('connect', function() { driver.io.pipe(tcp).pipe(driver.io); driver.start(); }); driver.messages.on('data', function(message) { console.log('Got a message', message); }); ``` The proxy's `connect` event is also where you should perform a TLS handshake on your TCP stream, if you are connecting to a `wss:` endpoint. In the event that proxy connection fails, `proxy` will emit an `error`. You can inspect the proxy's response via `proxy.statusCode` and `proxy.headers`. ```js proxy.on('error', function(error) { console.error(error.message); console.log(proxy.statusCode); console.log(proxy.headers); }); ``` Before calling `proxy.start()` you can set custom headers using `proxy.setHeader()`: ```js proxy.setHeader('User-Agent', 'node'); proxy.start(); ``` ### Driver API Drivers are created using one of the following methods: ```js driver = websocket.http(request, options) driver = websocket.server(options) driver = websocket.client(url, options) ``` The `http` method returns a driver chosen using the headers from a Node HTTP request object. The `server` method returns a driver that will parse an HTTP request and then decide which driver to use for it using the `http` method. The `client` method always returns a driver for the RFC version of the protocol with masking enabled on outgoing frames. The `options` argument is optional, and is an object. It may contain the following fields: * `maxLength` - the maximum allowed size of incoming message frames, in bytes. The default value is `2^26 - 1`, or 1 byte short of 64 MiB. * `protocols` - an array of strings representing acceptable subprotocols for use over the socket. The driver will negotiate one of these to use via the `Sec-WebSocket-Protocol` header if supported by the other peer. A driver has two duplex streams attached to it: * <b>`driver.io`</b> - this stream should be attached to an I/O socket like a TCP stream. Pipe incoming TCP chunks to this stream for them to be parsed, and pipe this stream back into TCP to send outgoing frames. * <b>`driver.messages`</b> - this stream emits messages received over the WebSocket. Writing to it sends messages to the other peer by emitting frames via the `driver.io` stream. All drivers respond to the following API methods, but some of them are no-ops depending on whether the client supports the behaviour. Note that most of these methods are commands: if they produce data that should be sent over the socket, they will give this to you by emitting `data` events on the `driver.io` stream. #### `driver.on('open', function(event) {})` Adds a callback to execute when the socket becomes open. #### `driver.on('message', function(event) {})` Adds a callback to execute when a message is received. `event` will have a `data` attribute containing either a string in the case of a text message or a `Buffer` in the case of a binary message. You can also listen for messages using the `driver.messages.on('data')` event, which emits strings for text messages and buffers for binary messages. #### `driver.on('error', function(event) {})` Adds a callback to execute when a protocol error occurs due to the other peer sending an invalid byte sequence. `event` will have a `message` attribute describing the error. #### `driver.on('close', function(event) {})` Adds a callback to execute when the socket becomes closed. The `event` object has `code` and `reason` attributes. #### `driver.on('ping', function(event) {})` Adds a callback block to execute when a ping is received. You do not need to handle this by sending a pong frame yourself; the driver handles this for you. #### `driver.on('pong', function(event) {})` Adds a callback block to execute when a pong is received. If this was in response to a ping you sent, you can also handle this event via the `driver.ping(message, function() { ... })` callback. #### `driver.addExtension(extension)` Registers a protocol extension whose operation will be negotiated via the `Sec-WebSocket-Extensions` header. `extension` is any extension compatible with the [websocket-extensions](https://github.com/faye/websocket-extensions-node) framework. #### `driver.setHeader(name, value)` Sets a custom header to be sent as part of the handshake response, either from the server or from the client. Must be called before `start()`, since this is when the headers are serialized and sent. #### `driver.start()` Initiates the protocol by sending the handshake - either the response for a server-side driver or the request for a client-side one. This should be the first method you invoke. Returns `true` if and only if a handshake was sent. #### `driver.parse(string)` Takes a string and parses it, potentially resulting in message events being emitted (see `on('message')` above) or in data being sent to `driver.io`. You should send all data you receive via I/O to this method by piping a stream into `driver.io`. #### `driver.text(string)` Sends a text message over the socket. If the socket handshake is not yet complete, the message will be queued until it is. Returns `true` if the message was sent or queued, and `false` if the socket can no longer send messages. This method is equivalent to `driver.messages.write(string)`. #### `driver.binary(buffer)` Takes a `Buffer` and sends it as a binary message. Will queue and return `true` or `false` the same way as the `text` method. It will also return `false` if the driver does not support binary messages. This method is equivalent to `driver.messages.write(buffer)`. #### `driver.ping(string = '', function() {})` Sends a ping frame over the socket, queueing it if necessary. `string` and the callback are both optional. If a callback is given, it will be invoked when the socket receives a pong frame whose content matches `string`. Returns `false` if frames can no longer be sent, or if the driver does not support ping/pong. #### `driver.pong(string = '')` Sends a pong frame over the socket, queueing it if necessary. `string` is optional. Returns `false` if frames can no longer be sent, or if the driver does not support ping/pong. You don't need to call this when a ping frame is received; pings are replied to automatically by the driver. This method is for sending unsolicited pongs. #### `driver.close()` Initiates the closing handshake if the socket is still open. For drivers with no closing handshake, this will result in the immediate execution of the `on('close')` driver. For drivers with a closing handshake, this sends a closing frame and `emit('close')` will execute when a response is received or a protocol error occurs. #### `driver.version` Returns the WebSocket version in use as a string. Will either be `hixie-75`, `hixie-76` or `hybi-$version`. #### `driver.protocol` Returns a string containing the selected subprotocol, if any was agreed upon using the `Sec-WebSocket-Protocol` mechanism. This value becomes available after `emit('open')` has fired. # readable-stream ***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) ```bash npm install --save readable-stream ``` This package is a mirror of the streams implementations in Node.js. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.15.3/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. ## Version 3.x.x v3.x.x of `readable-stream` supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: 1. Error codes: https://github.com/nodejs/node/pull/13310, https://github.com/nodejs/node/pull/13291, https://github.com/nodejs/node/pull/16589, https://github.com/nodejs/node/pull/15042, https://github.com/nodejs/node/pull/15665, https://github.com/nodejs/readable-stream/pull/344 2. 'readable' have precedence over flowing https://github.com/nodejs/node/pull/18994 3. make virtual methods errors consistent https://github.com/nodejs/node/pull/18813 4. updated streams error handling https://github.com/nodejs/node/pull/18438 5. writable.end should return this. https://github.com/nodejs/node/pull/18780 6. readable continues to read when push('') https://github.com/nodejs/node/pull/18211 7. add custom inspect to BufferList https://github.com/nodejs/node/pull/17907 8. always defer 'readable' with nextTick https://github.com/nodejs/node/pull/17979 ## Version 2.x.x v2.x.x of `readable-stream` supports all Node.js version from 0.8, as well as evergreen browsers and IE 10 & 11. ### Big Thanks Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] # Usage You can swap your `require('stream')` with `require('readable-stream')` without any changes, if you are just using one of the main classes and functions. ```js const { Readable, Writable, Transform, Duplex, pipeline, finished } = require('readable-stream') ```` Note that `require('stream')` will return `Stream`, while `require('readable-stream')` will return `Readable`. We discourage using whatever is exported directly, but rather use one of the properties as shown in the example above. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; * **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;[email protected]&gt; [sauce]: https://saucelabs.com # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Mac/Linux Build Status](https://img.shields.io/travis/paulmillr/chokidar/master.svg?label=Mac%20OSX%20%26%20Linux)](https://travis-ci.org/paulmillr/chokidar) [![Windows Build status](https://img.shields.io/appveyor/ci/paulmillr/chokidar/master.svg?label=Windows)](https://ci.appveyor.com/project/paulmillr/chokidar/branch/master) [![Coverage Status](https://coveralls.io/repos/paulmillr/chokidar/badge.svg)](https://coveralls.io/r/paulmillr/chokidar) > A neat wrapper around node.js fs.watch / fs.watchFile / FSEvents. [![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar) ## Why? Node.js `fs.watch`: * Doesn't report filenames on MacOS. * Doesn't report events at all when using editors like Sublime on MacOS. * Often reports events twice. * Emits most changes as `rename`. * Has [a lot of other issues](https://github.com/nodejs/node/search?q=fs.watch&type=Issues) * Does not provide an easy way to recursively watch file trees. Node.js `fs.watchFile`: * Almost as bad at event handling. * Also does not provide any recursive watching. * Results in high CPU utilization. Chokidar resolves these problems. Initially made for **[Brunch](http://brunch.io)** (an ultra-swift web app build tool), it is now used in [gulp](https://github.com/gulpjs/gulp/), [karma](http://karma-runner.github.io), [PM2](https://github.com/Unitech/PM2), [browserify](http://browserify.org/), [webpack](http://webpack.github.io/), [BrowserSync](http://www.browsersync.io/), [Microsoft's Visual Studio Code](https://github.com/microsoft/vscode), and [many others](https://www.npmjs.org/browse/depended/chokidar/). It has proven itself in production environments. ## How? Chokidar does still rely on the Node.js core `fs` module, but when using `fs.watch` and `fs.watchFile` for watching, it normalizes the events it receives, often checking for truth by getting file stats and/or dir contents. On MacOS, chokidar by default uses a native extension exposing the Darwin `FSEvents` API. This provides very efficient recursive watching compared with implementations like `kqueue` available on most \*nix platforms. Chokidar still does have to do some work to normalize the events received that way as well. On other platforms, the `fs.watch`-based implementation is the default, which avoids polling and keeps CPU usage down. Be advised that chokidar will initiate watchers recursively for everything within scope of the paths that have been specified, so be judicious about not wasting system resources by watching much more than needed. ## Getting started Install with npm: ```sh npm install chokidar ``` Then `require` and use it in your code: ```javascript var chokidar = require('chokidar'); // One-liner for current directory, ignores .dotfiles chokidar.watch('.', {ignored: /(^|[\/\\])\../}).on('all', (event, path) => { console.log(event, path); }); ``` ```javascript // Example of a more typical implementation structure: // Initialize watcher. var watcher = chokidar.watch('file, dir, glob, or array', { ignored: /(^|[\/\\])\../, persistent: true }); // Something to use when events are received. var log = console.log.bind(console); // Add event listeners. watcher .on('add', path => log(`File ${path} has been added`)) .on('change', path => log(`File ${path} has been changed`)) .on('unlink', path => log(`File ${path} has been removed`)); // More possible events. watcher .on('addDir', path => log(`Directory ${path} has been added`)) .on('unlinkDir', path => log(`Directory ${path} has been removed`)) .on('error', error => log(`Watcher error: ${error}`)) .on('ready', () => log('Initial scan complete. Ready for changes')) .on('raw', (event, path, details) => { log('Raw event info:', event, path, details); }); // 'add', 'addDir' and 'change' events also receive stat() results as second // argument when available: http://nodejs.org/api/fs.html#fs_class_fs_stats watcher.on('change', (path, stats) => { if (stats) console.log(`File ${path} changed size to ${stats.size}`); }); // Watch new files. watcher.add('new-file'); watcher.add(['new-file-2', 'new-file-3', '**/other-file*']); // Get list of actual paths being watched on the filesystem var watchedPaths = watcher.getWatched(); // Un-watch some files. watcher.unwatch('new-file*'); // Stop watching. watcher.close(); // Full list of options. See below for descriptions. (do not use this example) chokidar.watch('file', { persistent: true, ignored: '*.txt', ignoreInitial: false, followSymlinks: true, cwd: '.', disableGlobbing: false, usePolling: true, interval: 100, binaryInterval: 300, alwaysStat: false, depth: 99, awaitWriteFinish: { stabilityThreshold: 2000, pollInterval: 100 }, ignorePermissionErrors: false, atomic: true // or a custom 'atomicity delay', in milliseconds (default 100) }); ``` ## API `chokidar.watch(paths, [options])` * `paths` (string or array of strings). Paths to files, dirs to be watched recursively, or glob patterns. * `options` (object) Options object as defined below: #### Persistence * `persistent` (default: `true`). Indicates whether the process should continue to run as long as files are being watched. If set to `false` when using `fsevents` to watch, no more events will be emitted after `ready`, even if the process continues to run. #### Path filtering * `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition) Defines files/paths to be ignored. The whole relative or absolute path is tested, not just filename. If a function with two arguments is provided, it gets called twice per path - once with a single argument (the path), second time with two arguments (the path and the [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). * `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while instantiating the watching as chokidar discovers these file paths (before the `ready` event). * `followSymlinks` (default: `true`). When `false`, only the symlinks themselves will be watched for changes instead of following the link references and bubbling events through the link's path. * `cwd` (no default). The base directory from which watch `paths` are to be derived. Paths emitted with events will be relative to this. * `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as literal path names, even if they look like globs. #### Performance * `usePolling` (default: `false`). Whether to use fs.watchFile (backed by polling), or fs.watch. If polling leads to high CPU utilization, consider setting this to `false`. It is typically necessary to **set this to `true` to successfully watch files over a network**, and it may be necessary to successfully watch files in other non-standard situations. Setting to `true` explicitly on MacOS overrides the `useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable to true (1) or false (0) in order to override this option. * _Polling-specific settings_ (effective when `usePolling: true`) * `interval` (default: `100`). Interval of file system polling. You may also set the CHOKIDAR_INTERVAL env variable to override this option. * `binaryInterval` (default: `300`). Interval of file system polling for binary files. ([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json)) * `useFsEvents` (default: `true` on MacOS). Whether to use the `fsevents` watching interface if available. When set to `true` explicitly and `fsevents` is available this supercedes the `usePolling` setting. When set to `false` on MacOS, `usePolling: true` becomes the default. * `alwaysStat` (default: `false`). If relying upon the [`fs.Stats`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object that may get passed with `add`, `addDir`, and `change` events, set this to `true` to ensure it is provided even in cases where it wasn't already available from the underlying watch events. * `depth` (default: `undefined`). If set, limits how many levels of subdirectories will be traversed. * `awaitWriteFinish` (default: `false`). By default, the `add` event will fire when a file first appears on disk, before the entire file has been written. Furthermore, in some cases some `change` events will be emitted while the file is being written. In some cases, especially when watching for large files there will be a need to wait for the write operation to finish before responding to a file creation or modification. Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size, holding its `add` and `change` events until the size does not change for a configurable amount of time. The appropriate duration setting is heavily dependent on the OS and hardware. For accurate detection this parameter should be relatively high, making file watching much less responsive. Use with caution. * *`options.awaitWriteFinish` can be set to an object in order to adjust timing params:* * `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in milliseconds for a file size to remain constant before emitting its event. * `awaitWriteFinish.pollInterval` (default: 100). File size polling interval. #### Errors * `ignorePermissionErrors` (default: `false`). Indicates whether to watch files that don't have read permissions if possible. If watching fails due to `EPERM` or `EACCES` with this set to `true`, the errors will be suppressed silently. * `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`). Automatically filters out artifacts that occur when using editors that use "atomic writes" instead of writing directly to the source file. If a file is re-added within 100 ms of being deleted, Chokidar emits a `change` event rather than `unlink` then `add`. If the default of 100 ms does not work well for you, you can override it by setting `atomic` to a custom value, in milliseconds. ### Methods & Events `chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`: * `.add(path / paths)`: Add files, directories, or glob patterns for tracking. Takes an array of strings or just one string. * `.on(event, callback)`: Listen for an FS event. Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, `raw`, `error`. Additionally `all` is available which gets emitted with the underlying event name and path for every event other than `ready`, `raw`, and `error`. * `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. Takes an array of strings or just one string. * `.close()`: Removes all listeners from watched files. * `.getWatched()`: Returns an object representing all the paths on the file system being watched by this `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless the `cwd` option was used), and the values are arrays of the names of the items contained in each directory. ## CLI If you need a CLI interface for your file watching, check out [chokidar-cli](https://github.com/kimmobrunfeldt/chokidar-cli), allowing you to execute a command on each change, or get a stdio stream of change events. ## Install Troubleshooting * `npm WARN optional dep failed, continuing [email protected]` * This message is normal part of how `npm` handles optional dependencies and is not indicative of a problem. Even if accompanied by other related error messages, Chokidar should function properly. * `ERR! stack Error: Python executable "python" is v3.4.1, which is not supported by gyp.` * You should be able to resolve this by installing python 2.7 and running: `npm config set python python2.7` * `gyp ERR! stack Error: not found: make` * On Mac, install the XCode command-line tools ## License The MIT License (MIT) Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com) & Elan Shanker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This folder contains entry points for all stable `core-js` features with dependencies. It's the recommended way for usage only required features. # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) A robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) and [io.js v1.0.0+](https://github.com/iojs/io.js/blob/v1.x/lib/punycode.js). ## Installation Via [npm](https://www.npmjs.com/) (only required for Node.js releases older than v0.6.2): ```bash npm install punycode ``` Via [Bower](http://bower.io/): ```bash bower install punycode ``` Via [Component](https://github.com/component/component): ```bash component install bestiejs/punycode.js ``` In a browser: ```html <script src="punycode.js"></script> ``` In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), [Narwhal](http://narwhaljs.org/), and [RingoJS](http://ringojs.org/): ```js var punycode = require('punycode'); ``` In [Rhino](http://www.mozilla.org/rhino/): ```js load('punycode.js'); ``` Using an AMD loader like [RequireJS](http://requirejs.org/): ```js require( { 'paths': { 'punycode': 'path/to/punycode' } }, ['punycode'], function(punycode) { console.log(punycode); } ); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Unit tests & code coverage After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. To generate the code coverage report, use `grunt cover`. Feel free to fork if you see possible improvements! ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## Contributors | [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | |---| | [John-David Dalton](http://allyoucanleet.com/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. # global-prefix [![NPM version](https://img.shields.io/npm/v/global-prefix.svg?style=flat)](https://www.npmjs.com/package/global-prefix) [![NPM monthly downloads](https://img.shields.io/npm/dm/global-prefix.svg?style=flat)](https://npmjs.org/package/global-prefix) [![NPM total downloads](https://img.shields.io/npm/dt/global-prefix.svg?style=flat)](https://npmjs.org/package/global-prefix) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/global-prefix.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/global-prefix) [![Windows Build Status](https://img.shields.io/appveyor/ci/jonschlinkert/global-prefix.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/jonschlinkert/global-prefix) > Get the npm global path prefix. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save global-prefix ``` This is partially based on the code used by npm internally to resolve the global prefix. ## Usage ```js var prefix = require('global-prefix'); //=> '/usr/local' (this path will differ by system and user-defined config) ``` ## About ### Related projects * [global-modules](https://www.npmjs.com/package/global-modules): The directory used by npm for globally installed npm modules. | [homepage](https://github.com/jonschlinkert/global-modules "The directory used by npm for globally installed npm modules.") * [global-paths](https://www.npmjs.com/package/global-paths): Returns an array of unique "global" directories based on the user's platform and environment. The… [more](https://github.com/jonschlinkert/global-paths) | [homepage](https://github.com/jonschlinkert/global-paths "Returns an array of unique "global" directories based on the user's platform and environment. The resulting paths can be used for doing lookups for generators or other globally installed npm packages. Node.js / JavaScript.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 16 | [jonschlinkert](https://github.com/jonschlinkert) | | 15 | [doowb](https://github.com/doowb) | | 1 | [rmbaad](https://github.com/rmbaad) | | 1 | [avengerpenguin](https://github.com/avengerpenguin) | | 1 | [jason-chang](https://github.com/jason-chang) | | 1 | [jorrit](https://github.com/jorrit) | | 1 | [mathiasvr](https://github.com/mathiasvr) | | 1 | [tunnckoCore](https://github.com/tunnckoCore) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 28, 2017._ # is-data-descriptor [![NPM version](https://img.shields.io/npm/v/is-data-descriptor.svg)](https://www.npmjs.com/package/is-data-descriptor) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-data-descriptor.svg)](https://travis-ci.org/jonschlinkert/is-data-descriptor) > Returns true if a value has the characteristics of a valid JavaScript data descriptor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm i is-data-descriptor --save ``` ## Usage ```js var isDataDesc = require('is-data-descriptor'); ``` ## Examples `true` when the descriptor has valid properties with valid values. ```js // `value` can be anything isDataDesc({value: 'foo'}) isDataDesc({value: function() {}}) isDataDesc({value: true}) //=> true ``` `false` when not an object ```js isDataDesc('a') //=> false isDataDesc(null) //=> false isDataDesc([]) //=> false ``` `false` when the object has invalid properties ```js isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', get: function(){}}) //=> false isDataDesc({get: function(){}, value: 'foo'}) //=> false ``` `false` when a value is not the correct type ```js isDataDesc({value: 'foo', enumerable: 'foo'}) //=> false isDataDesc({value: 'foo', configurable: 'foo'}) //=> false isDataDesc({value: 'foo', writable: 'foo'}) //=> false ``` ## Valid properties The only valid data descriptor properties are the following: * `configurable` (required) * `enumerable` (required) * `value` (optional) * `writable` (optional) To be a valid data descriptor, either `value` or `writable` must be defined. **Invalid properties** A descriptor may have additional _invalid_ properties (an error will **not** be thrown). ```js var foo = {}; Object.defineProperty(foo, 'bar', { enumerable: true, whatever: 'blah', // invalid, but doesn't cause an error get: function() { return 'baz'; } }); console.log(foo.bar); //=> 'baz' ``` ## Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor) * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://www.npmjs.com/package/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor) * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/is-data-descriptor/issues/new). ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 [Jon Schlinkert](https://github.com/jonschlinkert) Released under the MIT license. *** _This file was generated by [verb](https://github.com/verbose/verb) on December 28, 2015._ # parse-passwd [![NPM version](https://img.shields.io/npm/v/parse-passwd.svg?style=flat)](https://www.npmjs.com/package/parse-passwd) [![NPM downloads](https://img.shields.io/npm/dm/parse-passwd.svg?style=flat)](https://npmjs.org/package/parse-passwd) [![Linux Build Status](https://img.shields.io/travis/doowb/parse-passwd.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/parse-passwd) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/parse-passwd.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/parse-passwd) > Parse a passwd file into a list of users. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save parse-passwd ``` ## Usage ```js var parse = require('parse-passwd'); ``` ## API **Example** ```js // assuming '/etc/passwd' contains: // doowb:*:123:123:Brian Woodward:/Users/doowb:/bin/bash console.log(parse(fs.readFileSync('/etc/passwd', 'utf8'))); //=> [ //=> { //=> username: 'doowb', //=> password: '*', //=> uid: '123', //=> gid: '123', //=> gecos: 'Brian Woodward', //=> homedir: '/Users/doowb', //=> shell: '/bin/bash' //=> } //=> ] ``` **Params** * `content` **{String}**: Content of a passwd file to parse. * `returns` **{Array}**: Array of user objects parsed from the content. ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for avice on opening issues, pull requests, and coding standards. ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Brian Woodward** * [github/doowb](https://github.com/doowb) * [twitter/doowb](http://twitter.com/doowb) ### License Copyright © 2016, [Brian Woodward](https://github.com/doowb). Released under the [MIT license](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 19, 2016._ # Glob Match files using the patterns the shell uses, like stars and stuff. [![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. ![](oh-my-glob.gif) ## Usage Install with npm ``` npm i glob ``` ```javascript var glob = require("glob") // options is optional glob("**/*.js", options, function (er, files) { // files is an array of filenames. // If the `nonull` option is set, and nothing // was found, then files is ["**/*.js"] // er is an error object or null. }) ``` ## Glob Primer "Globs" are the patterns you type when you do stuff like `ls *.js` on the command line, or put `build/*` in a `.gitignore` file. Before parsing the path part patterns, braced sections are expanded into a set. Braced sections start with `{` and end with `}`, with any number of comma-delimited sections within. Braced sections may contain slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. The following characters have special magic meaning when used in a path portion: * `*` Matches 0 or more characters in a single path portion * `?` Matches 1 character * `[...]` Matches a range of characters, similar to a RegExp range. If the first character of the range is `!` or `^` then it matches any character not in the range. * `!(pattern|pattern|pattern)` Matches anything that does not match any of the patterns provided. * `?(pattern|pattern|pattern)` Matches zero or one occurrence of the patterns provided. * `+(pattern|pattern|pattern)` Matches one or more occurrences of the patterns provided. * `*(a|b|c)` Matches zero or more occurrences of the patterns provided * `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns provided * `**` If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories. ### Dots If a file or directory path portion has a `.` as the first character, then it will not match any glob pattern unless that pattern's corresponding path part also has a `.` as its first character. For example, the pattern `a/.*/c` would match the file at `a/.b/c`. However the pattern `a/*/c` would not, because `*` does not start with a dot character. You can make glob treat dots as normal characters by setting `dot:true` in the options. ### Basename Matching If you set `matchBase:true` in the options, and the pattern has no slashes in it, then it will seek for any file anywhere in the tree with a matching basename. For example, `*.js` would match `test/simple/basic.js`. ### Empty Sets If no matching files are found, then an empty array is returned. This differs from the shell, where the pattern itself is returned. For example: $ echo a*s*d*f a*s*d*f To get the bash-style behavior, set the `nonull:true` in the options. ### See Also: * `man sh` * `man bash` (Search for "Pattern Matching") * `man 3 fnmatch` * `man 5 gitignore` * [minimatch documentation](https://github.com/isaacs/minimatch) ## glob.hasMagic(pattern, [options]) Returns `true` if there are any special characters in the pattern, and `false` otherwise. Note that the options affect the results. If `noext:true` is set in the options object, then `+(a|b)` will not be considered a magic pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` then that is considered magical, unless `nobrace:true` is set in the options. ## glob(pattern, [options], cb) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * `cb` `{Function}` * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Perform an asynchronous glob search. ## glob.sync(pattern, [options]) * `pattern` `{String}` Pattern to be matched * `options` `{Object}` * return: `{Array<String>}` filenames found matching the pattern Perform a synchronous glob search. ## Class: glob.Glob Create a Glob object by instantiating the `glob.Glob` class. ```javascript var Glob = require("glob").Glob var mg = new Glob(pattern, options, cb) ``` It's an EventEmitter, and starts walking the filesystem to find matches immediately. ### new glob.Glob(pattern, [options], [cb]) * `pattern` `{String}` pattern to search for * `options` `{Object}` * `cb` `{Function}` Called when an error occurs, or matches are found * `err` `{Error | null}` * `matches` `{Array<String>}` filenames found matching the pattern Note that if the `sync` flag is set in the options, then matches will be immediately available on the `g.found` member. ### Properties * `minimatch` The minimatch object that the glob uses. * `options` The options object passed in. * `aborted` Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * `cache` Convenience object. Each field has the following possible values: * `false` - Path does not exist * `true` - Path exists * `'FILE'` - Path exists, and is not a directory * `'DIR'` - Path exists, and is a directory * `[file, entries, ...]` - Path exists, is a directory, and the array value is the results of `fs.readdir` * `statCache` Cache of `fs.stat` results, to prevent statting the same path multiple times. * `symlinks` A record of which paths are symbolic links, which is relevant in resolving `**` patterns. * `realpathCache` An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. ### Events * `end` When the matching is finished, this is emitted with all the matches found. If the `nonull` option is set, and no match was found, then the `matches` list contains the original pattern. The matches are sorted, unless the `nosort` flag is set. * `match` Every time a match is found, this is emitted with the specific thing that matched. It is not deduplicated or resolved to a realpath. * `error` Emitted when an unexpected error is encountered, or whenever any fs error occurs if `options.strict` is set. * `abort` When `abort()` is called, this event is raised. ### Methods * `pause` Temporarily stop the search * `resume` Resume the search * `abort` Stop the search forever ### Options All the options that can be passed to Minimatch can also be passed to Glob to change pattern matching behavior. Also, some have been added, or have glob-specific ramifications. All options are false by default, unless otherwise noted. All options are added to the Glob object, as well. If you are running many `glob` operations, you can pass a Glob object as the `options` argument to a subsequent operation to shortcut some `stat` and `readdir` calls. At the very least, you may pass in shared `symlinks`, `statCache`, `realpathCache`, and `cache` options, so that parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults to `process.cwd()`. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. * `nomount` By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. * `mark` Add a `/` character to directory matches. Note that this requires additional stat calls. * `nosort` Don't sort the results. * `stat` Set to true to stat *all* results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. * `silent` When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. * `strict` When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. * `cache` See `cache` property above. Pass in a previously generated cache object to save some fs calls. * `statCache` A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See "Race Conditions" below.) * `symlinks` A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save `lstat` calls when resolving `**` matches. * `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. * `nounique` In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. * `nonull` Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). * `debug` Set to enable debug logging in minimatch and glob. * `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. * `noglobstar` Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) * `noext` Do not match `+(a|b)` "extglob" patterns. * `nocase` Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. * `matchBase` Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**/*.js`, matching all js files in all directories. * `nodir` Do not match directories, only files. (Note: to match *only* directories, simply put a `/` at the end of the pattern.) * `ignore` Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are *always* in `dot:true` mode, regardless of any other settings. * `follow` Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. * `realpath` Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between node-glob and other implementations, and are intentional. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.3, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. Note that symlinked directories are not crawled as part of a `**`, though their contents may match against subsequent portions of the pattern. This prevents infinite loops and duplicates and the like. If an escaped pattern has no matches, and the `nonull` flag is set, then glob returns the pattern as-provided, rather than interpreting the character escapes. For example, `glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. ### Comments and Negation Previously, this module let you mark a pattern as a "comment" if it started with a `#` character, or a "negated" pattern if it started with a `!` character. These options were deprecated in version 5, and removed in version 6. To specify things that should not match, use the `ignore` option. ## Windows **Please only use forward-slashes in glob expressions.** Though windows uses either `/` or `\` as its path separator, only `/` characters are used by this glob implementation. You must use forward-slashes **only** in glob expressions. Back-slashes will always be interpreted as escape characters, not path separators. Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, since it relies on directory walking and such. As a result, it is possible that a file that exists when glob looks for it may have been deleted or modified by the time it returns the result. As part of its internal implementation, this program caches all stat and readdir calls that it makes, in order to cut down on system overhead. However, this also makes it even more susceptible to races, especially if the cache or statCache objects are reused between glob calls. Users are thus advised not to use a glob result as a guarantee of filesystem state in the face of rapid changes. For the vast majority of operations, this is never a problem. ## Contributing Any change to behavior (including bugfixes) must come with a test. Patches that fail tests or reduce performance will be rejected. ``` # to run tests npm test # to re-generate test fixtures npm run test-regen # to benchmark against bash/zsh npm run bench # to profile javascript npm run prof ``` # nanomatch [![NPM version](https://img.shields.io/npm/v/nanomatch.svg?style=flat)](https://www.npmjs.com/package/nanomatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/nanomatch.svg?style=flat)](https://npmjs.org/package/nanomatch) [![NPM total downloads](https://img.shields.io/npm/dt/nanomatch.svg?style=flat)](https://npmjs.org/package/nanomatch) [![Linux Build Status](https://img.shields.io/travis/micromatch/nanomatch.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/nanomatch) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/nanomatch.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/nanomatch) > Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces) Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> - [Install](#install) - [What is nanomatch?](#what-is-nanomatch) - [Getting started](#getting-started) * [Installing nanomatch](#installing-nanomatch) * [Usage](#usage) - [Documentation](#documentation) * [Escaping](#escaping) - [API](#api) - [Options](#options) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.cache](#optionscache) * [options.dot](#optionsdot) * [options.failglob](#optionsfailglob) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.nocase](#optionsnocase) * [options.nodupes](#optionsnodupes) * [options.noglobstar](#optionsnoglobstar) * [options.nonegate](#optionsnonegate) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.slash](#optionsslash) * [options.star](#optionsstar) * [options.snapdragon](#optionssnapdragon) * [options.sourcemap](#optionssourcemap) * [options.unescape](#optionsunescape) * [options.unixify](#optionsunixify) - [Features](#features) - [Bash expansion libs](#bash-expansion-libs) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Nanomatch vs. Minimatch vs. Multimatch](#nanomatch-vs-minimatch-vs-multimatch) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save nanomatch ``` <details> <summary><strong>Release history</strong></summary> ## History ### key Changelog entries are classified using the following labels _(from [keep-a-changelog](https://github.com/olivierlacan/keep-a-changelog)_): * `added`: for new features * `changed`: for changes in existing functionality * `deprecated`: for once-stable features removed in upcoming releases * `removed`: for deprecated features removed in this release * `fixed`: for any bug fixes * `bumped`: updated dependencies, only minor or higher will be listed. ### [1.1.0](https://github.com/micromatch/nanomatch/compare/1.0.4...1.1.0) - 2017-04-11 **Fixed** * adds support for unclosed quotes **Added** * adds support for `options.noglobstar` ### [1.0.4](https://github.com/micromatch/nanomatch/compare/1.0.3...1.0.4) - 2017-04-06 Housekeeping updates. Adds documentation section about escaping, cleans up utils. ### [1.0.3](https://github.com/micromatch/nanomatch/compare/1.0.1...1.0.3) - 2017-04-06 This release includes fixes for windows path edge cases and other improvements for stricter adherence to bash spec. **Fixed** * More windows path edge cases **Added** * Support for bash-like quoted strings for escaping sequences of characters, such as `foo/"**"/bar` where `**` should be matched literally and not evaluated as special characters. ### [1.0.1](https://github.com/micromatch/nanomatch/compare/1.0.0...1.0.1) - 2016-12-12 **Added** * Support for windows path edge cases where backslashes are used in brackets or other unusual combinations. ### [1.0.0](https://github.com/micromatch/nanomatch/compare/0.1.0...1.0.0) - 2016-12-12 Stable release. ### [0.1.0] - 2016-10-08 First release. </details> ## What is nanomatch? Nanomatch is a fast and accurate glob matcher with full support for standard Bash glob features, including the following "metacharacters": `*`, `**`, `?` and `[...]`. **Learn more** * [Getting started](#getting-started): learn how to install and begin using nanomatch * [Features](#features): jump to info about supported patterns, and a glob matching reference * [API documentation](#api): jump to available options and methods * [Unit tests](test): visit unit tests. there is no better way to learn a code library than spending time the unit tests. Nanomatch has 36,000 unit tests - go become a glob matching ninja! <details> <summary><strong>How is this different?</strong></summary> **Speed and accuracy** Nanomatch uses [snapdragon](https://github.com/jonschlinkert/snapdragon) for parsing and compiling globs, which results in: * Granular control over the entire conversion process in a way that is easy to understand, reason about, and customize. * Faster matching, from a combination of optimized glob patterns and (optional) caching. * Much greater accuracy than minimatch. In fact, nanomatch passes _all of the spec tests_ from bash, including some that bash still fails. However, since there is no real specification for globs, if you encounter a pattern that yields unexpected match results [after researching previous issues](../../issues), [please let us know](../../issues/new). **Basic globbing only** Nanomatch supports [basic globbing only](#features), which is limited to `*`, `**`, `?` and regex-like brackets. If you need support for the other [bash "expansion" types](#bash-expansion-libs) (in addition to the wildcard matching provided by nanomatch), consider using [micromatch](https://github.com/micromatch/micromatch) instead. _(micromatch >=3.0.0 uses the nanomatch parser and compiler for basic glob matching)_ </details> ## Getting started ### Installing nanomatch **Install with [yarn](https://yarnpkg.com/)** ```sh $ yarn add nanomatch ``` **Install with [npm](https://npmjs.com)** ```sh $ npm install nanomatch ``` ### Usage Add nanomatch to your project using node's `require()` system: ```js var nanomatch = require('nanomatch'); // the main export is a function that takes an array of strings to match // and a string or array of patterns to use for matching nanomatch(list, patterns[, options]); ``` **Params** * `list` **{String|Array}**: List of strings to perform matches against. This is often a list of file paths. * `patterns` **{String|Array}**: One or more [glob paterns](#features) to use for matching. * `options` **{Object}**: Any [supported options](#options) may be passed **Examples** ```js var nm = require('nanomatch'); console.log(nm(['a', 'b/b', 'c/c/c'], '*')); //=> ['a'] console.log(nm(['a', 'b/b', 'c/c/c'], '*/*')); //=> ['b/b'] console.log(nm(['a', 'b/b', 'c/c/c'], '**')); //=> ['a', 'b/b', 'c/c/c'] ``` See the [API documentation](#api) for available methods and [options](https://github.com/einaros/options.js). ## Documentation ### Escaping _Backslashes and quotes_ can be used to escape characters, forcing nanomatch to regard those characters as a literal characters. **Backslashes** Use backslashes to escape single characters. For example, the following pattern would match `foo/*/bar` exactly: ```js 'foo/\*/bar' ``` The following pattern would match `foo/` followed by a literal `*`, followed by zero or more of any characters besides `/`, followed by `/bar`. ```js 'foo/\**/bar' ``` **Quoted strings** Use single or double quotes to escape sequences of characters. For example, the following patterns would match `foo/**/bar` exactly: ```js 'foo/"**"/bar' 'foo/\'**\'/bar' "foo/'**'/bar" ``` **Matching literal quotes** If you need to match quotes literally, you can escape them as well. For example, the following will match `foo/"*"/bar`, `foo/"a"/bar`, `foo/"b"/bar`, or `foo/"c"/bar`: ```js 'foo/\\"*\\"/bar' ``` And the following will match `foo/'*'/bar`, `foo/'a'/bar`, `foo/'b'/bar`, or `foo/'c'/bar`: ```js 'foo/\\\'*\\\'/bar' ``` ## API ### [nanomatch](index.js#L40) The main function takes a list of strings and one or more glob patterns to use for matching. **Params** * `list` **{Array}**: A list of strings to match * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of matches **Example** ```js var nm = require('nanomatch'); nm(list, patterns[, options]); console.log(nm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.match](index.js#L106) Similar to the main function, but `pattern` must be a string. **Params** * `list` **{Array}**: Array of strings to match * `pattern` **{String}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of matches **Example** ```js var nm = require('nanomatch'); nm.match(list, pattern[, options]); console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); //=> ['a.a', 'a.aa'] ``` ### [.isMatch](index.js#L167) Returns true if the specified `string` matches the given glob `pattern`. **Params** * `string` **{String}**: String to match * `pattern` **{String}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if the string matches the glob pattern. **Example** ```js var nm = require('nanomatch'); nm.isMatch(string, pattern[, options]); console.log(nm.isMatch('a.a', '*.a')); //=> true console.log(nm.isMatch('a.b', '*.a')); //=> false ``` ### [.some](index.js#L205) Returns true if some of the elements in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var nm = require('nanomatch'); nm.some(list, patterns[, options]); console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(nm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L243) Returns true if every element in the given `list` matches at least one of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var nm = require('nanomatch'); nm.every(list, patterns[, options]); console.log(nm.every('foo.js', ['foo.js'])); // true console.log(nm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(nm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.any](index.js#L277) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var nm = require('nanomatch'); nm.any(string, patterns[, options]); console.log(nm.any('a.a', ['b.*', '*.a'])); //=> true console.log(nm.any('a.a', 'b.*')); //=> false ``` ### [.all](index.js#L325) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var nm = require('nanomatch'); nm.all(string, patterns[, options]); console.log(nm.all('foo.js', ['foo.js'])); // true console.log(nm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(nm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.not](index.js#L359) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js var nm = require('nanomatch'); nm.not(list, patterns[, options]); console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L394) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if the patter matches any part of `str`. **Example** ```js var nm = require('nanomatch'); nm.contains(string, pattern[, options]); console.log(nm.contains('aa/bb/cc', '*b')); //=> true console.log(nm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L450) 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. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js var nm = require('nanomatch'); nm.matchKeys(object, patterns[, options]); var obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(nm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.matcher](index.js#L479) 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. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}**: See available [options](#options) for changing how matches are performed. * `returns` **{Function}**: Returns a matcher function. **Example** ```js var nm = require('nanomatch'); nm.matcher(pattern[, options]); var isMatch = nm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.capture](index.js#L560) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `pattern` **{String}**: Glob pattern to use for matching. * `string` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns an array of captures if the string matches the glob pattern, otherwise `null`. **Example** ```js var nm = require('nanomatch'); nm.capture(pattern, string[, options]); console.log(nm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(nm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L595) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}**: See available [options](#options) for changing how matches are performed. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js var nm = require('nanomatch'); nm.makeRe(pattern[, options]); console.log(nm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.create](index.js#L658) Parses the given glob `pattern` and returns an object with the compiled `output` and optional source `map`. **Params** * `pattern` **{String}**: Glob pattern to parse and compile. * `options` **{Object}**: Any [options](#options) to change how parsing and compiling is performed. * `returns` **{Object}**: Returns an object with the parsed AST, compiled string and optional source map. **Example** ```js var nm = require('nanomatch'); nm.create(pattern[, options]); console.log(nm.create('abc/*.js')); // { options: { source: 'string', sourcemap: true }, // state: {}, // compilers: // { ... }, // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', // ast: // { type: 'root', // errors: [], // nodes: // [ ... ], // dot: false, // input: 'abc/*.js' }, // parsingErrors: [], // map: // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/*.js' ] }, // position: { line: 1, column: 28 }, // content: {}, // files: {}, // idx: 6 } ``` ### [.parse](index.js#L697) Parse the given `str` with the given `options`. **Params** * `str` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an AST **Example** ```js var nm = require('nanomatch'); nm.parse(pattern[, options]); var ast = nm.parse('a/{b,c}/d'); console.log(ast); // { type: 'root', // errors: [], // input: 'a/{b,c}/d', // nodes: // [ { type: 'bos', val: '' }, // { type: 'text', val: 'a/' }, // { type: 'brace', // nodes: // [ { type: 'brace.open', val: '{' }, // { type: 'text', val: 'b,c' }, // { type: 'brace.close', val: '}' } ] }, // { type: 'text', val: '/d' }, // { type: 'eos', val: '' } ] } ``` ### [.compile](index.js#L745) Compile the given `ast` or string with the given `options`. **Params** * `ast` **{Object|String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object that has an `output` property with the compiled string. **Example** ```js var nm = require('nanomatch'); nm.compile(ast[, options]); var ast = nm.parse('a/{b,c}/d'); console.log(nm.compile(ast)); // { options: { source: 'string' }, // state: {}, // compilers: // { eos: [Function], // noop: [Function], // bos: [Function], // brace: [Function], // 'brace.open': [Function], // text: [Function], // 'brace.close': [Function] }, // output: [ 'a/(b|c)/d' ], // ast: // { ... }, // parsingErrors: [] } ``` ### [.clearCache](index.js#L768) Clear the regex cache. **Example** ```js nm.clearCache(); ``` ## Options <details> <summary><strong>basename</strong></summary> ### options.basename 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`. Type: `boolean` Default: `false` **Example** ```js nm(['a/b.js', 'a/c.md'], '*.js'); //=> [] nm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true}); //=> ['a/b.js'] ``` </details> <details> <summary><strong>bash</strong></summary> ### options.bash 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. Type: `boolean` Default: `true` **Example** ```js var files = ['abc', 'ajz']; console.log(nm(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(nm(files, '[a-c]*', {bash: false})); ``` </details> <details> <summary><strong>cache</strong></summary> ### options.cache Disable regex and function memoization. Type: `boolean` Default: `undefined` </details> <details> <summary><strong>dot</strong></summary> ### options.dot Match dotfiles. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `dot`. Type: `boolean` Default: `false` </details> <details> <summary><strong>failglob</strong></summary> ### options.failglob Similar to the `--failglob` behavior in Bash, throws an error when no matches are found. Type: `boolean` Default: `undefined` </details> <details> <summary><strong>ignore</strong></summary> ### options.ignore String or array of glob patterns to match files to ignore. Type: `String|Array` Default: `undefined` </details> <details> <summary><strong>matchBase</strong></summary> ### options.matchBase Alias for [options.basename](#options-basename). </details> <details> <summary><strong>nocase</strong></summary> ### options.nocase Use a case-insensitive regex for matching files. Same behavior as [minimatch](https://github.com/isaacs/minimatch). Type: `boolean` Default: `undefined` </details> <details> <summary><strong>nodupes</strong></summary> ### options.nodupes Remove duplicate elements from the result array. Type: `boolean` Default: `true` (enabled by default) **Example** Example of using the `unescape` and `nodupes` options together: ```js nm.match(['a/b/c', 'a/b/c'], '**'); //=> ['abc'] nm.match(['a/b/c', 'a/b/c'], '**', {nodupes: false}); //=> ['a/b/c', 'a/b/c'] ``` </details> <details> <summary><strong>nonegate</strong></summary> ### options.noglobstar Disable matching with globstars (`**`). Type: `boolean` Default: `undefined` ```js nm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] nm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` </details> <details> <summary><strong>nonegate</strong></summary> ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. Type: `boolean` Default: `undefined` </details> <details> <summary><strong>nonull</strong></summary> ### options.nonull Alias for [options.nullglob](#options-nullglob). </details> <details> <summary><strong>nullglob</strong></summary> ### options.nullglob 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`. Type: `boolean` Default: `undefined` </details> <details> <summary><strong><a name="slash">slash</a></strong></summary> ### options.slash Customize the slash character(s) to use for matching. Type: `string|function` Default: `[/\\]` (forward slash and backslash) </details> <details> <summary><strong><a name="star">star</a></strong></summary> ### options.star Customize the star character(s) to use for matching. It's not recommended that you modify this unless you have advanced knowledge of the compiler and matching rules. Type: `string|function` Default: `[^/\\]*?` </details> <details> <summary><strong><a name="snapdragon">snapdragon</a></strong></summary> ### options.snapdragon Pass your own instance of [snapdragon](https://github.com/jonschlinkert/snapdragon) to customize parsers or compilers. Type: `object` Default: `undefined` </details> <details> <summary><strong>snapdragon</strong></summary> ### options.sourcemap Generate a source map by enabling the `sourcemap` option with the `.parse`, `.compile`, or `.create` methods. **Examples** ```js var nm = require('nanomatch'); var res = nm.create('abc/*.js', {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,iBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/*.js' ] } var ast = nm.parse('abc/**/*.js'); var res = nm.compile(ast, {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,2BAAE,EAAC,iBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/**/*.js' ] } ``` </details> <details> <summary><strong>unescape</strong></summary> ### options.unescape Remove backslashes from returned matches. Type: `boolean` Default: `undefined` **Example** In this example we want to match a literal `*`: ```js nm.match(['abc', 'a\\*c'], 'a\\*c'); //=> ['a\\*c'] nm.match(['abc', 'a\\*c'], 'a\\*c', {unescape: true}); //=> ['a*c'] ``` </details> <details> <summary><strong>unixify</strong></summary> ### options.unixify Convert path separators on returned files to posix/unix-style forward slashes. Type: `boolean` Default: `true` **Example** ```js nm.match(['a\\b\\c'], 'a/**'); //=> ['a/b/c'] nm.match(['a\\b\\c'], {unixify: false}); //=> ['a\\b\\c'] ``` </details> ## Features Nanomatch has full support for standard Bash glob features, including the following "metacharacters": `*`, `**`, `?` and `[...]`. Here are some examples of how they work: | **Pattern** | **Description** | | --- | --- | | `*` | Matches any string except for `/`, leading `.`, or `/.` inside a path | | `**` | Matches any string including `/`, but not a leading `.` or `/.` inside a path. More than two stars (e.g. `***` is treated the same as one star, and `**` loses its special meaning | when it's not the only thing in a path segment, per Bash specifications) | | `foo*` | Matches any string beginning with `foo` | | `*bar*` | Matches any string containing `bar` (beginning, middle or end) | | `*.min.js` | Matches any string ending with `.min.js` | | `[abc]*.js` | Matches any string beginning with `a`, `b`, or `c` and ending with `.js` | | `abc?` | Matches `abcd` or `abcz` but not `abcde` | The exceptions noted for `*` apply to all patterns that contain a `*`. **Not supported** The following extended-globbing features are not supported: * [brace expansion](https://github.com/jonschlinkert/braces) (e.g. `{a,b,c}`) * [extglobs](https://github.com/jonschlinkert/extglob) (e.g. `@(a|!(c|d))`) * [POSIX brackets](https://github.com/jonschlinkert/expand-brackets) (e.g. `[[:alpha:][:digit:]]`) If you need any of these features consider using [micromatch](https://github.com/micromatch/micromatch) instead. ## Bash expansion libs Nanomatch is part of a suite of libraries aimed at bringing the power and expressiveness of [Bash's](https://www.gnu.org/software/bash/) matching and expansion capabilities to JavaScript, _and - as you can see by the [benchmarks](#benchmarks) - without sacrificing speed_. | **Related library** | **Matching Type** | **Example** | **Description** | | --- | --- | --- | --- | | `nanomatch` (you are here) | Wildcards | `*` | [Filename expansion](https://www.gnu.org/software/bash/manual/html_node/Filename-Expansion.html#Filename-Expansion), also referred to as globbing and pathname expansion, allows the use of [wildcards](#features) for matching. | | [expand-tilde](https://github.com/jonschlinkert/expand-tilde) | Tildes | `~` | [Tilde expansion](https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html#Tilde-Expansion) converts the leading tilde in a file path to the user home directory. | | [braces](https://github.com/jonschlinkert/braces) | Braces | `{a,b,c}` | [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) | | [expand-brackets](https://github.com/jonschlinkert/expand-brackets) | Brackets | `[[:alpha:]]` | [POSIX character classes](https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html) (also referred to as POSIX brackets, or POSIX character classes) | | [extglob](https://github.com/jonschlinkert/extglob) | Parens | `!(a\ | b)` | [Extglobs](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html#Pattern-Matching) | | [micromatch](https://github.com/micromatch/micromatch) | All | all | Micromatch is built on top of the other libraries. | There are many resources available on the web if you want to dive deeper into how these features work in Bash. ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && node benchmark ``` ### Nanomatch vs. Minimatch vs. Multimatch ```bash # globstar-basic (182 bytes) minimatch x 69,512 ops/sec ±1.92% (88 runs sampled) multimatch x 63,376 ops/sec ±1.41% (89 runs sampled) nanomatch x 432,451 ops/sec ±0.92% (88 runs sampled) fastest is nanomatch (by 651% avg) # large-list-globstar (485686 bytes) minimatch x 34.02 ops/sec ±1.42% (59 runs sampled) multimatch x 33.58 ops/sec ±1.97% (58 runs sampled) nanomatch x 483 ops/sec ±1.06% (86 runs sampled) fastest is nanomatch (by 1429% avg) # long-list-globstar (194085 bytes) minimatch x 383 ops/sec ±0.74% (90 runs sampled) multimatch x 378 ops/sec ±0.59% (89 runs sampled) nanomatch x 990 ops/sec ±1.14% (85 runs sampled) fastest is nanomatch (by 260% avg) # negation-basic (132 bytes) minimatch x 242,145 ops/sec ±1.17% (89 runs sampled) multimatch x 76,403 ops/sec ±0.78% (92 runs sampled) nanomatch x 537,253 ops/sec ±1.44% (86 runs sampled) fastest is nanomatch (by 337% avg) # not-glob-basic (93 bytes) minimatch x 252,402 ops/sec ±1.33% (89 runs sampled) multimatch x 209,954 ops/sec ±1.30% (90 runs sampled) nanomatch x 1,716,468 ops/sec ±1.13% (86 runs sampled) fastest is nanomatch (by 742% avg) # star-basic (93 bytes) minimatch x 182,780 ops/sec ±1.41% (91 runs sampled) multimatch x 153,210 ops/sec ±0.72% (89 runs sampled) nanomatch x 599,621 ops/sec ±1.22% (90 runs sampled) fastest is nanomatch (by 357% avg) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [is-extglob](https://www.npmjs.com/package/is-extglob): Returns true if a string has an extglob. | [homepage](https://github.com/jonschlinkert/is-extglob "Returns true if a string has an extglob.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 164 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [devongovett](https://github.com/devongovett) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 18, 2018._ # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ # snapdragon-util [![NPM version](https://img.shields.io/npm/v/snapdragon-util.svg?style=flat)](https://www.npmjs.com/package/snapdragon-util) [![NPM monthly downloads](https://img.shields.io/npm/dm/snapdragon-util.svg?style=flat)](https://npmjs.org/package/snapdragon-util) [![NPM total downloads](https://img.shields.io/npm/dt/snapdragon-util.svg?style=flat)](https://npmjs.org/package/snapdragon-util) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/snapdragon-util.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/snapdragon-util) > Utilities for the snapdragon parser/compiler. <details> <summary><strong>Table of Contents</strong></summary> - [Install](#install) - [Usage](#usage) - [API](#api) - [Release history](#release-history) * [[3.0.0] - 2017-05-01](#300---2017-05-01) * [[0.1.0]](#010) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save snapdragon-util ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add snapdragon-util ``` ## Usage ```js var util = require('snapdragon-util'); ``` ## API ### [.isNode](index.js#L21) Returns true if the given value is a node. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var node = new Node({type: 'foo'}); console.log(utils.isNode(node)); //=> true console.log(utils.isNode({})); //=> false ``` ### [.noop](index.js#L37) Emit an empty string for the given `node`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{undefined}** **Example** ```js // do nothing for beginning-of-string snapdragon.compiler.set('bos', utils.noop); ``` ### [.identity](index.js#L53) Appdend `node.val` to `compiler.output`, exactly as it was created by the parser. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{undefined}** **Example** ```js snapdragon.compiler.set('text', utils.identity); ``` ### [.append](index.js#L76) Previously named `.emit`, this method appends the given `val` to `compiler.output` for the given node. Useful when you know what value should be appended advance, regardless of the actual value of `node.val`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Function}**: Returns a compiler middleware function. **Example** ```js snapdragon.compiler .set('i', function(node) { this.mapVisit(node); }) .set('i.open', utils.append('<i>')) .set('i.close', utils.append('</i>')) ``` ### [.toNoop](index.js#L99) Used in compiler middleware, this onverts an AST node into an empty `text` node and deletes `node.nodes` if it exists. The advantage of this method is that, as opposed to completely removing the node, indices will not need to be re-calculated in sibling nodes, and nothing is appended to the output. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `nodes` **{Array}**: Optionally pass a new `nodes` value, to replace the existing `node.nodes` array. **Example** ```js utils.toNoop(node); // convert `node.nodes` to the given value instead of deleting it utils.toNoop(node, []); ``` ### [.visit](index.js#L128) Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon automatically calls registered compilers, this allows you to pass a visitor function. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `fn` **{Function}** * `returns` **{Object}**: returns the node after recursively visiting all child nodes. **Example** ```js snapdragon.compiler.set('i', function(node) { utils.visit(node, function(childNode) { // do stuff with "childNode" return childNode; }); }); ``` ### [.mapVisit](index.js#L155) Map [visit](#visit) the given `fn` over `node.nodes`. This is called by [visit](#visit), use this method if you do not want `fn` to be called on the first node. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `options` **{Object}** * `fn` **{Function}** * `returns` **{Object}**: returns the node **Example** ```js snapdragon.compiler.set('i', function(node) { utils.mapVisit(node, function(childNode) { // do stuff with "childNode" return childNode; }); }); ``` ### [.addOpen](index.js#L194) Unshift an `*.open` node onto `node.nodes`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `Node` **{Function}**: (required) Node constructor function from [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node). * `filter` **{Function}**: Optionaly specify a filter function to exclude the node. * `returns` **{Object}**: Returns the created opening node. **Example** ```js var Node = require('snapdragon-node'); snapdragon.parser.set('brace', function(node) { var match = this.match(/^{/); if (match) { var parent = new Node({type: 'brace'}); utils.addOpen(parent, Node); console.log(parent.nodes[0]): // { type: 'brace.open', val: '' }; // push the parent "brace" node onto the stack this.push(parent); // return the parent node, so it's also added to the AST return brace; } }); ``` ### [.addClose](index.js#L244) Push a `*.close` node onto `node.nodes`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `Node` **{Function}**: (required) Node constructor function from [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node). * `filter` **{Function}**: Optionaly specify a filter function to exclude the node. * `returns` **{Object}**: Returns the created closing node. **Example** ```js var Node = require('snapdragon-node'); snapdragon.parser.set('brace', function(node) { var match = this.match(/^}/); if (match) { var parent = this.parent(); if (parent.type !== 'brace') { throw new Error('missing opening: ' + '}'); } utils.addClose(parent, Node); console.log(parent.nodes[parent.nodes.length - 1]): // { type: 'brace.close', val: '' }; // no need to return a node, since the parent // was already added to the AST return; } }); ``` ### [.wrapNodes](index.js#L274) Wraps the given `node` with `*.open` and `*.close` nodes. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `Node` **{Function}**: (required) Node constructor function from [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node). * `filter` **{Function}**: Optionaly specify a filter function to exclude the node. * `returns` **{Object}**: Returns the node ### [.pushNode](index.js#L299) Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent. **Params** * `parent` **{Object}** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Object}**: Returns the child node **Example** ```js var parent = new Node({type: 'foo'}); var node = new Node({type: 'bar'}); utils.pushNode(parent, node); console.log(parent.nodes[0].type) // 'bar' console.log(node.parent.type) // 'foo' ``` ### [.unshiftNode](index.js#L325) Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent. **Params** * `parent` **{Object}** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{undefined}** **Example** ```js var parent = new Node({type: 'foo'}); var node = new Node({type: 'bar'}); utils.unshiftNode(parent, node); console.log(parent.nodes[0].type) // 'bar' console.log(node.parent.type) // 'foo' ``` ### [.popNode](index.js#L354) Pop the last `node` off of `parent.nodes`. The advantage of using this method is that it checks for `node.nodes` and works with any version of `snapdragon-node`. **Params** * `parent` **{Object}** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Number|Undefined}**: Returns the length of `node.nodes` or undefined. **Example** ```js var parent = new Node({type: 'foo'}); utils.pushNode(parent, new Node({type: 'foo'})); utils.pushNode(parent, new Node({type: 'bar'})); utils.pushNode(parent, new Node({type: 'baz'})); console.log(parent.nodes.length); //=> 3 utils.popNode(parent); console.log(parent.nodes.length); //=> 2 ``` ### [.shiftNode](index.js#L382) Shift the first `node` off of `parent.nodes`. The advantage of using this method is that it checks for `node.nodes` and works with any version of `snapdragon-node`. **Params** * `parent` **{Object}** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Number|Undefined}**: Returns the length of `node.nodes` or undefined. **Example** ```js var parent = new Node({type: 'foo'}); utils.pushNode(parent, new Node({type: 'foo'})); utils.pushNode(parent, new Node({type: 'bar'})); utils.pushNode(parent, new Node({type: 'baz'})); console.log(parent.nodes.length); //=> 3 utils.shiftNode(parent); console.log(parent.nodes.length); //=> 2 ``` ### [.removeNode](index.js#L409) Remove the specified `node` from `parent.nodes`. **Params** * `parent` **{Object}** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Object|undefined}**: Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`. **Example** ```js var parent = new Node({type: 'abc'}); var foo = new Node({type: 'foo'}); utils.pushNode(parent, foo); utils.pushNode(parent, new Node({type: 'bar'})); utils.pushNode(parent, new Node({type: 'baz'})); console.log(parent.nodes.length); //=> 3 utils.removeNode(parent, foo); console.log(parent.nodes.length); //=> 2 ``` ### [.isType](index.js#L443) Returns true if `node.type` matches the given `type`. Throws a `TypeError` if `node` is not an instance of `Node`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `type` **{String}** * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var node = new Node({type: 'foo'}); console.log(utils.isType(node, 'foo')); // false console.log(utils.isType(node, 'bar')); // true ``` ### [.hasType](index.js#L486) Returns true if the given `node` has the given `type` in `node.nodes`. Throws a `TypeError` if `node` is not an instance of `Node`. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `type` **{String}** * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var node = new Node({ type: 'foo', nodes: [ new Node({type: 'bar'}), new Node({type: 'baz'}) ] }); console.log(utils.hasType(node, 'xyz')); // false console.log(utils.hasType(node, 'baz')); // true ``` ### [.firstOfType](index.js#L519) Returns the first node from `node.nodes` of the given `type` **Params** * `nodes` **{Array}** * `type` **{String}** * `returns` **{Object|undefined}**: Returns the first matching node or undefined. **Example** ```js var node = new Node({ type: 'foo', nodes: [ new Node({type: 'text', val: 'abc'}), new Node({type: 'text', val: 'xyz'}) ] }); var textNode = utils.firstOfType(node.nodes, 'text'); console.log(textNode.val); //=> 'abc' ``` ### [.findNode](index.js#L556) Returns the node at the specified index, or the first node of the given `type` from `node.nodes`. **Params** * `nodes` **{Array}** * `type` **{String|Number}**: Node type or index. * `returns` **{Object}**: Returns a node or undefined. **Example** ```js var node = new Node({ type: 'foo', nodes: [ new Node({type: 'text', val: 'abc'}), new Node({type: 'text', val: 'xyz'}) ] }); var nodeOne = utils.findNode(node.nodes, 'text'); console.log(nodeOne.val); //=> 'abc' var nodeTwo = utils.findNode(node.nodes, 1); console.log(nodeTwo.val); //=> 'xyz' ``` ### [.isOpen](index.js#L584) Returns true if the given node is an "*.open" node. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var brace = new Node({type: 'brace'}); var open = new Node({type: 'brace.open'}); var close = new Node({type: 'brace.close'}); console.log(utils.isOpen(brace)); // false console.log(utils.isOpen(open)); // true console.log(utils.isOpen(close)); // false ``` ### [.isClose](index.js#L607) Returns true if the given node is a "*.close" node. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var brace = new Node({type: 'brace'}); var open = new Node({type: 'brace.open'}); var close = new Node({type: 'brace.close'}); console.log(utils.isClose(brace)); // false console.log(utils.isClose(open)); // false console.log(utils.isClose(close)); // true ``` ### [.hasOpen](index.js#L633) Returns true if `node.nodes` **has** an `.open` node **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var brace = new Node({ type: 'brace', nodes: [] }); var open = new Node({type: 'brace.open'}); console.log(utils.hasOpen(brace)); // false brace.pushNode(open); console.log(utils.hasOpen(brace)); // true ``` ### [.hasClose](index.js#L663) Returns true if `node.nodes` **has** a `.close` node **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var brace = new Node({ type: 'brace', nodes: [] }); var close = new Node({type: 'brace.close'}); console.log(utils.hasClose(brace)); // false brace.pushNode(close); console.log(utils.hasClose(brace)); // true ``` ### [.hasOpenAndClose](index.js#L697) Returns true if `node.nodes` has both `.open` and `.close` nodes **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var brace = new Node({ type: 'brace', nodes: [] }); var open = new Node({type: 'brace.open'}); var close = new Node({type: 'brace.close'}); console.log(utils.hasOpen(brace)); // false console.log(utils.hasClose(brace)); // false brace.pushNode(open); brace.pushNode(close); console.log(utils.hasOpen(brace)); // true console.log(utils.hasClose(brace)); // true ``` ### [.addType](index.js#L719) Push the given `node` onto the `state.inside` array for the given type. This array is used as a specialized "stack" for only the given `node.type`. **Params** * `state` **{Object}**: The `compiler.state` object or custom state object. * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Array}**: Returns the `state.inside` stack for the given type. **Example** ```js var state = { inside: {}}; var node = new Node({type: 'brace'}); utils.addType(state, node); console.log(state.inside); //=> { brace: [{type: 'brace'}] } ``` ### [.removeType](index.js#L759) Remove the given `node` from the `state.inside` array for the given type. This array is used as a specialized "stack" for only the given `node.type`. **Params** * `state` **{Object}**: The `compiler.state` object or custom state object. * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `returns` **{Array}**: Returns the `state.inside` stack for the given type. **Example** ```js var state = { inside: {}}; var node = new Node({type: 'brace'}); utils.addType(state, node); console.log(state.inside); //=> { brace: [{type: 'brace'}] } utils.removeType(state, node); //=> { brace: [] } ``` ### [.isEmpty](index.js#L788) Returns true if `node.val` is an empty string, or `node.nodes` does not contain any non-empty text nodes. **Params** * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `fn` **{Function}** * `returns` **{Boolean}** **Example** ```js var node = new Node({type: 'text'}); utils.isEmpty(node); //=> true node.val = 'foo'; utils.isEmpty(node); //=> false ``` ### [.isInsideType](index.js#L833) Returns true if the `state.inside` stack for the given type exists and has one or more nodes on it. **Params** * `state` **{Object}** * `type` **{String}** * `returns` **{Boolean}** **Example** ```js var state = { inside: {}}; var node = new Node({type: 'brace'}); console.log(utils.isInsideType(state, 'brace')); //=> false utils.addType(state, node); console.log(utils.isInsideType(state, 'brace')); //=> true utils.removeType(state, node); console.log(utils.isInsideType(state, 'brace')); //=> false ``` ### [.isInside](index.js#L867) Returns true if `node` is either a child or grand-child of the given `type`, or `state.inside[type]` is a non-empty array. **Params** * `state` **{Object}**: Either the `compiler.state` object, if it exists, or a user-supplied state object. * `node` **{Object}**: Instance of [snapdragon-node](https://github.com/jonschlinkert/snapdragon-node) * `type` **{String}**: The `node.type` to check for. * `returns` **{Boolean}** **Example** ```js var state = { inside: {}}; var node = new Node({type: 'brace'}); var open = new Node({type: 'brace.open'}); console.log(utils.isInside(state, open, 'brace')); //=> false utils.pushNode(node, open); console.log(utils.isInside(state, open, 'brace')); //=> true ``` ### [.last](index.js#L915) Get the last `n` element from the given `array`. Used for getting a node from `node.nodes.` **Params** * `array` **{Array}** * `n` **{Number}** * `returns` **{undefined}** ### [.arrayify](index.js#L935) Cast the given `val` to an array. **Params** * `val` **{any}** * `returns` **{Array}** **Example** ```js console.log(utils.arraify('')); //=> [] console.log(utils.arraify('foo')); //=> ['foo'] console.log(utils.arraify(['foo'])); //=> ['foo'] ``` ### [.stringify](index.js#L948) Convert the given `val` to a string by joining with `,`. Useful for creating a cheerio/CSS/DOM-style selector from a list of strings. **Params** * `val` **{any}** * `returns` **{Array}** ### [.trim](index.js#L961) Ensure that the given value is a string and call `.trim()` on it, or return an empty string. **Params** * `str` **{String}** * `returns` **{String}** ## Release history Changelog entries are classified using the following labels from [keep-a-changelog](https://github.com/olivierlacan/keep-a-changelog): * `added`: for new features * `changed`: for changes in existing functionality * `deprecated`: for once-stable features removed in upcoming releases * `removed`: for deprecated features removed in this release * `fixed`: for any bug fixes Custom labels used in this changelog: * `dependencies`: bumps dependencies * `housekeeping`: code re-organization, minor edits, or other changes that don't fit in one of the other categories. ### [3.0.0] - 2017-05-01 **Changed** * `.emit` was renamed to [.append](#append) * `.addNode` was renamed to [.pushNode](#pushNode) * `.getNode` was renamed to [.findNode](#findNode) * `.isEmptyNodes` was renamed to [.isEmpty](#isEmpty): also now works with `node.nodes` and/or `node.val` **Added** * [.identity](#identity) * [.removeNode](#removeNode) * [.shiftNode](#shiftNode) * [.popNode](#popNode) ### [0.1.0] First release. ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 01, 2017._ ## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). * Intuitive encode/decode API * Streaming support for Node v0.10+ * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). * License: MIT. [![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) ## Usage ### Basic API ```javascript var iconv = require('iconv-lite'); // Convert from an encoded buffer to js string. str = iconv.decode(Buffer.from([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); // Convert from js string to an encoded buffer. buf = iconv.encode("Sample input string", 'win1251'); // Check if encoding is supported iconv.encodingExists("us-ascii") ``` ### Streaming API (Node v0.10+) ```javascript // Decode stream (from binary stream to js strings) http.createServer(function(req, res) { var converterStream = iconv.decodeStream('win1251'); req.pipe(converterStream); converterStream.on('data', function(str) { console.log(str); // Do something with decoded strings, chunk-by-chunk. }); }); // Convert encoding streaming example fs.createReadStream('file-in-win1251.txt') .pipe(iconv.decodeStream('win1251')) .pipe(iconv.encodeStream('ucs2')) .pipe(fs.createWriteStream('file-in-ucs2.txt')); // Sugar: all encode/decode streams have .collect(cb) method to accumulate data. http.createServer(function(req, res) { req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { assert(typeof body == 'string'); console.log(body); // full request body string }); }); ``` ### [Deprecated] Extend Node.js own encodings > NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). ```javascript // After this call all Node basic primitives will understand iconv-lite encodings. iconv.extendNodeEncodings(); // Examples: buf = new Buffer(str, 'win1251'); buf.write(str, 'gbk'); str = buf.toString('latin1'); assert(Buffer.isEncoding('iso-8859-15')); Buffer.byteLength(str, 'us-ascii'); http.createServer(function(req, res) { req.setEncoding('big5'); req.collect(function(err, body) { console.log(body); }); }); fs.createReadStream("file.txt", "shift_jis"); // External modules are also supported (if they use Node primitives, which they probably do). request = require('request'); request({ url: "http://github.com/", encoding: "cp932" }); // To remove extensions iconv.undoExtendNodeEncodings(); ``` ## Supported encodings * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. Aliases like 'latin1', 'us-ascii' also supported. * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! ## Encoding/decoding speed Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). Note: your results may vary, so please always check on your hardware. operation [email protected] [email protected] ---------------------------------------------------------- encode('win1251') ~96 Mb/s ~320 Mb/s decode('win1251') ~95 Mb/s ~246 Mb/s ## BOM handling * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. * Encoding: No BOM added, unless overridden by `addBOM: true` option. ## UTF-16 Encodings This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be smart about endianness in the following ways: * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. ## Other notes When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). Untranslatable characters are set to � or ?. No transliteration is currently supported. Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). ## Testing ```bash $ git clone [email protected]:ashtuchkin/iconv-lite.git $ cd iconv-lite $ npm install $ npm test $ # To view performance: $ node test/performance.js $ # To view test coverage: $ npm run coverage $ open coverage/lcov-report/index.html ``` semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install --save semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero digit in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # cookie [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Basic HTTP cookie parser and serializer for HTTP servers. ## Installation ```sh $ npm install cookie ``` ## API ```js var cookie = require('cookie'); ``` ### cookie.parse(str, options) Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. The `str` argument is the string representing a `Cookie` header value and `options` is an optional object containing additional parsing options. ```js var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' } ``` #### Options `cookie.parse` accepts these properties in the options object. ##### decode Specifies a function that will be used to decode a cookie's value. Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode a previously-encoded cookie value into a JavaScript string or other object. The default function is the global `decodeURIComponent`, which will decode any URL-encoded sequences into their byte representations. **note** if an error is thrown from this function, the original, non-decoded cookie value will be returned as the cookie's value. ### cookie.serialize(name, value, options) Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the name for the cookie, the `value` argument is the value to set the cookie to, and the `options` argument is an optional object containing additional serialization options. ```js var setCookie = cookie.serialize('foo', 'bar'); // foo=bar ``` #### Options `cookie.serialize` accepts these properties in the options object. ##### domain Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6266-5.2.3]. By default, no domain is set, and most clients will consider the cookie to apply to only the current domain. ##### encode Specifies a function that will be used to encode a cookie's value. Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value. The default function is the global `ecodeURIComponent`, which will encode a JavaScript string into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. ##### expires Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6266-5.2.1]. By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application. **note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and `magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, so if both are set, they should point to the same date and time. ##### httpOnly Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6266-5.2.6]. When truthy, the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. **note** be careful when setting this to `true`, as compliant clients will not allow client-side JavaScript to see the cookie in `document.cookie`. ##### maxAge Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6266-5.2.2]. The given number will be converted to an integer by rounding down. By default, no maximum age is set. **note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and `magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, so if both are set, they should point to the same date and time. ##### path Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6266-5.2.4]. By default, the path is considered the ["default path"][rfc-6266-5.1.4]. By default, no maximum age is set, and most clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting a web browser application. ##### sameSite Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][draft-west-first-party-cookies-07]. - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. - `false` will not set the `SameSite` attribute. - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. More information about the different enforcement levels can be found in the specification https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1.1 **note** This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it. ##### secure Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6266-5.2.5]. When truthy, the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. **note** be careful when setting this to `true`, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection. ## Example The following example uses this module in conjunction with the Node.js core HTTP server to prompt a user for their name and display it back on future visits. ```js var cookie = require('cookie'); var escapeHtml = require('escape-html'); var http = require('http'); var url = require('url'); function onRequest(req, res) { // Parse the query string var query = url.parse(req.url, true, true).query; if (query && query.name) { // Set a new cookie with the name res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { httpOnly: true, maxAge: 60 * 60 * 24 * 7 // 1 week })); // Redirect back after setting cookie res.statusCode = 302; res.setHeader('Location', req.headers.referer || '/'); res.end(); return; } // Parse the cookies on the request var cookies = cookie.parse(req.headers.cookie || ''); // Get the visitor name set in the cookie var name = cookies.name; res.setHeader('Content-Type', 'text/html; charset=UTF-8'); if (name) { res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>'); } else { res.write('<p>Hello, new visitor!</p>'); } res.write('<form method="GET">'); res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">'); res.end('</form'); } http.createServer(onRequest).listen(3000); ``` ## Testing ```sh $ npm test ``` ## References - [RFC 6266: HTTP State Management Mechanism][rfc-6266] - [Same-site Cookies][draft-west-first-party-cookies-07] [draft-west-first-party-cookies-07]: https://tools.ietf.org/html/draft-west-first-party-cookies-07 [rfc-6266]: https://tools.ietf.org/html/rfc6266 [rfc-6266-5.1.4]: https://tools.ietf.org/html/rfc6266#section-5.1.4 [rfc-6266-5.2.1]: https://tools.ietf.org/html/rfc6266#section-5.2.1 [rfc-6266-5.2.2]: https://tools.ietf.org/html/rfc6266#section-5.2.2 [rfc-6266-5.2.3]: https://tools.ietf.org/html/rfc6266#section-5.2.3 [rfc-6266-5.2.4]: https://tools.ietf.org/html/rfc6266#section-5.2.4 [rfc-6266-5.3]: https://tools.ietf.org/html/rfc6266#section-5.3 ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/cookie.svg [npm-url]: https://npmjs.org/package/cookie [node-version-image]: https://img.shields.io/node/v/cookie.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/cookie/master.svg [travis-url]: https://travis-ci.org/jshttp/cookie [coveralls-image]: https://img.shields.io/coveralls/jshttp/cookie/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master [downloads-image]: https://img.shields.io/npm/dm/cookie.svg [downloads-url]: https://npmjs.org/package/cookie # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # private [![Build Status](https://travis-ci.org/benjamn/private.png?branch=master)](https://travis-ci.org/benjamn/private) [![Greenkeeper badge](https://badges.greenkeeper.io/benjamn/private.svg)](https://greenkeeper.io/) A general-purpose utility for associating truly private state with any JavaScript object. Installation --- From NPM: npm install private From GitHub: cd path/to/node_modules git clone git://github.com/benjamn/private.git cd private npm install . Usage --- **Get or create a secret object associated with any (non-frozen) object:** ```js var getSecret = require("private").makeAccessor(); var obj = Object.create(null); // any kind of object works getSecret(obj).totallySafeProperty = "p455w0rd"; console.log(Object.keys(obj)); // [] console.log(Object.getOwnPropertyNames(obj)); // [] console.log(getSecret(obj)); // { totallySafeProperty: "p455w0rd" } ``` Now, only code that has a reference to both `getSecret` and `obj` can possibly access `.totallySafeProperty`. *Importantly, no global references to the secret object are retained by the `private` package, so as soon as `obj` gets garbage collected, the secret will be reclaimed as well. In other words, you don't have to worry about memory leaks.* **Create a unique property name that cannot be enumerated or guessed:** ```js var secretKey = require("private").makeUniqueKey(); var obj = Object.create(null); // any kind of object works Object.defineProperty(obj, secretKey, { value: { totallySafeProperty: "p455w0rd" }, enumerable: false // optional; non-enumerability is the default }); Object.defineProperty(obj, "nonEnumerableProperty", { value: "anyone can guess my name", enumerable: false }); console.log(obj[secretKey].totallySafeProperty); // p455w0rd console.log(obj.nonEnumerableProperty); // "anyone can guess my name" console.log(Object.keys(obj)); // [] console.log(Object.getOwnPropertyNames(obj)); // ["nonEnumerableProperty"] for (var key in obj) { console.log(key); // never called } ``` Because these keys are non-enumerable, you can't discover them using a `for`-`in` loop. Because `secretKey` is a long string of random characters, you would have a lot of trouble guessing it. And because the `private` module wraps `Object.getOwnPropertyNames` to exclude the keys it generates, you can't even use that interface to discover it. Unless you have access to the value of the `secretKey` property name, there is no way to access the value associated with it. So your only responsibility as secret-keeper is to avoid handing out the value of `secretKey` to untrusted code. Think of this style as a home-grown version of the first style. Note, however, that it requires a full implementation of ES5's `Object.defineProperty` method in order to make any safety guarantees, whereas the first example will provide safety even in environments that do not support `Object.defineProperty`. Rationale --- In JavaScript, the only data that are truly private are local variables whose values do not *leak* from the scope in which they were defined. This notion of *closure privacy* is powerful, and it readily provides some of the benefits of traditional data privacy, a la Java or C++: ```js function MyClass(secret) { this.increment = function() { return ++secret; }; } var mc = new MyClass(3); console.log(mc.increment()); // 4 ``` You can learn something about `secret` by calling `.increment()`, and you can increase its value by one as many times as you like, but you can never decrease its value, because it is completely inaccessible except through the `.increment` method. And if the `.increment` method were not available, it would be as if no `secret` variable had ever been declared, as far as you could tell. This style breaks down as soon as you want to inherit methods from the prototype of a class: ```js function MyClass(secret) { this.secret = secret; } MyClass.prototype.increment = function() { return ++this.secret; }; ``` The only way to communicate between the `MyClass` constructor and the `.increment` method in this example is to manipulate shared properties of `this`. Unfortunately `this.secret` is now exposed to unlicensed modification: ```js var mc = new MyClass(6); console.log(mc.increment()); // 7 mc.secret -= Infinity; console.log(mc.increment()); // -Infinity mc.secret = "Go home JavaScript, you're drunk."; mc.increment(); // NaN ``` Another problem with closure privacy is that it only lends itself to per-instance privacy, whereas the `private` keyword in most object-oriented languages indicates that the data member in question is visible to all instances of the same class. Suppose you have a `Node` class with a notion of parents and children: ```js function Node() { var parent; var children = []; this.getParent = function() { return parent; }; this.appendChild = function(child) { children.push(child); child.parent = this; // Can this be made to work? }; } ``` The desire here is to allow other `Node` objects to manipulate the value returned by `.getParent()`, but otherwise disallow any modification of the `parent` variable. You could expose a `.setParent` function, but then anyone could call it, and you might as well give up on the getter/setter pattern. This module solves both of these problems. Usage --- Let's revisit the `Node` example from above: ```js var p = require("private").makeAccessor(); function Node() { var privates = p(this); var children = []; this.getParent = function() { return privates.parent; }; this.appendChild = function(child) { children.push(child); var cp = p(child); if (cp.parent) cp.parent.removeChild(child); cp.parent = this; return child; }; } ``` Now, in order to access the private data of a `Node` object, you need to have access to the unique `p` function that is being used here. This is already an improvement over the previous example, because it allows restricted access by other `Node` instances, but can it help with the `Node.prototype` problem too? Yes it can! ```js var p = require("private").makeAccessor(); function Node() { p(this).children = []; } var Np = Node.prototype; Np.getParent = function() { return p(this).parent; }; Np.appendChild = function(child) { p(this).children.push(child); var cp = p(child); if (cp.parent) cp.parent.removeChild(child); cp.parent = this; return child; }; ``` Because `p` is in scope not only within the `Node` constructor but also within `Node` methods, we can finally avoid redefining methods every time the `Node` constructor is called. Now, you might be wondering how you can restrict access to `p` so that no untrusted code is able to call it. The answer is to use your favorite module pattern, be it CommonJS, AMD `define`, or even the old Immediately-Invoked Function Expression: ```js var Node = (function() { var p = require("private").makeAccessor(); function Node() { p(this).children = []; } var Np = Node.prototype; Np.getParent = function() { return p(this).parent; }; Np.appendChild = function(child) { p(this).children.push(child); var cp = p(child); if (cp.parent) cp.parent.removeChild(child); cp.parent = this; return child; }; return Node; }()); var parent = new Node; var child = new Node; parent.appendChild(child); assert.strictEqual(child.getParent(), parent); ``` Because this version of `p` never leaks from the enclosing function scope, only `Node` objects have access to it. So, you see, the claim I made at the beginning of this README remains true: > In JavaScript, the only data that are truly private are local variables > whose values do not *leak* from the scope in which they were defined. It just so happens that closure privacy is sufficient to implement a privacy model similar to that provided by other languages. # wrappy Callback wrapping utility ## USAGE ```javascript var wrappy = require("wrappy") // var wrapper = wrappy(wrapperFunction) // make sure a cb is called only once // See also: http://npm.im/once for this specific use case var once = wrappy(function (cb) { var called = false return function () { if (called) return called = true return cb.apply(this, arguments) } }) function printBoo () { console.log('boo') } // has some rando property printBoo.iAmBooPrinter = true var onlyPrintOnce = once(printBoo) onlyPrintOnce() // prints 'boo' onlyPrintOnce() // does nothing // random property is retained! assert.equal(onlyPrintOnce.iAmBooPrinter, true) ``` ### Esrecurse [![Build Status](https://travis-ci.org/estools/esrecurse.svg?branch=master)](https://travis-ci.org/estools/esrecurse) Esrecurse ([esrecurse](https://github.com/estools/esrecurse)) is [ECMAScript](https://www.ecma-international.org/publications/standards/Ecma-262.htm) recursive traversing functionality. ### Example Usage The following code will output all variables declared at the root of a file. ```javascript esrecurse.visit(ast, { XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); ``` We can use `Visitor` instance. ```javascript var visitor = new esrecurse.Visitor({ XXXStatement: function (node) { this.visit(node.left); // do something... this.visit(node.right); } }); visitor.visit(ast); ``` We can inherit `Visitor` instance easily. ```javascript class Derived extends esrecurse.Visitor { constructor() { super(null); } XXXStatement(node) { } } ``` ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { this.visit(node.left); // do something... this.visit(node.right); }; ``` And you can invoke default visiting operation inside custom visit operation. ```javascript function DerivedVisitor() { esrecurse.Visitor.call(/* this for constructor */ this /* visitor object automatically becomes this. */); } util.inherits(DerivedVisitor, esrecurse.Visitor); DerivedVisitor.prototype.XXXStatement = function (node) { // do something... this.visitChildren(node); }; ``` The `childVisitorKeys` option does customize the behaviour of `this.visitChildren(node)`. We can use user-defined node types. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { // Extending the existing traversing rules. childVisitorKeys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } } ); ``` We can use the `fallback` option as well. If the `fallback` option is `"iteration"`, `esrecurse` would visit all enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: 'iteration' } ); ``` If the `fallback` option is a function, `esrecurse` calls this function to determine the enumerable properties of unknown nodes. Please note circular references cause the stack overflow. AST might have circular references in additional properties for some purpose (e.g. `node.parent`). ```javascript esrecurse.visit( ast, { Literal: function (node) { // do something... } }, { fallback: function (node) { return Object.keys(node).filter(function(key) { return key !== 'argument' }); } } ); ``` ### License Copyright (C) 2014 [Yusuke Suzuki](https://github.com/Constellation) (twitter: [@Constellation](https://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # tslib This is a runtime library for [TypeScript](http://www.typescriptlang.org/) that contains all of the TypeScript helper functions. This library is primarily used by the `--importHelpers` flag in TypeScript. When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: ```ts var __assign = (this && this.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; exports.x = {}; exports.y = __assign({}, exports.x); ``` will instead be emitted as something like the following: ```ts var tslib_1 = require("tslib"); exports.x = {}; exports.y = tslib_1.__assign({}, exports.x); ``` Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. # Installing For the latest stable version, run: ## npm ```sh # TypeScript 2.3.3 or later npm install --save tslib # TypeScript 2.3.2 or earlier npm install --save [email protected] ``` ## bower ```sh # TypeScript 2.3.3 or later bower install tslib # TypeScript 2.3.2 or earlier bower install [email protected] ``` ## JSPM ```sh # TypeScript 2.3.3 or later jspm install tslib # TypeScript 2.3.2 or earlier jspm install [email protected] ``` # Usage Set the `importHelpers` compiler option on the command line: ``` tsc --importHelpers file.ts ``` or in your tsconfig.json: ```json { "compilerOptions": { "importHelpers": true } } ``` #### For bower and JSPM users You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: ```json { "compilerOptions": { "module": "amd", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["bower_components/tslib/tslib.d.ts"] } } } ``` For JSPM users: ```json { "compilerOptions": { "module": "system", "importHelpers": true, "baseUrl": "./", "paths": { "tslib" : ["jspm_packages/npm/[email protected]/tslib.d.ts"] } } } ``` # Contribute There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. * [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. * Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). * Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). * Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. * [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). * Read the language specification ([docx](http://go.microsoft.com/fwlink/?LinkId=267121), [pdf](http://go.microsoft.com/fwlink/?LinkId=267238)). # Documentation * [Quick tutorial](http://www.typescriptlang.org/Tutorial) * [Programming handbook](http://www.typescriptlang.org/Handbook) * [Language specification](https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md) * [Homepage](http://www.typescriptlang.org/) # hash.js [![Build Status](https://secure.travis-ci.org/indutny/hash.js.svg)](http://travis-ci.org/indutny/hash.js) Just a bike-shed. ## Install ```sh npm install hash.js ``` ## Usage ```js var hash = require('hash.js') hash.sha256().update('abc').digest('hex') ``` ## Selective hash usage ```js var sha512 = require('hash.js/lib/hash/sha/512'); sha512().update('abc').digest('hex'); ``` #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2014. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Console Control Strings A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted. ## Usage ```js var consoleControl = require('console-control-strings') console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) process.stdout.write(consoleControl.goto(75, 10)) ``` ## Why Another? There are tons of libraries similar to this one. I wanted one that was: 1. Very clear about compatibility goals. 2. Could emit, for instance, a start color code without an end one. 3. Returned strings w/o writing to streams. 4. Was not weighed down with other unrelated baggage. ## Functions ### var code = consoleControl.up(_num = 1_) Returns the escape sequence to move _num_ lines up. ### var code = consoleControl.down(_num = 1_) Returns the escape sequence to move _num_ lines down. ### var code = consoleControl.forward(_num = 1_) Returns the escape sequence to move _num_ lines righ. ### var code = consoleControl.back(_num = 1_) Returns the escape sequence to move _num_ lines left. ### var code = consoleControl.nextLine(_num = 1_) Returns the escape sequence to move _num_ lines down and to the beginning of the line. ### var code = consoleControl.previousLine(_num = 1_) Returns the escape sequence to move _num_ lines up and to the beginning of the line. ### var code = consoleControl.eraseData() Returns the escape sequence to erase everything from the current cursor position to the bottom right of the screen. This is line based, so it erases the remainder of the current line and all following lines. ### var code = consoleControl.eraseLine() Returns the escape sequence to erase to the end of the current line. ### var code = consoleControl.goto(_x_, _y_) Returns the escape sequence to move the cursor to the designated position. Note that the origin is _1, 1_ not _0, 0_. ### var code = consoleControl.gotoSOL() Returns the escape sequence to move the cursor to the beginning of the current line. (That is, it returns a carriage return, `\r`.) ### var code = consoleControl.beep() Returns the escape sequence to cause the termianl to beep. (That is, it returns unicode character `\x0007`, a Control-G.) ### var code = consoleControl.hideCursor() Returns the escape sequence to hide the cursor. ### var code = consoleControl.showCursor() Returns the escape sequence to show the cursor. ### var code = consoleControl.color(_colors = []_) ### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) Returns the escape sequence to set the current terminal display attributes (mostly colors). Arguments can either be a list of attributes or an array of attributes. The difference between passing in an array or list of colors and calling `.color` separately for each one, is that in the former case a single escape sequence will be produced where as in the latter each change will have its own distinct escape sequence. Each attribute can be one of: * Reset: * **reset** – Reset all attributes to the terminal default. * Styles: * **bold** – Display text as bold. In some terminals this means using a bold font, in others this means changing the color. In some it means both. * **italic** – Display text as italic. This is not available in most Windows terminals. * **underline** – Underline text. This is not available in most Windows Terminals. * **inverse** – Invert the foreground and background colors. * **stopBold** – Do not display text as bold. * **stopItalic** – Do not display text as italic. * **stopUnderline** – Do not underline text. * **stopInverse** – Do not invert foreground and background. * Colors: * **white** * **black** * **blue** * **cyan** * **green** * **magenta** * **red** * **yellow** * **grey** / **brightBlack** * **brightRed** * **brightGreen** * **brightYellow** * **brightBlue** * **brightMagenta** * **brightCyan** * **brightWhite** * Background Colors: * **bgWhite** * **bgBlack** * **bgBlue** * **bgCyan** * **bgGreen** * **bgMagenta** * **bgRed** * **bgYellow** * **bgGrey** / **bgBrightBlack** * **bgBrightRed** * **bgBrightGreen** * **bgBrightYellow** * **bgBrightBlue** * **bgBrightMagenta** * **bgBrightCyan** * **bgBrightWhite** # performance-now [![Build Status](https://travis-ci.org/braveg1rl/performance-now.png?branch=master)](https://travis-ci.org/braveg1rl/performance-now) [![Dependency Status](https://david-dm.org/braveg1rl/performance-now.png)](https://david-dm.org/braveg1rl/performance-now) Implements a function similar to `performance.now` (based on `process.hrtime`). Modern browsers have a `window.performance` object with - among others - a `now` method which gives time in milliseconds, but with sub-millisecond precision. This module offers the same function based on the Node.js native `process.hrtime` function. Using `process.hrtime` means that the reported time will be monotonically increasing, and not subject to clock-drift. According to the [High Resolution Time specification](http://www.w3.org/TR/hr-time/), the number of milliseconds reported by `performance.now` should be relative to the value of `performance.timing.navigationStart`. In the current version of the module (2.0) the reported time is relative to the time the current Node process has started (inferred from `process.uptime()`). Version 1.0 reported a different time. The reported time was relative to the time the module was loaded (i.e. the time it was first `require`d). If you need this functionality, version 1.0 is still available on NPM. ## Example usage ```javascript var now = require("performance-now") var start = now() var end = now() console.log(start.toFixed(3)) // the number of milliseconds the current node process is running console.log((start-end).toFixed(3)) // ~ 0.002 on my system ``` Running the now function two times right after each other yields a time difference of a few microseconds. Given this overhead, I think it's best to assume that the precision of intervals computed with this method is not higher than 10 microseconds, if you don't know the exact overhead on your own system. ## License performance-now is released under the [MIT License](http://opensource.org/licenses/MIT). Copyright (c) 2017 Braveg1rl # jsbn: javascript big number [Tom Wu's Original Website](http://www-cs-students.stanford.edu/~tjw/jsbn/) I felt compelled to put this on github and publish to npm. I haven't tested every other big integer library out there, but the few that I have tested in comparison to this one have not even come close in performance. I am aware of the `bi` module on npm, however it has been modified and I wanted to publish the original without modifications. This is jsbn and jsbn2 from Tom Wu's original website above, with the modular pattern applied to prevent global leaks and to allow for use with node.js on the server side. ## usage var BigInteger = require('jsbn'); var a = new BigInteger('91823918239182398123'); alert(a.bitLength()); // 67 ## API ### bi.toString() returns the base-10 number as a string ### bi.negate() returns a new BigInteger equal to the negation of `bi` ### bi.abs returns new BI of absolute value ### bi.compareTo ### bi.bitLength ### bi.mod ### bi.modPowInt ### bi.clone ### bi.intValue ### bi.byteValue ### bi.shortValue ### bi.signum ### bi.toByteArray ### bi.equals ### bi.min ### bi.max ### bi.and ### bi.or ### bi.xor ### bi.andNot ### bi.not ### bi.shiftLeft ### bi.shiftRight ### bi.getLowestSetBit ### bi.bitCount ### bi.testBit ### bi.setBit ### bi.clearBit ### bi.flipBit ### bi.add ### bi.subtract ### bi.multiply ### bi.divide ### bi.remainder ### bi.divideAndRemainder ### bi.modPow ### bi.modInverse ### bi.pow ### bi.gcd ### bi.isProbablePrime # has-values [![NPM version](https://img.shields.io/npm/v/has-values.svg?style=flat)](https://www.npmjs.com/package/has-values) [![NPM downloads](https://img.shields.io/npm/dm/has-values.svg?style=flat)](https://npmjs.org/package/has-values) [![Build Status](https://img.shields.io/travis/jonschlinkert/has-values.svg?style=flat)](https://travis-ci.org/jonschlinkert/has-values) > Returns true if any values exist, false if empty. Works for booleans, functions, numbers, strings, nulls, objects and arrays. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install has-values --save ``` ## Usage ```js var hasValue = require('has-values'); hasValue('a'); //=> true hasValue(''); //=> false hasValue(1); //=> true hasValue(0); //=> false hasValue(0, true); // treat zero as a value //=> true hasValue({a: 'a'}}); //=> true hasValue({}}); //=> false hasValue(['a']); //=> true hasValue([]); //=> false hasValue(function(foo) {}); // function length/arity //=> true hasValue(function() {}); //=> false hasValue(true); hasValue(false); //=> true ``` ## isEmpty To test for empty values, do: ```js function isEmpty(o, isZero) { return !hasValue(o, isZero); } ``` ## Related projects You might also be interested in these projects: * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://www.npmjs.com/package/has-value) | [homepage](https://github.com/jonschlinkert/has-value) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/has-values/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/has-values/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v, on March 27, 2016._ # Regular Expression Tokenizer Tokenizes strings that represent a regular expressions. [![Build Status](https://secure.travis-ci.org/fent/ret.js.svg)](http://travis-ci.org/fent/ret.js) [![Dependency Status](https://david-dm.org/fent/ret.js.svg)](https://david-dm.org/fent/ret.js) [![codecov](https://codecov.io/gh/fent/ret.js/branch/master/graph/badge.svg)](https://codecov.io/gh/fent/ret.js) # Usage ```js var ret = require('ret'); var tokens = ret(/foo|bar/.source); ``` `tokens` will contain the following object ```js { "type": ret.types.ROOT "options": [ [ { "type": ret.types.CHAR, "value", 102 }, { "type": ret.types.CHAR, "value", 111 }, { "type": ret.types.CHAR, "value", 111 } ], [ { "type": ret.types.CHAR, "value", 98 }, { "type": ret.types.CHAR, "value", 97 }, { "type": ret.types.CHAR, "value", 114 } ] ] } ``` # Token Types `ret.types` is a collection of the various token types exported by ret. ### ROOT Only used in the root of the regexp. This is needed due to the posibility of the root containing a pipe `|` character. In that case, the token will have an `options` key that will be an array of arrays of tokens. If not, it will contain a `stack` key that is an array of tokens. ```js { "type": ret.types.ROOT, "stack": [token1, token2...], } ``` ```js { "type": ret.types.ROOT, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### GROUP Groups contain tokens that are inside of a parenthesis. If the group begins with `?` followed by another character, it's a special type of group. A ':' tells the group not to be remembered when `exec` is used. '=' means the previous token matches only if followed by this group, and '!' means the previous token matches only if NOT followed. Like root, it can contain an `options` key instead of `stack` if there is a pipe. ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "stack": [token1, token2...], } ``` ```js { "type": ret.types.GROUP, "remember" true, "followedBy": false, "notFollowedBy": false, "options" [ [token1, token2...], [othertoken1, othertoken2...] ... ], } ``` ### POSITION `\b`, `\B`, `^`, and `$` specify positions in the regexp. ```js { "type": ret.types.POSITION, "value": "^", } ``` ### SET Contains a key `set` specifying what tokens are allowed and a key `not` specifying if the set should be negated. A set can contain other sets, ranges, and characters. ```js { "type": ret.types.SET, "set": [token1, token2...], "not": false, } ``` ### RANGE Used in set tokens to specify a character range. `from` and `to` are character codes. ```js { "type": ret.types.RANGE, "from": 97, "to": 122, } ``` ### REPETITION ```js { "type": ret.types.REPETITION, "min": 0, "max": Infinity, "value": token, } ``` ### REFERENCE References a group token. `value` is 1-9. ```js { "type": ret.types.REFERENCE, "value": 1, } ``` ### CHAR Represents a single character token. `value` is the character code. This might seem a bit cluttering instead of concatenating characters together. But since repetition tokens only repeat the last token and not the last clause like the pipe, it's simpler to do it this way. ```js { "type": ret.types.CHAR, "value": 123, } ``` ## Errors ret.js will throw errors if given a string with an invalid regular expression. All possible errors are * Invalid group. When a group with an immediate `?` character is followed by an invalid character. It can only be followed by `!`, `=`, or `:`. Example: `/(?_abc)/` * Nothing to repeat. Thrown when a repetitional token is used as the first token in the current clause, as in right in the beginning of the regexp or group, or right after a pipe. Example: `/foo|?bar/`, `/{1,3}foo|bar/`, `/foo(+bar)/` * Unmatched ). A group was not opened, but was closed. Example: `/hello)2u/` * Unterminated group. A group was not closed. Example: `/(1(23)4/` * Unterminated character class. A custom character set was not closed. Example: `/[abc/` # Install npm install ret # Tests Tests are written with [vows](http://vowsjs.org/) ```bash npm test ``` # License MIT [![NPM version](https://badge.fury.io/js/sockjs.svg)](http://badge.fury.io/js/sockjs) SockJS family: * [SockJS-client](https://github.com/sockjs/sockjs-client) JavaScript client library * [SockJS-node](https://github.com/sockjs/sockjs-node) Node.js server * [SockJS-erlang](https://github.com/sockjs/sockjs-erlang) Erlang server * [SockJS-tornado](https://github.com/MrJoes/sockjs-tornado) Python/Tornado server * [vert.x](https://github.com/eclipse/vert.x) Java/vert.x server Work in progress: * [SockJS-ruby](https://github.com/nyarly/sockjs-ruby) * [SockJS-netty](https://github.com/cgbystrom/sockjs-netty) * [SockJS-gevent](https://github.com/sdiehl/sockjs-gevent) ([and a fork](https://github.com/njoyce/sockjs-gevent)) * [pyramid-SockJS](https://github.com/fafhrd91/pyramid_sockjs) * [wildcloud-websockets](https://github.com/wildcloud/wildcloud-websockets) * [SockJS-cyclone](https://github.com/flaviogrossi/sockjs-cyclone) * [SockJS-twisted](https://github.com/Fugiman/sockjs-twisted/) * [wai-SockJS](https://github.com/Palmik/wai-sockjs) * [SockJS-perl](https://github.com/vti/sockjs-perl) * [SockJS-go](https://github.com/igm/sockjs-go/) What is SockJS? =============== SockJS is a JavaScript library (for browsers) that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server, with WebSockets or without. This necessitates the use of a server, which this is one version of, for Node.js. SockJS-node server ================== SockJS-node is a Node.js server side counterpart of [SockJS-client browser library](https://github.com/sockjs/sockjs-client) written in CoffeeScript. To install `sockjs-node` run: npm install sockjs A simplified echo SockJS server could look more or less like: ```javascript var http = require('http'); var sockjs = require('sockjs'); var echo = sockjs.createServer({ sockjs_url: 'http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js' }); echo.on('connection', function(conn) { conn.on('data', function(message) { conn.write(message); }); conn.on('close', function() {}); }); var server = http.createServer(); echo.installHandlers(server, {prefix:'/echo'}); server.listen(9999, '0.0.0.0'); ``` (Take look at [examples](https://github.com/sockjs/sockjs-node/tree/master/examples/echo) directory for a complete version.) Subscribe to [SockJS mailing list](https://groups.google.com/forum/#!forum/sockjs) for discussions and support. SockJS-node API --------------- The API design is based on common Node APIs like the [Streams API](http://nodejs.org/docs/v0.5.8/api/streams.html) or the [Http.Server API](http://nodejs.org/docs/v0.5.8/api/http.html#http.Server). ### Server class SockJS module is generating a `Server` class, similar to [Node.js http.createServer](http://nodejs.org/docs/v0.5.8/api/http.html#http.createServer) module. ```javascript var sockjs_server = sockjs.createServer(options); ``` Where `options` is a hash which can contain: <dl> <dt>sockjs_url (string, required)</dt> <dd>Transports which don't support cross-domain communication natively ('eventsource' to name one) use an iframe trick. A simple page is served from the SockJS server (using its foreign domain) and is placed in an invisible iframe. Code run from this iframe doesn't need to worry about cross-domain issues, as it's being run from domain local to the SockJS server. This iframe also does need to load SockJS javascript client library, and this option lets you specify its url (if you're unsure, point it to <a href="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"> the latest minified SockJS client release</a>, this is the default). You must explicitly specify this url on the server side for security reasons - we don't want the possibility of running any foreign javascript within the SockJS domain (aka cross site scripting attack). Also, sockjs javascript library is probably already cached by the browser - it makes sense to reuse the sockjs url you're using in normally.</dd> <dt>prefix (string regex)</dt> <dd>A url prefix for the server. All http requests which paths begins with selected prefix will be handled by SockJS. All other requests will be passed through, to previously registered handlers.</dd> <dt>response_limit (integer)</dt> <dd>Most streaming transports save responses on the client side and don't free memory used by delivered messages. Such transports need to be garbage-collected once in a while. `response_limit` sets a minimum number of bytes that can be send over a single http streaming request before it will be closed. After that client needs to open new request. Setting this value to one effectively disables streaming and will make streaming transports to behave like polling transports. The default value is 128K.</dd> <dt>websocket (boolean)</dt> <dd>Some load balancers don't support websockets. This option can be used to disable websockets support by the server. By default websockets are enabled.</dd> <dt>jsessionid (boolean or function)</dt> <dd>Some hosting providers enable sticky sessions only to requests that have JSESSIONID cookie set. This setting controls if the server should set this cookie to a dummy value. By default setting JSESSIONID cookie is disabled. More sophisticated behaviour can be achieved by supplying a function.</dd> <dt>log (function(severity, message))</dt> <dd>It's quite useful, especially for debugging, to see some messages printed by a SockJS-node library. This is done using this `log` function, which is by default set to `console.log`. If this behaviour annoys you for some reason, override `log` setting with a custom handler. The following `severities` are used: `debug` (miscellaneous logs), `info` (requests logs), `error` (serious errors, consider filing an issue).</dd> <dt>heartbeat_delay (milliseconds)</dt> <dd>In order to keep proxies and load balancers from closing long running http requests we need to pretend that the connection is active and send a heartbeat packet once in a while. This setting controls how often this is done. By default a heartbeat packet is sent every 25 seconds. </dd> <dt>disconnect_delay (milliseconds)</dt> <dd>The server sends a `close` event when a client receiving connection have not been seen for a while. This delay is configured by this setting. By default the `close` event will be emitted when a receiving connection wasn't seen for 5 seconds. </dd> <dt>disable_cors (boolean)</dt> <dd>Enabling this option will prevent <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a> headers from being included in the HTTP response. Can be used when the sockjs client is known to be connecting from the same origin as the sockjs server.</dd> </dl> ### Server instance Once you have create `Server` instance you can hook it to the [http.Server instance](http://nodejs.org/docs/v0.5.8/api/http.html#http.createServer). ```javascript var http_server = http.createServer(); sockjs_server.installHandlers(http_server, options); http_server.listen(...); ``` Where `options` can overshadow options given when creating `Server` instance. `Server` instance is an [EventEmitter](http://nodejs.org/docs/v0.4.10/api/events.html#events.EventEmitter), and emits following event: <dl> <dt>Event: connection (connection)</dt> <dd>A new connection has been successfully opened.</dd> </dl> All http requests that don't go under the path selected by `prefix` will remain unanswered and will be passed to previously registered handlers. You must install your custom http handlers before calling `installHandlers`. ### Connection instance A `Connection` instance supports [Node Stream API](http://nodejs.org/docs/v0.5.8/api/streams.html) and has following methods and properties: <dl> <dt>Property: readable (boolean)</dt> <dd>Is the stream readable?</dd> <dt>Property: writable (boolean)</dt> <dd>Is the stream writable?</dd> <dt>Property: remoteAddress (string)</dt> <dd>Last known IP address of the client.</dd> <dt>Property: remotePort (number)</dt> <dd>Last known port number of the client.</dd> <dt>Property: address (object)</dt> <dd>Hash with 'address' and 'port' fields.</dd> <dt>Property: headers (object)</dt> <dd>Hash containing various headers copied from last receiving request on that connection. Exposed headers include: `origin`, `referer` and `x-forwarded-for` (and friends). We explicitly do not grant access to `cookie` header, as using it may easily lead to security issues (for details read the section "Authorisation").</dd> <dt>Property: url (string)</dt> <dd><a href="http://nodejs.org/docs/v0.4.10/api/http.html#request.url">Url</a> property copied from last request.</dd> <dt>Property: pathname (string)</dt> <dd>`pathname` from parsed url, for convenience.</dd> <dt>Property: prefix (string)</dt> <dd>Prefix of the url on which the request was handled.</dd> <dt>Property: protocol (string)</dt> <dd>Protocol used by the connection. Keep in mind that some protocols are indistinguishable - for example "xhr-polling" and "xdr-polling".</dd> <dt>Property: readyState (integer)</dt> <dd>Current state of the connection: 0-connecting, 1-open, 2-closing, 3-closed.</dd> <dt>write(message)</dt> <dd>Sends a message over opened connection. A message must be a non-empty string. It's illegal to send a message after the connection was closed (either after 'close' or 'end' method or 'close' event).</dd> <dt>close([code], [reason])</dt> <dd>Asks the remote client to disconnect. 'code' and 'reason' parameters are optional and can be used to share the reason of disconnection.</dd> <dt>end()</dt> <dd>Asks the remote client to disconnect with default 'code' and 'reason' values.</dd> </dl> A `Connection` instance emits the following events: <dl> <dt>Event: data (message)</dt> <dd>A message arrived on the connection. Message is a unicode string.</dd> <dt>Event: close ()</dt> <dd>Connection was closed. This event is triggered exactly once for every connection.</dd> </dl> For example: ```javascript sockjs_server.on('connection', function(conn) { console.log('connection' + conn); conn.on('close', function() { console.log('close ' + conn); }); conn.on('data', function(message) { console.log('message ' + conn, message); }); }); ``` ### Footnote A fully working echo server does need a bit more boilerplate (to handle requests unanswered by SockJS), see the [`echo` example](https://github.com/sockjs/sockjs-node/tree/master/examples/echo) for a complete code. ### Examples If you want to see samples of running code, take a look at: * [./examples/echo](https://github.com/sockjs/sockjs-node/tree/master/examples/echo) directory, which contains a full example of a echo server. * [./examples/test_server](https://github.com/sockjs/sockjs-node/tree/master/examples/test_server) a standard SockJS test server. Connecting to SockJS-node without the client -------------------------------------------- Although the main point of SockJS it to enable browser-to-server connectivity, it is possible to connect to SockJS from an external application. Any SockJS server complying with 0.3 protocol does support a raw WebSocket url. The raw WebSocket url for the test server looks like: * ws://localhost:8081/echo/websocket You can connect any WebSocket RFC 6455 compliant WebSocket client to this url. This can be a command line client, external application, third party code or even a browser (though I don't know why you would want to do so). Note: This endpoint will *not send any heartbeat packets*. Deployment and load balancing ----------------------------- There are two issues that need to be considered when planning a non-trivial SockJS-node deployment: WebSocket-compatible load balancer and sticky sessions (aka session affinity). ### WebSocket compatible load balancer Often WebSockets don't play nicely with proxies and load balancers. Deploying a SockJS server behind Nginx or Apache could be painful. Fortunately recent versions of an excellent load balancer [HAProxy](http://haproxy.1wt.eu/) are able to proxy WebSocket connections. We propose to put HAProxy as a front line load balancer and use it to split SockJS traffic from normal HTTP data. Take a look at the sample [SockJS HAProxy configuration](https://github.com/sockjs/sockjs-node/blob/master/examples/haproxy.cfg). The config also shows how to use HAproxy balancing to split traffic between multiple Node.js servers. You can also do balancing using dns names. ### Sticky sessions If you plan deploying more than one SockJS server, you must make sure that all HTTP requests for a single session will hit the same server. SockJS has two mechanisms that can be useful to achieve that: * Urls are prefixed with server and session id numbers, like: `/resource/<server_number>/<session_id>/transport`. This is useful for load balancers that support prefix-based affinity (HAProxy does). * `JSESSIONID` cookie is being set by SockJS-node. Many load balancers turn on sticky sessions if that cookie is set. This technique is derived from Java applications, where sticky sessions are often necessary. HAProxy does support this method, as well as some hosting providers, for example CloudFoundry. In order to enable this method on the client side, please supply a `cookie:true` option to SockJS constructor. Development and testing ----------------------- If you want to work on SockJS-node source code, you need to clone the git repo and follow these steps. First you need to install dependencies: cd sockjs-node npm install npm install --dev ln -s .. node_modules/sockjs You're ready to compile CoffeeScript: make build If compilation succeeds you may want to test if your changes pass all the tests. Currently, there are two separate test suites. For both of them you need to start a SockJS-node test server (by default listening on port 8081): make test_server ### SockJS-protocol Python tests To run it run something like: cd sockjs-protocol make test_deps ./venv/bin/python sockjs-protocol.py For details see [SockJS-protocol README](https://github.com/sockjs/sockjs-protocol#readme). ### SockJS-client QUnit tests You need to start a second web server (by default listening on 8080) that is serving various static html and javascript files: cd sockjs-client make test At that point you should have two web servers running: sockjs-node on 8081 and sockjs-client on 8080. When you open the browser on [http://localhost:8080/](http://localhost:8080/) you should be able run the QUnit tests against your sockjs-node server. For details see [SockJS-client README](https://github.com/sockjs/sockjs-client#readme). Additionally, if you're doing more serious development consider using `make serve`, which will automatically the server when you modify the source code. Various issues and design considerations ---------------------------------------- ### Authorisation SockJS-node does not expose cookies to the application. This is done deliberately as using cookie-based authorisation with SockJS simply doesn't make sense and will lead to security issues. Cookies are a contract between a browser and an http server, and are identified by a domain name. If a browser has a cookie set for particular domain, it will pass it as a part of all http requests to the host. But to get various transports working, SockJS uses a middleman - an iframe hosted from target SockJS domain. That means the server will receive requests from the iframe, and not from the real domain. The domain of an iframe is the same as the SockJS domain. The problem is that any website can embed the iframe and communicate with it - and request establishing SockJS connection. Using cookies for authorisation in this scenario will result in granting full access to SockJS communication with your website from any website. This is a classic CSRF attack. Basically - cookies are not suited for SockJS model. If you want to authorise a session - provide a unique token on a page, send it as a first thing over SockJS connection and validate it on the server side. In essence, this is how cookies work. ### Deploying SockJS on Heroku Long polling is known to cause problems on Heroku, but [workaround for SockJS is available](https://github.com/sockjs/sockjs-node/issues/57#issuecomment-5242187). # signal-exit [![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) [![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) [![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) [![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/signal-exit/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/signal-exit) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the proces to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. # <img src="./logo.png" alt="bn.js" width="160" height="160" /> > BigNum in pure javascript [![Build Status](https://secure.travis-ci.org/indutny/bn.js.png)](http://travis-ci.org/indutny/bn.js) ## Install `npm install --save bn.js` ## Usage ```js const BN = require('bn.js'); var a = new BN('dead', 16); var b = new BN('101010', 2); var res = a.add(b); console.log(res.toString(10)); // 57047 ``` **Note**: decimals are not supported in this library. ## Notation ### Prefixes There are several prefixes to instructions that affect the way the work. Here is the list of them in the order of appearance in the function name: * `i` - perform operation in-place, storing the result in the host object (on which the method was invoked). Might be used to avoid number allocation costs * `u` - unsigned, ignore the sign of operands when performing operation, or always return positive value. Second case applies to reduction operations like `mod()`. In such cases if the result will be negative - modulo will be added to the result to make it positive ### Postfixes The only available postfix at the moment is: * `n` - which means that the argument of the function must be a plain JavaScript Number. Decimals are not supported. ### Examples * `a.iadd(b)` - perform addition on `a` and `b`, storing the result in `a` * `a.umod(b)` - reduce `a` modulo `b`, returning positive value * `a.iushln(13)` - shift bits of `a` left by 13 ## Instructions Prefixes/postfixes are put in parens at the of the line. `endian` - could be either `le` (little-endian) or `be` (big-endian). ### Utilities * `a.clone()` - clone number * `a.toString(base, length)` - convert to base-string and pad with zeroes * `a.toNumber()` - convert to Javascript Number (limited to 53 bits) * `a.toJSON()` - convert to JSON compatible hex string (alias of `toString(16)`) * `a.toArray(endian, length)` - convert to byte `Array`, and optionally zero pad to length, throwing if already exceeding * `a.toArrayLike(type, endian, length)` - convert to an instance of `type`, which must behave like an `Array` * `a.toBuffer(endian, length)` - convert to Node.js Buffer (if available). For compatibility with browserify and similar tools, use this instead: `a.toArrayLike(Buffer, endian, length)` * `a.bitLength()` - get number of bits occupied * `a.zeroBits()` - return number of less-significant consequent zero bits (example: `1010000` has 4 zero bits) * `a.byteLength()` - return number of bytes occupied * `a.isNeg()` - true if the number is negative * `a.isEven()` - no comments * `a.isOdd()` - no comments * `a.isZero()` - no comments * `a.cmp(b)` - compare numbers and return `-1` (a `<` b), `0` (a `==` b), or `1` (a `>` b) depending on the comparison result (`ucmp`, `cmpn`) * `a.lt(b)` - `a` less than `b` (`n`) * `a.lte(b)` - `a` less than or equals `b` (`n`) * `a.gt(b)` - `a` greater than `b` (`n`) * `a.gte(b)` - `a` greater than or equals `b` (`n`) * `a.eq(b)` - `a` equals `b` (`n`) * `a.toTwos(width)` - convert to two's complement representation, where `width` is bit width * `a.fromTwos(width)` - convert from two's complement representation, where `width` is the bit width * `BN.isBN(object)` - returns true if the supplied `object` is a BN.js instance ### Arithmetics * `a.neg()` - negate sign (`i`) * `a.abs()` - absolute value (`i`) * `a.add(b)` - addition (`i`, `n`, `in`) * `a.sub(b)` - subtraction (`i`, `n`, `in`) * `a.mul(b)` - multiply (`i`, `n`, `in`) * `a.sqr()` - square (`i`) * `a.pow(b)` - raise `a` to the power of `b` * `a.div(b)` - divide (`divn`, `idivn`) * `a.mod(b)` - reduct (`u`, `n`) (but no `umodn`) * `a.divRound(b)` - rounded division ### Bit operations * `a.or(b)` - or (`i`, `u`, `iu`) * `a.and(b)` - and (`i`, `u`, `iu`, `andln`) (NOTE: `andln` is going to be replaced with `andn` in future) * `a.xor(b)` - xor (`i`, `u`, `iu`) * `a.setn(b)` - set specified bit to `1` * `a.shln(b)` - shift left (`i`, `u`, `iu`) * `a.shrn(b)` - shift right (`i`, `u`, `iu`) * `a.testn(b)` - test if specified bit is set * `a.maskn(b)` - clear bits with indexes higher or equal to `b` (`i`) * `a.bincn(b)` - add `1 << b` to the number * `a.notn(w)` - not (for the width specified by `w`) (`i`) ### Reduction * `a.gcd(b)` - GCD * `a.egcd(b)` - Extended GCD results (`{ a: ..., b: ..., gcd: ... }`) * `a.invm(b)` - inverse `a` modulo `b` ## Fast reduction When doing lots of reductions using the same modulo, it might be beneficial to use some tricks: like [Montgomery multiplication][0], or using special algorithm for [Mersenne Prime][1]. ### Reduction context To enable this tricks one should create a reduction context: ```js var red = BN.red(num); ``` where `num` is just a BN instance. Or: ```js var red = BN.red(primeName); ``` Where `primeName` is either of these [Mersenne Primes][1]: * `'k256'` * `'p224'` * `'p192'` * `'p25519'` Or: ```js var red = BN.mont(num); ``` To reduce numbers with [Montgomery trick][0]. `.mont()` is generally faster than `.red(num)`, but slower than `BN.red(primeName)`. ### Converting numbers Before performing anything in reduction context - numbers should be converted to it. Usually, this means that one should: * Convert inputs to reducted ones * Operate on them in reduction context * Convert outputs back from the reduction context Here is how one may convert numbers to `red`: ```js var redA = a.toRed(red); ``` Where `red` is a reduction context created using instructions above Here is how to convert them back: ```js var a = redA.fromRed(); ``` ### Red instructions Most of the instructions from the very start of this readme have their counterparts in red context: * `a.redAdd(b)`, `a.redIAdd(b)` * `a.redSub(b)`, `a.redISub(b)` * `a.redShl(num)` * `a.redMul(b)`, `a.redIMul(b)` * `a.redSqr()`, `a.redISqr()` * `a.redSqrt()` - square root modulo reduction context's prime * `a.redInvm()` - modular inverse of the number * `a.redNeg()` * `a.redPow(b)` - modular exponentiation ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: https://en.wikipedia.org/wiki/Montgomery_modular_multiplication [1]: https://en.wikipedia.org/wiki/Mersenne_prime # assert [![Build Status](https://travis-ci.org/defunctzombie/commonjs-assert.svg?branch=master)](https://travis-ci.org/defunctzombie/commonjs-assert) This module is used for writing unit tests for your applications, you can access it with require('assert'). The API is derived from the [commonjs 1.0 unit testing](http://wiki.commonjs.org/wiki/Unit_Testing/1.0) spec and the [node.js assert module](http://nodejs.org/api/assert.html) ## assert.fail(actual, expected, message, operator) Throws an exception that displays the values for actual and expected separated by the provided operator. ## assert(value, message), assert.ok(value, [message]) Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message); ## assert.equal(actual, expected, [message]) Tests shallow, coercive equality with the equal comparison operator ( == ). ## assert.notEqual(actual, expected, [message]) Tests shallow, coercive non-equality with the not equal comparison operator ( != ). ## assert.deepEqual(actual, expected, [message]) Tests for deep equality. ## assert.notDeepEqual(actual, expected, [message]) Tests for any deep inequality. ## assert.strictEqual(actual, expected, [message]) Tests strict equality, as determined by the strict equality operator ( === ) ## assert.notStrictEqual(actual, expected, [message]) Tests strict non-equality, as determined by the strict not equal operator ( !== ) ## assert.throws(block, [error], [message]) Expects block to throw an error. error can be constructor, regexp or validation function. Validate instanceof using constructor: ```javascript assert.throws(function() { throw new Error("Wrong value"); }, Error); ``` Validate error message using RegExp: ```javascript assert.throws(function() { throw new Error("Wrong value"); }, /value/); ``` Custom error validation: ```javascript assert.throws(function() { throw new Error("Wrong value"); }, function(err) { if ( (err instanceof Error) && /value/.test(err) ) { return true; } }, "unexpected error"); ``` ## assert.doesNotThrow(block, [message]) Expects block not to throw an error, see assert.throws for details. ## assert.ifError(value) Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks. # Tapable The tapable package expose many Hook classes, which can be used to create hooks for plugins. ``` javascript const { SyncHook, SyncBailHook, SyncWaterfallHook, SyncLoopHook, AsyncParallelHook, AsyncParallelBailHook, AsyncSeriesHook, AsyncSeriesBailHook, AsyncSeriesWaterfallHook } = require("tapable"); ``` ## Installation ``` shell npm install --save tapable ``` ## Usage All Hook constructors take one optional argument, which is a list of argument names as strings. ``` js const hook = new SyncHook(["arg1", "arg2", "arg3"]); ``` The best practice is to expose all hooks of a class in a `hooks` property: ``` js class Car { constructor() { this.hooks = { accelerate: new SyncHook(["newSpeed"]), brake: new SyncHook(), calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]) }; } /* ... */ } ``` Other people can now use these hooks: ``` js const myCar = new Car(); // Use the tap method to add a consument myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on()); ``` It's required to pass a name to identify the plugin/reason. You may receive arguments: ``` js myCar.hooks.accelerate.tap("LoggerPlugin", newSpeed => console.log(`Accelerating to ${newSpeed}`)); ``` For sync hooks, `tap` is the only valid method to add a plugin. Async hooks also support async plugins: ``` js myCar.hooks.calculateRoutes.tapPromise("GoogleMapsPlugin", (source, target, routesList) => { // return a promise return google.maps.findRoute(source, target).then(route => { routesList.add(route); }); }); myCar.hooks.calculateRoutes.tapAsync("BingMapsPlugin", (source, target, routesList, callback) => { bing.findRoute(source, target, (err, route) => { if(err) return callback(err); routesList.add(route); // call the callback callback(); }); }); // You can still use sync plugins myCar.hooks.calculateRoutes.tap("CachedRoutesPlugin", (source, target, routesList) => { const cachedRoute = cache.get(source, target); if(cachedRoute) routesList.add(cachedRoute); }) ``` The class declaring these hooks need to call them: ``` js class Car { /* ... */ setSpeed(newSpeed) { this.hooks.accelerate.call(newSpeed); } useNavigationSystemPromise(source, target) { const routesList = new List(); return this.hooks.calculateRoutes.promise(source, target, routesList).then(() => { return routesList.getRoutes(); }); } useNavigationSystemAsync(source, target, callback) { const routesList = new List(); this.hooks.calculateRoutes.callAsync(source, target, routesList, err => { if(err) return callback(err); callback(null, routesList.getRoutes()); }); } } ``` The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on: * The number of registered plugins (none, one, many) * The kind of registered plugins (sync, async, promise) * The used call method (sync, async, promise) * The number of arguments * Whether interception is used This ensures fastest possible execution. ## Hook types Each hook can be tapped with one or several functions. How they are executed depends on the hook type: * Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row. * __Waterfall__. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function. * __Bail__. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones. * __Loop__. TODO Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes: * __Sync__. A sync hook can only be tapped with synchronous functions (using `myHook.tap()`). * __AsyncSeries__. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). They call each async method in a row. * __AsyncParallel__. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). However, they run each async method in parallel. The hook type is reflected in its class name. E.g., `AsyncSeriesWaterfallHook` allows asynchronous functions and runs them in series, passing each function’s return value into the next function. ## Interception All Hooks offer an additional interception API: ``` js myCar.hooks.calculateRoutes.intercept({ call: (source, target, routesList) => { console.log("Starting to calculate routes"); }, register: (tapInfo) => { // tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ... } console.log(`${tapInfo.name} is doing its job`); return tapInfo; // may return a new tapInfo object } }) ``` **call**: `(...args) => void` Adding `call` to your interceptor will trigger when hooks are triggered. You have access to the hooks arguments. **tap**: `(tap: Tap) => void` Adding `tap` to your interceptor will trigger when a plugin taps into a hook. Provided is the `Tap` object. `Tap` object can't be changed. **loop**: `(...args) => void` Adding `loop` to your interceptor will trigger for each loop of a looping hook. **register**: `(tap: Tap) => Tap | undefined` Adding `register` to your interceptor will trigger for each added `Tap` and allows to modify it. ## Context Plugins and interceptors can opt-in to access an optional `context` object, which can be used to pass arbitrary values to subsequent plugins and interceptors. ``` js myCar.hooks.accelerate.intercept({ context: true, tap: (context, tapInfo) => { // tapInfo = { type: "sync", name: "NoisePlugin", fn: ... } console.log(`${tapInfo.name} is doing it's job`); // `context` starts as an empty object if at least one plugin uses `context: true`. // If no plugins use `context: true`, then `context` is undefined. if (context) { // Arbitrary properties can be added to `context`, which plugins can then access. context.hasMuffler = true; } } }); myCar.hooks.accelerate.tap({ name: "NoisePlugin", context: true }, (context, newSpeed) => { if (context && context.hasMuffler) { console.log("Silence..."); } else { console.log("Vroom!"); } }); ``` ## HookMap A HookMap is a helper class for a Map with Hooks ``` js const keyedHook = new HookMap(key => new SyncHook(["arg"])) ``` ``` js keyedHook.tap("some-key", "MyPlugin", (arg) => { /* ... */ }); keyedHook.tapAsync("some-key", "MyPlugin", (arg, callback) => { /* ... */ }); keyedHook.tapPromise("some-key", "MyPlugin", (arg) => { /* ... */ }); ``` ``` js const hook = keyedHook.get("some-key"); if(hook !== undefined) { hook.callAsync("arg", err => { /* ... */ }); } ``` ## Hook/HookMap interface Public: ``` ts interface Hook { tap: (name: string | Tap, fn: (context?, ...args) => Result) => void, tapAsync: (name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void, tapPromise: (name: string | Tap, fn: (context?, ...args) => Promise<Result>) => void, intercept: (interceptor: HookInterceptor) => void } interface HookInterceptor { call: (context?, ...args) => void, loop: (context?, ...args) => void, tap: (context?, tap: Tap) => void, register: (tap: Tap) => Tap, context: boolean } interface HookMap { for: (key: any) => Hook, tap: (key: any, name: string | Tap, fn: (context?, ...args) => Result) => void, tapAsync: (key: any, name: string | Tap, fn: (context?, ...args, callback: (err, result: Result) => void) => void) => void, tapPromise: (key: any, name: string | Tap, fn: (context?, ...args) => Promise<Result>) => void, intercept: (interceptor: HookMapInterceptor) => void } interface HookMapInterceptor { factory: (key: any, hook: Hook) => Hook } interface Tap { name: string, type: string fn: Function, stage: number, context: boolean } ``` Protected (only for the class containing the hook): ``` ts interface Hook { isUsed: () => boolean, call: (...args) => Result, promise: (...args) => Promise<Result>, callAsync: (...args, callback: (err, result: Result) => void) => void, } interface HookMap { get: (key: any) => Hook | undefined, for: (key: any) => Hook } ``` ## MultiHook A helper Hook-like class to redirect taps to multiple other hooks: ``` js const { MultiHook } = require("tapable"); this.hooks.allHooks = new MultiHook([this.hooks.hookA, this.hooks.hookB]); ``` # through2 [![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/) **A tiny wrapper around Node streams.Transform (Streams2/3) to avoid explicit subclassing noise** Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`. Note: As 2.x.x this module starts using **Streams3** instead of Stream2. To continue using a Streams2 version use `npm install through2@0` to fetch the latest version of 0.x.x. More information about Streams2 vs Streams3 and recommendations see the article **[Why I don't use Node's core 'stream' module](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html)**. ```js fs.createReadStream('ex.txt') .pipe(through2(function (chunk, enc, callback) { for (var i = 0; i < chunk.length; i++) if (chunk[i] == 97) chunk[i] = 122 // swap 'a' for 'z' this.push(chunk) callback() })) .pipe(fs.createWriteStream('out.txt')) .on('finish', () => doSomethingSpecial()) ``` Or object streams: ```js var all = [] fs.createReadStream('data.csv') .pipe(csv2()) .pipe(through2.obj(function (chunk, enc, callback) { var data = { name : chunk[0] , address : chunk[3] , phone : chunk[10] } this.push(data) callback() })) .on('data', (data) => { all.push(data) }) .on('end', () => { doSomethingSpecial(all) }) ``` Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`. ## API <b><code>through2([ options, ] [ transformFunction ] [, flushFunction ])</code></b> Consult the **[stream.Transform](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`). ### options The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`). The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call: ```js fs.createReadStream('/tmp/important.dat') .pipe(through2({ objectMode: true, allowHalfOpen: false }, (chunk, enc, cb) => { cb(null, 'wut?') // note we can use the second argument on the callback // to provide data as an alternative to this.push('wut?') } ) .pipe(fs.createWriteStream('/tmp/wut.txt')) ``` ### transformFunction The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk. To queue a new chunk, call `this.push(chunk)`&mdash;this can be called as many times as required before the `callback()` if you have multiple pieces to send on. Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error. If you **do not provide a `transformFunction`** then you will get a simple pass-through stream. ### flushFunction The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress. ```js fs.createReadStream('/tmp/important.dat') .pipe(through2( (chunk, enc, cb) => cb(null, chunk), // transform is a noop function (cb) { // flush function this.push('tacking on an extra buffer to the end'); cb(); } )) .pipe(fs.createWriteStream('/tmp/wut.txt')); ``` <b><code>through2.ctor([ options, ] transformFunction[, flushFunction ])</code></b> Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances. ```js var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) { if (record.temp != null && record.unit == "F") { record.temp = ( ( record.temp - 32 ) * 5 ) / 9 record.unit = "C" } this.push(record) callback() }) // Create instances of FToC like so: var converter = new FToC() // Or: var converter = FToC() // Or specify/override options when you instantiate, if you prefer: var converter = FToC({objectMode: true}) ``` ## See Also - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams. - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams. - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams. - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies. - the [mississippi stream utility collection](https://github.com/maxogden/mississippi) includes `through2` as well as many more useful stream modules similar to this one ## License **through2** is Copyright (c) Rod Vagg [@rvagg](https://twitter.com/rvagg) and additional contributors and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. # detect-file [![NPM version](https://img.shields.io/npm/v/detect-file.svg?style=flat)](https://www.npmjs.com/package/detect-file) [![NPM monthly downloads](https://img.shields.io/npm/dm/detect-file.svg?style=flat)](https://npmjs.org/package/detect-file) [![NPM total downloads](https://img.shields.io/npm/dt/detect-file.svg?style=flat)](https://npmjs.org/package/detect-file) [![Linux Build Status](https://img.shields.io/travis/doowb/detect-file.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/detect-file) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/detect-file.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/detect-file) > Detects if a file exists and returns the resolved filepath. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save detect-file ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add detect-file ``` ## Usage ```js var detect = require('detect-file'); ``` ## API ### [detect](index.js#L33) Detect the given `filepath` if it exists. **Params** * `filepath` **{String}**: filepath to detect. * `options` **{Object}**: Additional options. * `options.nocase` **{Boolean}**: Set this to `true` to force case-insensitive filename checks. This is useful on case sensitive file systems. * `returns` **{String}**: Returns the detected filepath if it exists, otherwise returns `null`. **Example** ```js var res = detect('package.json'); console.log(res); //=> "package.json" var res = detect('fake-file.json'); console.log(res) //=> null ``` ## Case sensitive file systems When using the `nocase` option, this library will attempt to detect the filepath with the following methods: 1. Try to read all files in the `filepath` using `fs.readdirSync`. If successful and `filepath` is a directory, return the `filepath`. 2. Try to read all files in the `filepath`'s directory using `fs.readdirSync`. If successful, do case insensitive comparasions of the `filepath` to the files in `filepath`'s directory. ## About ### Related projects [fs-exists-sync](https://www.npmjs.com/package/fs-exists-sync): Drop-in replacement for `fs.existsSync` with zero dependencies. Other libs I found either have crucial differences… [more](https://github.com/jonschlinkert/fs-exists-sync) | [homepage](https://github.com/jonschlinkert/fs-exists-sync "Drop-in replacement for `fs.existsSync` with zero dependencies. Other libs I found either have crucial differences from fs.existsSync, or unnecessary dependencies. See README.md for more info.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Brian Woodward** * [github/doowb](https://github.com/doowb) * [twitter/doowb](https://twitter.com/doowb) ### License Copyright © 2017, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on August 05, 2017._ <p align="center"> <img src="https://raw.github.com/nodejitsu/node-http-proxy/master/doc/logo.png"/> </p> # node-http-proxy [![Build Status](https://travis-ci.org/nodejitsu/node-http-proxy.svg?branch=master)](https://travis-ci.org/nodejitsu/node-http-proxy) [![codecov](https://codecov.io/gh/nodejitsu/node-http-proxy/branch/master/graph/badge.svg)](https://codecov.io/gh/nodejitsu/node-http-proxy) `node-http-proxy` is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as reverse proxies and load balancers. ### Table of Contents * [Installation](#installation) * [Upgrading from 0.8.x ?](#upgrading-from-08x-) * [Core Concept](#core-concept) * [Use Cases](#use-cases) * [Setup a basic stand-alone proxy server](#setup-a-basic-stand-alone-proxy-server) * [Setup a stand-alone proxy server with custom server logic](#setup-a-stand-alone-proxy-server-with-custom-server-logic) * [Setup a stand-alone proxy server with proxy request header re-writing](#setup-a-stand-alone-proxy-server-with-proxy-request-header-re-writing) * [Modify a response from a proxied server](#modify-a-response-from-a-proxied-server) * [Setup a stand-alone proxy server with latency](#setup-a-stand-alone-proxy-server-with-latency) * [Using HTTPS](#using-https) * [Proxying WebSockets](#proxying-websockets) * [Options](#options) * [Listening for proxy events](#listening-for-proxy-events) * [Shutdown](#shutdown) * [Miscellaneous](#miscellaneous) * [Test](#test) * [ProxyTable API](#proxytable-api) * [Logo](#logo) * [Contributing and Issues](#contributing-and-issues) * [License](#license) ### Installation `npm install http-proxy --save` **[Back to top](#table-of-contents)** ### Upgrading from 0.8.x ? Click [here](UPGRADING.md) **[Back to top](#table-of-contents)** ### Core Concept A new proxy is created by calling `createProxyServer` and passing an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L22-L50)) ```javascript var httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(options); // See (†) ``` †Unless listen(..) is invoked on the object, this does not create a webserver. See below. An object will be returned with four methods: * web `req, res, [options]` (used for proxying regular HTTP(S) requests) * ws `req, socket, head, [options]` (used for proxying WS(S) requests) * listen `port` (a function that wraps the object in a webserver, for your convenience) * close `[callback]` (a function that closes the inner webserver and stops listening on given port) It is then possible to proxy requests by calling these functions ```javascript http.createServer(function(req, res) { proxy.web(req, res, { target: 'http://mytarget.com:8080' }); }); ``` Errors can be listened on either using the Event Emitter API ```javascript proxy.on('error', function(e) { ... }); ``` or using the callback API ```javascript proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... }); ``` When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes)) which apply transformations to both the `req` and `res` object. The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target. The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data to the client. **[Back to top](#table-of-contents)** ### Use Cases #### Setup a basic stand-alone proxy server ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create your proxy server and set the target in the options. // httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†) // // Create your target server // http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9000); ``` †Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created. **[Back to top](#table-of-contents)** #### Setup a stand-alone proxy server with custom server logic This example shows how you can proxy a request using your own HTTP server and also you can put your own logic to handle the request. ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); // // Create your custom server and just call `proxy.web()` to proxy // a web request to the target passed in the options // also you can use `proxy.ws()` to proxy a websockets request // var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: 'http://127.0.0.1:5060' }); }); console.log("listening on port 5050") server.listen(5050); ``` **[Back to top](#table-of-contents)** #### Setup a stand-alone proxy server with proxy request header re-writing This example shows how you can proxy a request using your own HTTP server that modifies the outgoing proxy request by adding a special header. ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); // To modify the proxy connection before data is sent, you can listen // for the 'proxyReq' event. When the event is fired, you will receive // the following arguments: // (http.ClientRequest proxyReq, http.IncomingMessage req, // http.ServerResponse res, Object options). This mechanism is useful when // you need to modify the proxy request before the proxy connection // is made to the target. // proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); }); var server = http.createServer(function(req, res) { // You can define here your custom logic to handle the request // and then proxy the request. proxy.web(req, res, { target: 'http://127.0.0.1:5060' }); }); console.log("listening on port 5050") server.listen(5050); ``` **[Back to top](#table-of-contents)** #### Modify a response from a proxied server Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on. [Harmon](https://github.com/No9/harmon) allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum. **[Back to top](#table-of-contents)** #### Setup a stand-alone proxy server with latency ```js var http = require('http'), httpProxy = require('http-proxy'); // // Create a proxy server with latency // var proxy = httpProxy.createProxyServer(); // // Create your server that makes an operation that waits a while // and then proxies the request // http.createServer(function (req, res) { // This simulates an operation that takes 500ms to execute setTimeout(function () { proxy.web(req, res, { target: 'http://localhost:9008' }); }, 500); }).listen(8008); // // Create your target server // http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.end(); }).listen(9008); ``` **[Back to top](#table-of-contents)** #### Using HTTPS You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set `secure: true` in the options. ##### HTTPS -> HTTP ```js // // Create the HTTPS proxy server in front of a HTTP server // httpProxy.createServer({ target: { host: 'localhost', port: 9009 }, ssl: { key: fs.readFileSync('valid-ssl-key.pem', 'utf8'), cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8') } }).listen(8009); ``` ##### HTTPS -> HTTPS ```js // // Create the proxy server listening on port 443 // httpProxy.createServer({ ssl: { key: fs.readFileSync('valid-ssl-key.pem', 'utf8'), cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8') }, target: 'https://localhost:9010', secure: true // Depends on your needs, could be false. }).listen(443); ``` ##### HTTP -> HTTPS (using a PKCS12 client certificate) ```js // // Create an HTTP proxy server with an HTTPS target // httpProxy.createProxyServer({ target: { protocol: 'https:', host: 'my-domain-name', port: 443, pfx: fs.readFileSync('path/to/certificate.p12'), passphrase: 'password', }, changeOrigin: true, }).listen(8000); ``` **[Back to top](#table-of-contents)** #### Proxying WebSockets You can activate the websocket support for the proxy using `ws:true` in the options. ```js // // Create a proxy server for websockets // httpProxy.createServer({ target: 'ws://localhost:9014', ws: true }).listen(8014); ``` Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method. ```js // // Setup our server to proxy standard HTTP requests // var proxy = new httpProxy.createProxyServer({ target: { host: 'localhost', port: 9015 } }); var proxyServer = http.createServer(function (req, res) { proxy.web(req, res); }); // // Listen to the `upgrade` event and proxy the // WebSocket requests as well. // proxyServer.on('upgrade', function (req, socket, head) { proxy.ws(req, socket, head); }); proxyServer.listen(8015); ``` **[Back to top](#table-of-contents)** ### Options `httpProxy.createProxyServer` supports the following options: * **target**: url string to be parsed with the url module * **forward**: url string to be parsed with the url module * **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects) * **ssl**: object to be passed to https.createServer() * **ws**: true/false, if you want to proxy websockets * **xfwd**: true/false, adds x-forward headers * **secure**: true/false, if you want to verify the SSL Certs * **toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies) * **prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path * **ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required). * **localAddress**: Local interface string to bind for outgoing connections * **changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL * **preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key * **auth**: Basic authentication i.e. 'user:password' to compute an Authorization header. * **hostRewrite**: rewrites the location hostname on (201/301/302/307/308) redirects. * **autoRewrite**: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. * **protocolRewrite**: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. * **cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values: * `false` (default): disable cookie rewriting * String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`. * Object: mapping of domains to new domains, use `"*"` to match all domains. For example keep one domain unchanged, rewrite one domain and remove other domains: ``` cookieDomainRewrite: { "unchanged.domain": "unchanged.domain", "old.domain": "new.domain", "*": "" } ``` * **cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values: * `false` (default): disable cookie rewriting * String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`. * Object: mapping of paths to new paths, use `"*"` to match all paths. For example, to keep one path unchanged, rewrite one path and remove other paths: ``` cookiePathRewrite: { "/unchanged.path/": "/unchanged.path/", "/old.path/": "/new.path/", "*": "" } ``` * **headers**: object with extra headers to be added to target requests. * **proxyTimeout**: timeout (in millis) for outgoing proxy requests * **timeout**: timeout (in millis) for incoming requests * **followRedirects**: true/false, Default: false - specify whether you want to follow redirects * **selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event * **buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option: ``` 'use strict'; const streamify = require('stream-array'); const HttpProxy = require('http-proxy'); const proxy = new HttpProxy(); module.exports = (req, res, next) => { proxy.web(req, res, { target: 'http://localhost:4003/', buffer: streamify(req.rawBody) }, next); }; ``` **NOTE:** `options.ws` and `options.ssl` are optional. `options.target` and `options.forward` cannot both be missing If you are using the `proxyServer.listen` method, the following options are also applicable: * **ssl**: object to be passed to https.createServer() * **ws**: true/false, if you want to proxy websockets **[Back to top](#table-of-contents)** ### Listening for proxy events * `error`: The error event is emitted if the request to the target fail. **We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.** * `proxyReq`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections * `proxyReqWs`: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections * `proxyRes`: This event is emitted if the request to the target got a response. * `open`: This event is emitted once the proxy websocket was created and piped into the target websocket. * `close`: This event is emitted once the proxy websocket was closed. * (DEPRECATED) `proxySocket`: Deprecated in favor of `open`. ```js var httpProxy = require('http-proxy'); // Error example // // Http Proxy Server with bad target // var proxy = httpProxy.createServer({ target:'http://localhost:9005' }); proxy.listen(8005); // // Listen for the `error` event on `proxy`. proxy.on('error', function (err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong. And we are reporting a custom error message.'); }); // // Listen for the `proxyRes` event on `proxy`. // proxy.on('proxyRes', function (proxyRes, req, res) { console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2)); }); // // Listen for the `open` event on `proxy`. // proxy.on('open', function (proxySocket) { // listen for messages coming FROM the target here proxySocket.on('data', hybiParseAndLogMessage); }); // // Listen for the `close` event on `proxy`. // proxy.on('close', function (res, socket, head) { // view disconnected websocket connections console.log('Client disconnected'); }); ``` **[Back to top](#table-of-contents)** ### Shutdown * When testing or running server within another program it may be necessary to close the proxy. * This will stop the proxy from accepting new connections. ```js var proxy = new httpProxy.createProxyServer({ target: { host: 'localhost', port: 1337 } }); proxy.close(); ``` **[Back to top](#table-of-contents)** ### Miscellaneous If you want to handle your own response after receiving the `proxyRes`, you can do so with `selfHandleResponse`. As you can see below, if you use this option, you are able to intercept and read the `proxyRes` but you must also make sure to reply to the `res` itself otherwise the original client will never receive any data. ### Modify response ```js var option = { target: target, selfHandleResponse : true }; proxy.on('proxyRes', function (proxyRes, req, res) { var body = new Buffer(''); proxyRes.on('data', function (data) { body = Buffer.concat([body, data]); }); proxyRes.on('end', function () { body = body.toString(); console.log("res from proxied server:", body); res.end("my response to cli"); }); }); proxy.web(req, res, option); ``` #### ProxyTable API A proxy table API is available through this add-on [module](https://github.com/donasaur/http-proxy-rules), which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to. #### Test ``` $ npm test ``` #### Logo Logo created by [Diego Pasquali](http://dribbble.com/diegopq) **[Back to top](#table-of-contents)** ### Contributing and Issues * Read carefully our [Code Of Conduct](https://github.com/nodejitsu/node-http-proxy/blob/master/CODE_OF_CONDUCT.md) * Search on Google/Github * If you can't find anything, open an issue * If you feel comfortable about fixing the issue, fork the repo * Commit to your local branch (which must be different from `master`) * Submit your Pull Request (be sure to include tests and update documentation) **[Back to top](#table-of-contents)** ### License >The MIT License (MIT) > >Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors. > >Permission is hereby granted, free of charge, to any person obtaining a copy >of this software and associated documentation files (the "Software"), to deal >in the Software without restriction, including without limitation the rights >to use, copy, modify, merge, publish, distribute, sublicense, and/or sell >copies of the Software, and to permit persons to whom the Software is >furnished to do so, subject to the following conditions: > >The above copyright notice and this permission notice shall be included in >all copies or substantial portions of the Software. > >THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR >IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, >FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE >AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER >LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, >OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN >THE SOFTWARE. <!-- -- This file is auto-generated from src/README_js.md. Changes should be made there. --> # Mime A comprehensive, compact MIME type module. [![Build Status](https://travis-ci.org/broofa/node-mime.svg?branch=master)](https://travis-ci.org/broofa/node-mime) ## Version 2 Notes Version 2 is a breaking change from 1.x as the semver implies. Specifically: * `lookup()` renamed to `getType()` * `extension()` renamed to `getExtension()` * `charset()` and `load()` methods have been removed If you prefer the legacy version of this module please `npm install mime@^1`. Version 1 docs may be found [here](https://github.com/broofa/node-mime/tree/v1.4.0). ## Install ### NPM ``` npm install mime ``` ### Browser It is recommended that you use a bundler such as [webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to package your code. However, browser-ready versions are available via wzrd.in. E.g. For the full version: <script src="https://wzrd.in/standalone/mime@latest"></script> <script> mime.getType(...); // etc. <script> Or, for the `mime/lite` version: <script src="https://wzrd.in/standalone/mime%2flite@latest"></script> <script> mimelite.getType(...); // (Note `mimelite` here) <script> ## Quick Start For the full version (800+ MIME types, 1,000+ extensions): ```javascript const mime = require('mime'); mime.getType('txt'); // ⇨ 'text/plain' mime.getExtension('text/plain'); // ⇨ 'txt' ``` See [Mime API](#mime-api) below for API details. ## Lite Version There is also a "lite" version of this module that omits vendor-specific (`*/vnd.*`) and experimental (`*/x-*`) types. It weighs in at ~2.5KB, compared to 8KB for the full version. To load the lite version: ```javascript const mime = require('mime/lite'); ``` ## Mime .vs. mime-types .vs. mime-db modules For those of you wondering about the difference between these [popular] NPM modules, here's a brief rundown ... [`mime-db`](https://github.com/jshttp/mime-db) is "the source of truth" for MIME type information. It is not an API. Rather, it is a canonical dataset of mime type definitions pulled from IANA, Apache, NGINX, and custom mappings submitted by the Node.js community. [`mime-types`](https://github.com/jshttp/mime-types) is a thin wrapper around mime-db that provides an API drop-in compatible(ish) with `mime @ < v1.3.6` API. `mime` is, as of v2, a self-contained module bundled with a pre-optimized version of the `mime-db` dataset. It provides a simplified API with the following characteristics: * Intelligently resolved type conflicts (See [mime-score](https://github.com/broofa/mime-score) for details) * Method naming consistent with industry best-practices * Compact footprint. E.g. The minified+compressed sizes of the various modules: Module | Size --- | --- `mime-db` | 18 KB `mime-types` | same as mime-db `mime` | 8 KB `mime/lite` | 2 KB ## Mime API Both `require('mime')` and `require('mime/lite')` return instances of the MIME class, documented below. Note: Inputs to this API are case-insensitive. Outputs (returned values) will be lowercase. ### new Mime(typeMap, ... more maps) Most users of this module will not need to create Mime instances directly. However if you would like to create custom mappings, you may do so as follows ... ```javascript // Require Mime class const Mime = require('mime/Mime'); // Define mime type -> extensions map const typeMap = { 'text/abc': ['abc', 'alpha', 'bet'], 'text/def': ['leppard'] }; // Create and use Mime instance const myMime = new Mime(typeMap); myMime.getType('abc'); // ⇨ 'text/abc' myMime.getExtension('text/def'); // ⇨ 'leppard' ``` If more than one map argument is provided, each map is `define()`ed (see below), in order. ### mime.getType(pathOrExtension) Get mime type for the given path or extension. E.g. ```javascript mime.getType('js'); // ⇨ 'application/javascript' mime.getType('json'); // ⇨ 'application/json' mime.getType('txt'); // ⇨ 'text/plain' mime.getType('dir/text.txt'); // ⇨ 'text/plain' mime.getType('dir\\text.txt'); // ⇨ 'text/plain' mime.getType('.text.txt'); // ⇨ 'text/plain' mime.getType('.txt'); // ⇨ 'text/plain' ``` `null` is returned in cases where an extension is not detected or recognized ```javascript mime.getType('foo/txt'); // ⇨ null mime.getType('bogus_type'); // ⇨ null ``` ### mime.getExtension(type) Get extension for the given mime type. Charset options (often included in Content-Type headers) are ignored. ```javascript mime.getExtension('text/plain'); // ⇨ 'txt' mime.getExtension('application/json'); // ⇨ 'json' mime.getExtension('text/html; charset=utf8'); // ⇨ 'html' ``` ### mime.define(typeMap[, force = false]) Define [more] type mappings. `typeMap` is a map of type -> extensions, as documented in `new Mime`, above. By default this method will throw an error if you try to map a type to an extension that is already assigned to another type. Passing `true` for the `force` argument will suppress this behavior (overriding any previous mapping). ```javascript mime.define({'text/x-abc': ['abc', 'abcd']}); mime.getType('abcd'); // ⇨ 'text/x-abc' mime.getExtension('text/x-abc') // ⇨ 'abc' ``` ## Command Line mime [path_or_extension] E.g. > mime scripts/jquery.js application/javascript ---- Markdown generated from [src/README_js.md](src/README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # has > Object.prototype.hasOwnProperty.call shortcut ## Installation ```sh npm install --save has ``` ## Usage ```js var has = require('has'); has({}, 'hasOwnProperty'); // false has(Object.prototype, 'hasOwnProperty'); // true ``` # serve-index [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Linux Build][travis-image]][travis-url] [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url] [![Gratipay][gratipay-image]][gratipay-url] Serves pages that contain directory listings for a given path. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install serve-index ``` ## API ```js var serveIndex = require('serve-index') ``` ### serveIndex(path, options) Returns middlware that serves an index of the directory in the given `path`. The `path` is based off the `req.url` value, so a `req.url` of `'/some/dir` with a `path` of `'public'` will look at `'public/some/dir'`. If you are using something like `express`, you can change the URL "base" with `app.use` (see the express example). #### Options Serve index accepts these properties in the options object. ##### filter Apply this filter function to files. Defaults to `false`. The `filter` function is called for each file, with the signature `filter(filename, index, files, dir)` where `filename` is the name of the file, `index` is the array index, `files` is the array of files and `dir` is the absolute path the file is located (and thus, the directory the listing is for). ##### hidden Display hidden (dot) files. Defaults to `false`. ##### icons Display icons. Defaults to `false`. ##### stylesheet Optional path to a CSS stylesheet. Defaults to a built-in stylesheet. ##### template Optional path to an HTML template or a function that will render a HTML string. Defaults to a built-in template. When given a string, the string is used as a file path to load and then the following tokens are replaced in templates: * `{directory}` with the name of the directory. * `{files}` with the HTML of an unordered list of file links. * `{linked-path}` with the HTML of a link to the directory. * `{style}` with the specified stylesheet and embedded images. When given as a function, the function is called as `template(locals, callback)` and it needs to invoke `callback(error, htmlString)`. The following are the provided locals: * `directory` is the directory being displayed (where `/` is the root). * `displayIcons` is a Boolean for if icons should be rendered or not. * `fileList` is a sorted array of files in the directory. The array contains objects with the following properties: - `name` is the relative name for the file. - `stat` is a `fs.Stats` object for the file. * `path` is the full filesystem path to `directory`. * `style` is the default stylesheet or the contents of the `stylesheet` option. * `viewName` is the view name provided by the `view` option. ##### view Display mode. `tiles` and `details` are available. Defaults to `tiles`. ## Examples ### Serve directory indexes with vanilla node.js http server ```js var finalhandler = require('finalhandler') var http = require('http') var serveIndex = require('serve-index') var serveStatic = require('serve-static') // Serve directory indexes for public/ftp folder (with icons) var index = serveIndex('public/ftp', {'icons': true}) // Serve up public/ftp folder files var serve = serveStatic('public/ftp') // Create server var server = http.createServer(function onRequest(req, res){ var done = finalhandler(req, res) serve(req, res, function onNext(err) { if (err) return done(err) index(req, res, done) }) }) // Listen server.listen(3000) ``` ### Serve directory indexes with express ```js var express = require('express') var serveIndex = require('serve-index') var app = express() // Serve URLs like /ftp/thing as public/ftp/thing // The express.static serves the file contents // The serveIndex is this module serving the directory app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', {'icons': true})) // Listen app.listen(3000) ``` ## License [MIT](LICENSE). The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons are created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/). [npm-image]: https://img.shields.io/npm/v/serve-index.svg [npm-url]: https://npmjs.org/package/serve-index [travis-image]: https://img.shields.io/travis/expressjs/serve-index/master.svg?label=linux [travis-url]: https://travis-ci.org/expressjs/serve-index [appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-index/master.svg?label=windows [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-index [coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-index/master.svg [coveralls-url]: https://coveralls.io/r/expressjs/serve-index?branch=master [downloads-image]: https://img.shields.io/npm/dm/serve-index.svg [downloads-url]: https://npmjs.org/package/serve-index [gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg [gratipay-url]: https://www.gratipay.com/dougwilson/ # hoist-non-react-statics [![NPM version](https://badge.fury.io/js/hoist-non-react-statics.svg)](http://badge.fury.io/js/hoist-non-react-statics) [![Build Status](https://img.shields.io/travis/mridgway/hoist-non-react-statics.svg)](https://travis-ci.org/mridgway/hoist-non-react-statics) [![Coverage Status](https://img.shields.io/coveralls/mridgway/hoist-non-react-statics.svg)](https://coveralls.io/r/mridgway/hoist-non-react-statics?branch=master) [![Dependency Status](https://img.shields.io/david/mridgway/hoist-non-react-statics.svg)](https://david-dm.org/mridgway/hoist-non-react-statics) [![devDependency Status](https://img.shields.io/david/dev/mridgway/hoist-non-react-statics.svg)](https://david-dm.org/mridgway/hoist-non-react-statics#info=devDependencies) Copies non-react specific statics from a child component to a parent component. Similar to `Object.assign`, but with React static keywords blacklisted from being overridden. ```bash $ npm install --save hoist-non-react-statics ``` ## Usage ```js import hoistNonReactStatics from 'hoist-non-react-statics'; hoistNonReactStatics(targetComponent, sourceComponent); ``` If you have specific statics that you don't want to be hoisted, you can also pass a third parameter to exclude them: ```js hoistNonReactStatics(targetComponent, sourceComponent, { myStatic: true, myOtherStatic: true }); ``` ## What does this module do? See this [explanation](https://facebook.github.io/react/docs/higher-order-components.html#static-methods-must-be-copied-over) from the React docs. ## Compatible React Versions Please use latest 3.x. Versions prior to 3.x will not support ForwardRefs. | hoist-non-react-statics Version | Compatible React Version | |--------------------------|-------------------------------| | 3.x | 0.13-16.x With ForwardRef Support | | 2.x | 0.13-16.x Without ForwardRef Support | | 1.x | 0.13-16.2 | ## Browser Support This package uses `Object.defineProperty` which has a broken implementation in IE8. In order to use this package in IE8, you will need a polyfill that fixes this method. ## License This software is free to use under the Yahoo Inc. BSD license. See the [LICENSE file][] for license text and copyright information. [LICENSE file]: https://github.com/mridgway/hoist-non-react-statics/blob/master/LICENSE.md Third-party open source code used are listed in our [package.json file]( https://github.com/mridgway/hoist-non-react-statics/blob/master/package.json). # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ [![npm][npm]][npm-url] [![node][node]][node-url] [![npm-stats][npm-stats]][npm-url] [![deps][deps]][deps-url] [![travis][travis]][travis-url] [![appveyor][appveyor]][appveyor-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] <div align="center"> <img height="100" src="https://worldvectorlogo.com/logos/sass-1.svg"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> <h1>Sass Loader</h1> <p>Loads a Sass/SCSS file and compiles it to CSS.</p> </div> Use the [css-loader](https://github.com/webpack-contrib/css-loader) or the [raw-loader](https://github.com/webpack-contrib/raw-loader) to turn it into a JS module and the [MiniCssExtractPlugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to extract it into a separate file. Looking for the webpack 1 loader? Check out the [archive/webpack-1 branch](https://github.com/webpack-contrib/sass-loader/tree/archive/webpack-1). <h2 align="center">Install</h2> ```bash npm install sass-loader node-sass webpack --save-dev ``` The sass-loader requires [webpack](https://github.com/webpack) as a [`peerDependency`](https://docs.npmjs.com/files/package.json#peerdependencies) and it requires you to install either [Node Sass][] or [Dart Sass][] on your own. This allows you to control the versions of all your dependencies, and to choose which Sass implementation to use. [Node Sass]: https://github.com/sass/node-sass [Dart Sass]: http://sass-lang.com/dart-sass <h2 align="center">Examples</h2> Chain the sass-loader with the [css-loader](https://github.com/webpack-contrib/css-loader) and the [style-loader](https://github.com/webpack-contrib/style-loader) to immediately apply all styles to the DOM. ```bash npm install style-loader css-loader --save-dev ``` ```js // webpack.config.js module.exports = { ... module: { rules: [{ test: /\.scss$/, use: [ "style-loader", // creates style nodes from JS strings "css-loader", // translates CSS into CommonJS "sass-loader" // compiles Sass to CSS, using Node Sass by default ] }] } }; ``` You can also pass options directly to [Node Sass][] or [Dart Sass][]: ```js // webpack.config.js module.exports = { ... module: { rules: [{ test: /\.scss$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader", options: { includePaths: ["absolute/path/a", "absolute/path/b"] } }] }] } }; ``` See [the Node Sass documentation](https://github.com/sass/node-sass/blob/master/README.md#options) for all available Sass options. The special `implementation` option determines which implementation of Sass to use. It takes either a [Node Sass][] or a [Dart Sass][] module. For example, to use Dart Sass, you'd pass: ```js // ... { loader: "sass-loader", options: { implementation: require("sass") } } // ... ``` Note that when using Dart Sass, **synchronous compilation is twice as fast as asynchronous compilation** by default, due to the overhead of asynchronous callbacks. To avoid this overhead, you can use the [`fibers`](https://www.npmjs.com/package/fibers) package to call asynchronous importers from the synchronous code path. To enable this, pass the `Fiber` class to the `fiber` option: ```js // webpack.config.js const Fiber = require('fibers'); module.exports = { ... module: { rules: [{ test: /\.scss$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader", options: { implementation: require("sass"), fiber: Fiber } }] }] } }; ``` ### In production Usually, it's recommended to extract the style sheets into a dedicated file in production using the [MiniCssExtractPlugin](https://github.com/webpack-contrib/mini-css-extract-plugin). This way your styles are not dependent on JavaScript: ```js const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { ... module: { rules: [{ test: /\.scss$/, use: [ // fallback to style-loader in development process.env.NODE_ENV !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader, "css-loader", "sass-loader" ] }] }, plugins: [ new MiniCssExtractPlugin({ // Options similar to the same options in webpackOptions.output // both options are optional filename: "[name].css", chunkFilename: "[id].css" }) ] }; ``` <h2 align="center">Usage</h2> ### Imports webpack provides an [advanced mechanism to resolve files](https://webpack.js.org/concepts/module-resolution/). The sass-loader uses Sass's custom importer feature to pass all queries to the webpack resolving engine. Thus you can import your Sass modules from `node_modules`. Just prepend them with a `~` to tell webpack that this is not a relative import: ```css @import "~bootstrap/dist/css/bootstrap"; ``` It's important to only prepend it with `~`, because `~/` resolves to the home directory. webpack needs to distinguish between `bootstrap` and `~bootstrap` because CSS and Sass files have no special syntax for importing relative files. Writing `@import "file"` is the same as `@import "./file";` ### Problems with `url(...)` Since Sass/[libsass](https://github.com/sass/libsass) does not provide [url rewriting](https://github.com/sass/libsass/issues/532), all linked assets must be relative to the output. - If you're just generating CSS without passing it to the css-loader, it must be relative to your web root. - If you pass the generated CSS on to the css-loader, all urls must be relative to the entry-file (e.g. `main.scss`). More likely you will be disrupted by this second issue. It is natural to expect relative references to be resolved against the `.scss` file in which they are specified (like in regular `.css` files). Thankfully there are a two solutions to this problem: - Add the missing url rewriting using the [resolve-url-loader](https://github.com/bholloway/resolve-url-loader). Place it before the sass-loader in the loader chain. - Library authors usually provide a variable to modify the asset path. [bootstrap-sass](https://github.com/twbs/bootstrap-sass) for example has an `$icon-font-path`. Check out [this working bootstrap example](https://github.com/webpack-contrib/sass-loader/tree/master/test/bootstrapSass). ### Extracting style sheets Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or [hot module replacement](https://webpack.js.org/concepts/hot-module-replacement/) in development. In production, on the other hand, it's not a good idea to apply your style sheets depending on JS execution. Rendering may be delayed or even a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content) might be visible. Thus it's often still better to have them as separate files in your final production build. There are two possibilities to extract a style sheet from the bundle: - [extract-loader](https://github.com/peerigon/extract-loader) (simpler, but specialized on the css-loader's output) - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) (more complex, but works in all use-cases) ### Source maps To enable CSS source maps, you'll need to pass the `sourceMap` option to the sass-loader *and* the css-loader. Your `webpack.config.js` should look like this: ```javascript module.exports = { ... devtool: "source-map", // any "source-map"-like devtool is possible module: { rules: [{ test: /\.scss$/, use: [{ loader: "style-loader" }, { loader: "css-loader", options: { sourceMap: true } }, { loader: "sass-loader", options: { sourceMap: true } }] }] } }; ``` If you want to edit the original Sass files inside Chrome, [there's a good blog post](https://medium.com/@toolmantim/getting-started-with-css-sourcemaps-and-in-browser-sass-editing-b4daab987fb0). Checkout [test/sourceMap](https://github.com/webpack-contrib/sass-loader/tree/master/test) for a running example. ### Environment variables If you want to prepend Sass code before the actual entry file, you can set the `data` option. In this case, the sass-loader will not override the `data` option but just append the entry's content. This is especially useful when some of your Sass variables depend on the environment: ```javascript { loader: "sass-loader", options: { data: "$env: " + process.env.NODE_ENV + ";" } } ``` **Please note:** Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Sass entry files. <h2 align="center">Maintainers</h2> <table> <tr> <td align="center"> <a href="https://github.com/jhnns"><img width="150" height="150" src="https://avatars0.githubusercontent.com/u/781746?v=3"></a><br> <a href="https://github.com/jhnns">Johannes Ewald</a> </td> <td align="center"> <a href="https://github.com/webpack-contrib"><img width="150" height="150" src="https://avatars1.githubusercontent.com/u/1243901?v=3&s=460"></a><br> <a href="https://github.com/webpack-contrib">Jorik Tangelder</a> </td> <td align="center"> <a href="https://github.com/akiran"><img width="150" height="150" src="https://avatars1.githubusercontent.com/u/3403295?v=3"></a><br> <a href="https://github.com/akiran">Kiran</a> </td> <tr> </table> <h2 align="center">License</h2> [MIT](http://www.opensource.org/licenses/mit-license.php) [npm]: https://img.shields.io/npm/v/sass-loader.svg [npm-stats]: https://img.shields.io/npm/dm/sass-loader.svg [npm-url]: https://npmjs.com/package/sass-loader [node]: https://img.shields.io/node/v/sass-loader.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack-contrib/sass-loader.svg [deps-url]: https://david-dm.org/webpack-contrib/sass-loader [travis]: http://img.shields.io/travis/webpack-contrib/sass-loader.svg [travis-url]: https://travis-ci.org/webpack-contrib/sass-loader [appveyor-url]: https://ci.appveyor.com/project/webpack-contrib/sass-loader/branch/master [appveyor]: https://ci.appveyor.com/api/projects/status/rqpy1vaovh20ttxs/branch/master?svg=true [cover]: https://codecov.io/gh/webpack-contrib/sass-loader/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/sass-loader [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack # URI.js URI.js is an [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt) compliant, scheme extendable URI parsing/validating/resolving library for all JavaScript environments (browsers, Node.js, etc). It is also compliant with the IRI ([RFC 3987](http://www.ietf.org/rfc/rfc3987.txt)), IDNA ([RFC 5890](http://www.ietf.org/rfc/rfc5890.txt)), IPv6 Address ([RFC 5952](http://www.ietf.org/rfc/rfc5952.txt)), IPv6 Zone Identifier ([RFC 6874](http://www.ietf.org/rfc/rfc6874.txt)) specifications. URI.js has an extensive test suite, and works in all (Node.js, web) environments. It weighs in at 6.2kb (gzipped, 16kb deflated). ## API ### Parsing URI.parse("uri://user:[email protected]:123/one/two.three?q1=a1&q2=a2#body"); //returns: //{ // scheme : "uri", // userinfo : "user:pass", // host : "example.com", // port : 123, // path : "/one/two.three", // query : "q1=a1&q2=a2", // fragment : "body" //} ### Serializing URI.serialize({scheme : "http", host : "example.com", fragment : "footer"}) === "http://example.com/#footer" ### Resolving URI.resolve("uri://a/b/c/d?q", "../../g") === "uri://a/g" ### Normalizing URI.normalize("HTTP://ABC.com:80/%7Esmith/home.html") === "http://abc.com/~smith/home.html" ### Comparison URI.equal("example://a/b/c/%7Bfoo%7D", "eXAMPLE://a/./b/../b/%63/%7bfoo%7d") === true ### IP Support //IPv4 normalization URI.normalize("//192.068.001.000") === "//192.68.1.0" //IPv6 normalization URI.normalize("//[2001:0:0DB8::0:0001]") === "//[2001:0:db8::1]" //IPv6 zone identifier support URI.parse("//[2001:db8::7%25en1]"); //returns: //{ // host : "2001:db8::7%en1" //} ### IRI Support //convert IRI to URI URI.serialize(URI.parse("http://examplé.org/rosé")) === "http://xn--exampl-gva.org/ros%C3%A9" //convert URI to IRI URI.serialize(URI.parse("http://xn--exampl-gva.org/ros%C3%A9"), {iri:true}) === "http://examplé.org/rosé" ### Options All of the above functions can accept an additional options argument that is an object that can contain one or more of the following properties: * `scheme` (string) Indicates the scheme that the URI should be treated as, overriding the URI's normal scheme parsing behavior. * `reference` (string) If set to `"suffix"`, it indicates that the URI is in the suffix format, and the validator will use the option's `scheme` property to determine the URI's scheme. * `tolerant` (boolean, false) If set to `true`, the parser will relax URI resolving rules. * `absolutePath` (boolean, false) If set to `true`, the serializer will not resolve a relative `path` component. * `iri` (boolean, false) If set to `true`, the serializer will unescape non-ASCII characters as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `unicodeSupport` (boolean, false) If set to `true`, the parser will unescape non-ASCII characters in the parsed output as per [RFC 3987](http://www.ietf.org/rfc/rfc3987.txt). * `domainHost` (boolean, false) If set to `true`, the library will treat the `host` component as a domain name, and convert IDNs (International Domain Names) as per [RFC 5891](http://www.ietf.org/rfc/rfc5891.txt). ## Scheme Extendable URI.js supports inserting custom [scheme](http://en.wikipedia.org/wiki/URI_scheme) dependent processing rules. Currently, URI.js has built in support for the following schemes: * http \[[RFC 2616](http://www.ietf.org/rfc/rfc2616.txt)\] * https \[[RFC 2818](http://www.ietf.org/rfc/rfc2818.txt)\] * mailto \[[RFC 6068](http://www.ietf.org/rfc/rfc6068.txt)\] * urn \[[RFC 2141](http://www.ietf.org/rfc/rfc2141.txt)\] * urn:uuid \[[RFC 4122](http://www.ietf.org/rfc/rfc4122.txt)\] ### HTTP Support URI.equal("HTTP://ABC.COM:80", "http://abc.com/") === true ### Mailto Support URI.parse("mailto:[email protected],[email protected]?subject=SUBSCRIBE&body=Sign%20me%20up!"); //returns: //{ // scheme : "mailto", // to : ["[email protected]", "[email protected]"], // subject : "SUBSCRIBE", // body : "Sign me up!" //} URI.serialize({ scheme : "mailto", to : ["[email protected]"], subject : "REMOVE", body : "Please remove me", headers : { cc : "[email protected]" } }) === "mailto:[email protected][email protected]&subject=REMOVE&body=Please%20remove%20me" ### URN Support URI.parse("urn:example:foo"); //returns: //{ // scheme : "urn", // nid : "example", // nss : "foo", //} #### URN UUID Support URI.parse("urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); //returns: //{ // scheme : "urn", // nid : "example", // uuid : "f81d4fae-7dec-11d0-a765-00a0c91e6bf6", //} ## Usage To load in a browser, use the following tag: <script type="text/javascript" src="uri-js/dist/es5/uri.all.min.js"></script> To load in a CommonJS (Node.js) environment, first install with npm by running on the command line: npm install uri-js Then, in your code, load it using: const URI = require("uri-js"); If you are writing your code in ES6+ (ESNEXT) or TypeScript, you would load it using: import * as URI from "uri-js"; Or you can load just what you need using named exports: import { parse, serialize, resolve, resolveComponents, normalize, equal, removeDotSegments, pctEncChar, pctDecChars, escapeComponent, unescapeComponent } from "uri-js"; ## Breaking changes ### Breaking changes from 3.x URN parsing has been completely changed to better align with the specification. Scheme is now always `urn`, but has two new properties: `nid` which contains the Namspace Identifier, and `nss` which contains the Namespace Specific String. The `nss` property will be removed by higher order scheme handlers, such as the UUID URN scheme handler. The UUID of a URN can now be found in the `uuid` property. ### Breaking changes from 2.x URI validation has been removed as it was slow, exposed a vulnerabilty, and was generally not useful. ### Breaking changes from 1.x The `errors` array on parsed components is now an `error` string. ## License ([Simplified BSD](http://en.wikipedia.org/wiki/BSD_licenses#2-clause)) Copyright 2011 Gary Court. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY GARY COURT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Gary Court. This folder contains implementations of polyfills. It's not recommended to include in your projects directly if you don't completely understand what are you doing. # `react-dom` This package serves as the entry point to the DOM and server renderers for React. It is intended to be paired with the generic React package, which is shipped as `react` to npm. ## Installation ```sh npm install react react-dom ``` ## Usage ### In the browser ```js var React = require('react'); var ReactDOM = require('react-dom'); class MyComponent extends React.Component { render() { return <div>Hello World</div>; } } ReactDOM.render(<MyComponent />, node); ``` ### On the server ```js var React = require('react'); var ReactDOMServer = require('react-dom/server'); class MyComponent extends React.Component { render() { return <div>Hello World</div>; } } ReactDOMServer.renderToString(<MyComponent />); ``` ## API ### `react-dom` - `findDOMNode` - `render` - `unmountComponentAtNode` ### `react-dom/server` - `renderToString` - `renderToStaticMarkup` # Node.js releases data All data is located in `data` directory. `data/raw` contains raw data `nodejs.json` and `iojs.json`. `data/processed` contains `envs.js` with both node.js and io.js data preprocessed to be used by [browserlist](https://github.com/ai/browserslist) and other projects. Each version in this file contains only necessary info: version, release date and optionally LTS flag. ## Installation ```bash npm install --save node-releases ``` ## Updating data ```bash npm run build ``` This is a build script which fetches data from web, processes it and saves processed data to `data/processed/envs.json`. If you want to run this steps separately you can use commands described below. ### Fetching data ```bash npm run fetch ``` This npm script will download new data to `data/raw` directory. Also it'll download Node.js release schedule into `release-schedule` folder. ### Processing data ```bash npm run process ``` This script generates `envs.json` file from raw data files and saves it to `data/processed` directory. # range-parser [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Range header field parser. ## Installation ``` $ npm install range-parser ``` ## API ```js var parseRange = require('range-parser') ``` ### parseRange(size, header, options) Parse the given `header` string where `size` is the maximum size of the resource. An array of ranges will be returned or negative numbers indicating an error parsing. * `-2` signals a malformed header string * `-1` signals an unsatisfiable range ```js // parse header from request var range = parseRange(size, req.headers.range) // the type of the range if (range.type === 'bytes') { // the ranges range.forEach(function (r) { // do something with r.start and r.end }) } ``` #### Options These properties are accepted in the options object. ##### combine Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. When `true`, ranges will be combined and returned as if they were specified that way in the header. ```js parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) // => [ // { start: 0, end: 10 }, // { start: 50, end: 60 } // ] ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/range-parser.svg [npm-url]: https://npmjs.org/package/range-parser [node-version-image]: https://img.shields.io/node/v/range-parser.svg [node-version-url]: https://nodejs.org/endownload [travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg [travis-url]: https://travis-ci.org/jshttp/range-parser [coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg [coveralls-url]: https://coveralls.io/r/jshttp/range-parser [downloads-image]: https://img.shields.io/npm/dm/range-parser.svg [downloads-url]: https://npmjs.org/package/range-parser # extend-shallow [![NPM version](https://img.shields.io/npm/v/extend-shallow.svg?style=flat)](https://www.npmjs.com/package/extend-shallow) [![NPM monthly downloads](https://img.shields.io/npm/dm/extend-shallow.svg?style=flat)](https://npmjs.org/package/extend-shallow) [![NPM total downloads](https://img.shields.io/npm/dt/extend-shallow.svg?style=flat)](https://npmjs.org/package/extend-shallow) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/extend-shallow.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save extend-shallow ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [for-in](https://www.npmjs.com/package/for-in): Iterate over the own and inherited enumerable properties of an object, and return an object… [more](https://github.com/jonschlinkert/for-in) | [homepage](https://github.com/jonschlinkert/for-in "Iterate over the own and inherited enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js") * [for-own](https://www.npmjs.com/package/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) | [homepage](https://github.com/jonschlinkert/for-own "Iterate over the own enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 33 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [pdehaan](https://github.com/pdehaan) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 19, 2017._ # v8-compile-cache [![Build Status](https://travis-ci.org/zertosh/v8-compile-cache.svg?branch=master)](https://travis-ci.org/zertosh/v8-compile-cache) `v8-compile-cache` attaches a `require` hook to use [V8's code cache](https://v8project.blogspot.com/2015/07/code-caching.html) to speed up instantiation time. The "code cache" is the work of parsing and compiling done by V8. The ability to tap into V8 to produce/consume this cache was introduced in [Node v5.7.0](https://nodejs.org/en/blog/release/v5.7.0/). ## Usage 1. Add the dependency: ```sh $ npm install --save v8-compile-cache ``` 2. Then, in your entry module add: ```js require('v8-compile-cache'); ``` **Requiring `v8-compile-cache` in Node <5.7.0 is a noop – but you need at least Node 4.0.0 to support the ES2015 syntax used by `v8-compile-cache`.** ## Options Set the environment variable `DISABLE_V8_COMPILE_CACHE=1` to disable the cache. ## Internals The caches are stored in `$TMP/v8-compile-cache/V8_VERSION`, where there are `.BLOB` and `.MAP` files corresponding to the entry module that required `v8-compile-cache`. The cache is _entry module specific_ because it is faster to load the entire code cache into memory at once, than it is to read it from disk on a file-by-file basis. ## Benchmarks See https://github.com/zertosh/v8-compile-cache/tree/master/bench. **Load Times:** | Module | Without Cache | With Cache | | ---------------- | -------------:| ----------:| | `babel-core` | `218ms` | `185ms` | | `yarn` | `153ms` | `113ms` | | `yarn` (bundled) | `228ms` | `105ms` | _^ Includes the overhead of loading the cache itself._ ## Acknowledgements * `FileSystemBlobStore` and `NativeCompileCache` are based on Atom's implementation of their v8 compile cache: - https://github.com/atom/atom/blob/b0d7a8a/src/file-system-blob-store.js - https://github.com/atom/atom/blob/b0d7a8a/src/native-compile-cache.js * `mkdirpSync` is based on: - https://github.com/substack/node-mkdirp/blob/f2003bb/index.js#L55-L98 # Regenerate [![Build status](https://travis-ci.org/mathiasbynens/regenerate.svg?branch=master)](https://travis-ci.org/mathiasbynens/regenerate) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/regenerate.svg)](https://codecov.io/gh/mathiasbynens/regenerate) [![Dependency status](https://gemnasium.com/mathiasbynens/regenerate.svg)](https://gemnasium.com/mathiasbynens/regenerate) _Regenerate_ is a Unicode-aware regex generator for JavaScript. It allows you to easily generate ES5-compatible regular expressions based on a given set of Unicode symbols or code points. (This is trickier than you might think, because of [how JavaScript deals with astral symbols](https://mathiasbynens.be/notes/javascript-unicode).) ## Installation Via [npm](https://npmjs.org/): ```bash npm install regenerate ``` Via [Bower](http://bower.io/): ```bash bower install regenerate ``` Via [Component](https://github.com/component/component): ```bash component install mathiasbynens/regenerate ``` In a browser: ```html <script src="regenerate.js"></script> ``` In [Node.js](https://nodejs.org/), [io.js](https://iojs.org/), and [RingoJS ≥ v0.8.0](http://ringojs.org/): ```js var regenerate = require('regenerate'); ``` In [Narwhal](http://narwhaljs.org/) and [RingoJS ≤ v0.7.0](http://ringojs.org/): ```js var regenerate = require('regenerate').regenerate; ``` In [Rhino](http://www.mozilla.org/rhino/): ```js load('regenerate.js'); ``` Using an AMD loader like [RequireJS](http://requirejs.org/): ```js require( { 'paths': { 'regenerate': 'path/to/regenerate' } }, ['regenerate'], function(regenerate) { console.log(regenerate); } ); ``` ## API ### `regenerate(value1, value2, value3, ...)` The main Regenerate function. Calling this function creates a new set that gets a chainable API. ```js var set = regenerate() .addRange(0x60, 0x69) // add U+0060 to U+0069 .remove(0x62, 0x64) // remove U+0062 and U+0064 .add(0x1D306); // add U+1D306 set.valueOf(); // → [0x60, 0x61, 0x63, 0x65, 0x66, 0x67, 0x68, 0x69, 0x1D306] set.toString(); // → '[`ace-i]|\\uD834\\uDF06' set.toRegExp(); // → /[`ace-i]|\uD834\uDF06/ ``` Any arguments passed to `regenerate()` will be added to the set right away. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted, as well as arrays containing values of these types. ```js regenerate(0x1D306, 'A', '©', 0x2603).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' var items = [0x1D306, 'A', '©', 0x2603]; regenerate(items).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' ``` ### `regenerate.prototype.add(value1, value2, value3, ...)` Any arguments passed to `add()` are added to the set. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted, as well as arrays containing values of these types. ```js regenerate().add(0x1D306, 'A', '©', 0x2603).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' var items = [0x1D306, 'A', '©', 0x2603]; regenerate().add(items).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' ``` It’s also possible to pass in a Regenerate instance. Doing so adds all code points in that instance to the current set. ```js var set = regenerate(0x1D306, 'A'); regenerate().add('©', 0x2603).add(set).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' ``` Note that the initial call to `regenerate()` acts like `add()`. This allows you to create a new Regenerate instance and add some code points to it in one go: ```js regenerate(0x1D306, 'A', '©', 0x2603).toString(); // → '[A\\xA9\\u2603]|\\uD834\\uDF06' ``` ### `regenerate.prototype.remove(value1, value2, value3, ...)` Any arguments passed to `remove()` are removed to the set. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted, as well as arrays containing values of these types. ```js regenerate(0x1D306, 'A', '©', 0x2603).remove('☃').toString(); // → '[A\\xA9]|\\uD834\\uDF06' ``` It’s also possible to pass in a Regenerate instance. Doing so removes all code points in that instance from the current set. ```js var set = regenerate('☃'); regenerate(0x1D306, 'A', '©', 0x2603).remove(set).toString(); // → '[A\\xA9]|\\uD834\\uDF06' ``` ### `regenerate.prototype.addRange(start, end)` Adds a range of code points from `start` to `end` (inclusive) to the set. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted. ```js regenerate(0x1D306).addRange(0x00, 0xFF).toString(16); // → '[\\0-\\xFF]|\\uD834\\uDF06' regenerate().addRange('A', 'z').toString(); // → '[A-z]' ``` ### `regenerate.prototype.removeRange(start, end)` Removes a range of code points from `start` to `end` (inclusive) from the set. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted. ```js regenerate() .addRange(0x000000, 0x10FFFF) // add all Unicode code points .removeRange('A', 'z') // remove all symbols from `A` to `z` .toString(); // → '[\\0-@\\{-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]' regenerate() .addRange(0x000000, 0x10FFFF) // add all Unicode code points .removeRange(0x0041, 0x007A) // remove all code points from U+0041 to U+007A .toString(); // → '[\\0-@\\{-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]' ``` ### `regenerate.prototype.intersection(codePoints)` Removes any code points from the set that are not present in both the set and the given `codePoints` array. `codePoints` must be an array of numeric code point values, i.e. numbers. ```js regenerate() .addRange(0x00, 0xFF) // add extended ASCII code points .intersection([0x61, 0x69]) // remove all code points from the set except for these .toString(); // → '[ai]' ``` Instead of the `codePoints` array, it’s also possible to pass in a Regenerate instance. ```js var whitelist = regenerate(0x61, 0x69); regenerate() .addRange(0x00, 0xFF) // add extended ASCII code points .intersection(whitelist) // remove all code points from the set except for those in the `whitelist` set .toString(); // → '[ai]' ``` ### `regenerate.prototype.contains(value)` Returns `true` if the given value is part of the set, and `false` otherwise. Both code points (numbers) and symbols (strings consisting of a single Unicode symbol) are accepted. ```js var set = regenerate().addRange(0x00, 0xFF); set.contains('A'); // → true set.contains(0x1D306); // → false ``` ### `regenerate.prototype.clone()` Returns a clone of the current code point set. Any actions performed on the clone won’t mutate the original set. ```js var setA = regenerate(0x1D306); var setB = setA.clone().add(0x1F4A9); setA.toArray(); // → [0x1D306] setB.toArray(); // → [0x1D306, 0x1F4A9] ``` ### `regenerate.prototype.toString(options)` Returns a string representing (part of) a regular expression that matches all the symbols mapped to the code points within the set. ```js regenerate(0x1D306, 0x1F4A9).toString(); // → '\\uD834\\uDF06|\\uD83D\\uDCA9' ``` If the `bmpOnly` property of the optional `options` object is set to `true`, the output matches surrogates individually, regardless of whether they’re lone surrogates or just part of a surrogate pair. This simplifies the output, but it can only be used in case you’re certain the strings it will be used on don’t contain any astral symbols. ```js var highSurrogates = regenerate().addRange(0xD800, 0xDBFF); highSurrogates.toString(); // → '[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])' highSurrogates.toString({ 'bmpOnly': true }); // → '[\\uD800-\\uDBFF]' var lowSurrogates = regenerate().addRange(0xDC00, 0xDFFF); lowSurrogates.toString(); // → '(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]' lowSurrogates.toString({ 'bmpOnly': true }); // → '[\\uDC00-\\uDFFF]' ``` Note that lone low surrogates cannot be matched accurately using regular expressions in JavaScript. Regenerate’s output makes a best-effort approach but [there can be false negatives in this regard](https://github.com/mathiasbynens/regenerate/issues/28#issuecomment-72224808). If the `hasUnicodeFlag` property of the optional `options` object is set to `true`, the output makes use of Unicode code point escapes (`\u{…}`) where applicable. This simplifies the output at the cost of compatibility and portability, since it means the output can only be used as a pattern in a regular expression with [the ES6 `u` flag](https://mathiasbynens.be/notes/es6-unicode-regex) enabled. ```js var set = regenerate().addRange(0x0, 0x10FFFF); set.toString(); // → '[\\0-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]'' set.toString({ 'hasUnicodeFlag': true }); // → '[\\0-\\u{10FFFF}]' ``` ### `regenerate.prototype.toRegExp(flags = '')` Returns a regular expression that matches all the symbols mapped to the code points within the set. Optionally, you can pass [flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#Parameters) to be added to the regular expression. ```js var regex = regenerate(0x1D306, 0x1F4A9).toRegExp(); // → /\uD834\uDF06|\uD83D\uDCA9/ regex.test('𝌆'); // → true regex.test('A'); // → false // With flags: var regex = regenerate(0x1D306, 0x1F4A9).toRegExp('g'); // → /\uD834\uDF06|\uD83D\uDCA9/g ``` **Note:** This probably shouldn’t be used. Regenerate is intended as a tool that is used as part of a build process, not at runtime. ### `regenerate.prototype.valueOf()` or `regenerate.prototype.toArray()` Returns a sorted array of unique code points in the set. ```js regenerate(0x1D306) .addRange(0x60, 0x65) .add(0x59, 0x60) // note: 0x59 is added after 0x65, and 0x60 is a duplicate .valueOf(); // → [0x59, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x1D306] ``` ### `regenerate.version` A string representing the semantic version number. ## Combine Regenerate with other libraries Regenerate gets even better when combined with other libraries such as [Punycode.js](https://mths.be/punycode). Here’s an example where [Punycode.js](https://mths.be/punycode) is used to convert a string into an array of code points, that is then passed on to Regenerate: ```js var regenerate = require('regenerate'); var punycode = require('punycode'); var string = 'Lorem ipsum dolor sit amet.'; // Get an array of all code points used in the string: var codePoints = punycode.ucs2.decode(string); // Generate a regular expression that matches any of the symbols used in the string: regenerate(codePoints).toString(); // → '[ \\.Ladeilmopr-u]' ``` In ES6 you can do something similar with [`Array.from`](https://mths.be/array-from) which uses [the string’s iterator](https://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols) to split the given string into an array of strings that each contain a single symbol. [`regenerate()`](#regenerateprototypeaddvalue1-value2-value3-) accepts both strings and code points, remember? ```js var regenerate = require('regenerate'); var string = 'Lorem ipsum dolor sit amet.'; // Get an array of all symbols used in the string: var symbols = Array.from(string); // Generate a regular expression that matches any of the symbols used in the string: regenerate(symbols).toString(); // → '[ \\.Ladeilmopr-u]' ``` ## Support Regenerate supports at least Chrome 27+, Firefox 3+, Safari 4+, Opera 10+, IE 6+, Node.js v0.10.0+, io.js v1.0.0+, Narwhal 0.3.2+, RingoJS 0.8+, PhantomJS 1.9.0+, and Rhino 1.7RC4+. ## Unit tests & code coverage After cloning this repository, run `npm install` to install the dependencies needed for Regenerate development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, and web browsers as well, use `grunt test`. To generate the code coverage report, use `grunt cover`. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Regenerate is available under the [MIT](https://mths.be/mit) license. # color-convert [![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) Color-convert is a color conversion library for JavaScript and node. It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): ```js var convert = require('color-convert'); convert.rgb.hsl(140, 200, 100); // [96, 48, 59] convert.keyword.rgb('blue'); // [0, 0, 255] var rgbChannels = convert.rgb.channels; // 3 var cmykChannels = convert.cmyk.channels; // 4 var ansiChannels = convert.ansi16.channels; // 1 ``` # Install ```console $ npm install color-convert ``` # API Simply get the property of the _from_ and _to_ conversion that you're looking for. All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). ```js var convert = require('color-convert'); // Hex to LAB convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] // RGB to CMYK convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] ``` ### Arrays All functions that accept multiple arguments also support passing an array. Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) ```js var convert = require('color-convert'); convert.rgb.hex(123, 45, 67); // '7B2D43' convert.rgb.hex([123, 45, 67]); // '7B2D43' ``` ## Routing Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). # Contribute If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. # License Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). # min-document [![build status][1]][2] [![dependency status][3]][4] <!-- [![browser support][5]][6] --> A minimal DOM implementation ## Example ```js var document = require("min-document") var div = document.createElement("div") div.className = "foo bar" var span = document.createElement("span") div.appendChild(span) span.textContent = "Hello!" /* <div class="foo bar"> <span>Hello!</span> </div> */ var html = String(div) ``` ## Installation `npm install min-document` ## Contributors - Raynos ## MIT Licenced [1]: https://secure.travis-ci.org/Raynos/min-document.png [2]: https://travis-ci.org/Raynos/min-document [3]: https://david-dm.org/Raynos/min-document.png [4]: https://david-dm.org/Raynos/min-document [5]: https://ci.testling.com/Raynos/min-document.png [6]: https://ci.testling.com/Raynos/min-document # normalize-path [![NPM version](https://img.shields.io/npm/v/normalize-path.svg?style=flat)](https://www.npmjs.com/package/normalize-path) [![NPM monthly downloads](https://img.shields.io/npm/dm/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![NPM total downloads](https://img.shields.io/npm/dt/normalize-path.svg?style=flat)](https://npmjs.org/package/normalize-path) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/normalize-path.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/normalize-path) > Normalize slashes in a file path to be posix/unix-like forward slashes. Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save normalize-path ``` ## Usage ```js const normalize = require('normalize-path'); console.log(normalize('\\foo\\bar\\baz\\')); //=> '/foo/bar/baz' ``` **win32 namespaces** ```js console.log(normalize('\\\\?\\UNC\\Server01\\user\\docs\\Letter.txt')); //=> '//?/UNC/Server01/user/docs/Letter.txt' console.log(normalize('\\\\.\\CdRomX')); //=> '//./CdRomX' ``` **Consecutive slashes** Condenses multiple consecutive forward slashes (except for leading slashes in win32 namespaces) to a single slash. ```js console.log(normalize('.//foo//bar///////baz/')); //=> './foo/bar/baz' ``` ### Trailing slashes By default trailing slashes are removed. Pass `false` as the last argument to disable this behavior and _**keep** trailing slashes_: ```js console.log(normalize('foo\\bar\\baz\\', false)); //=> 'foo/bar/baz/' console.log(normalize('./foo/bar/baz/', false)); //=> './foo/bar/baz/' ``` ## Release history ### v3.0 No breaking changes in this release. * a check was added to ensure that [win32 namespaces](https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces) are handled properly by win32 `path.parse()` after a path has been normalized by this library. * a minor optimization was made to simplify how the trailing separator was handled ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects Other useful path-related libraries: * [contains-path](https://www.npmjs.com/package/contains-path): Return true if a file path contains the given path. | [homepage](https://github.com/jonschlinkert/contains-path "Return true if a file path contains the given path.") * [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.") * [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.") * [parse-filepath](https://www.npmjs.com/package/parse-filepath): Pollyfill for node.js `path.parse`, parses a filepath into an object. | [homepage](https://github.com/jonschlinkert/parse-filepath "Pollyfill for node.js `path.parse`, parses a filepath into an object.") * [path-ends-with](https://www.npmjs.com/package/path-ends-with): Return `true` if a file path ends with the given string/suffix. | [homepage](https://github.com/jonschlinkert/path-ends-with "Return `true` if a file path ends with the given string/suffix.") * [unixify](https://www.npmjs.com/package/unixify): Convert Windows file paths to unix paths. | [homepage](https://github.com/jonschlinkert/unixify "Convert Windows file paths to unix paths.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 35 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [phated](https://github.com/phated) | ### Author **Jon Schlinkert** * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on April 19, 2018._ # source-list-map ## API ### Example ``` js var SourceListMap = require("source-list-map").SourceListMap; // Create a new map var map = new SourceListMap(); // Add generated code that is map line to line to some soure map.add("Generated\ncode1\n", "source-code.js", "Orginal\nsource"); // Add generated code that isn't mapped map.add("Generated\ncode2\n"); // Get SourceMap and generated source map.toStringWithSourceMap({ file: "generated-code.js" }); // { // source: 'Generated\ncode1\nGenerated\ncode2\n', // map: { // version: 3, // file: 'generated-code.js', // sources: [ 'source-code.js' ], // sourcesContent: [ 'Orginal\nsource' ], // mappings: 'AAAA;AACA;;;' // } // } // Convert existing SourceMap into SourceListMap // (Only the first mapping per line is preserved) var fromStringWithSourceMap = require("source-list-map").fromStringWithSourceMap; var map = fromStringWithSourceMap("Generated\ncode", { version: 3, ... }); ``` ### `new SourceListMap()` ### `SourceListMap.prototype.add` ``` js SourceListMap.prototype.add(generatedCode: string) SourceListMap.prototype.add(generatedCode: string, source: string, originalSource: string) SourceListMap.prototype.add(sourceListMap: SourceListMap) ``` Append some stuff. ### `SourceListMap.prototype.prepend` ``` js SourceListMap.prototype.prepend(generatedCode: string) SourceListMap.prototype.prepend(generatedCode: string, source: string, originalSource: string) SourceListMap.prototype.prepend(sourceListMap: SourceListMap) ``` Prepend some stuff. ### `SourceListMap.prototype.toString()` Get generated code. ### `SourceListMap.prototype.toStringWithSourceMap` ``` js SourceListMap.prototype.toStringWithSourceMap(options: object) ``` Get generated code and SourceMap. `options` can contains `file` property which defines the `file` property of the SourceMap. ### `SourceListMap.prototype.mapGeneratedCode` ``` js SourceListMap.prototype.mapGeneratedCode(fn: function) : SourceListMap ``` Applies `fn` to each generated code block (per line). The returned value is set as new generated code. Returns a new SourceListMap. Removing and adding lines is supported. The SourceMap complexity will increase when doing this. ## Test [![Build Status](https://travis-ci.org/webpack/source-list-map.svg)](https://travis-ci.org/webpack/source-list-map) ## License Copyright (c) 2017 JS Foundation MIT (http://www.opensource.org/licenses/mit-license.php) in-publish ========== Detect if we were run as a result of `npm publish`. This is intended to allow you to easily have prepublish lifecycle scripts that don't run when you run `npm install`. ``` $ npm install --save in-publish [email protected] node_modules/in-publish ``` Then edit your package.json to have: ```json "scripts": { "prepublish": "in-publish && thing-I-dont-want-on-dev-install || not-in-publish" } ``` Now when you run: ``` $ npm install ``` Then `thing-I-dont-want-on-dev-install` won't be run, but... ``` $ npm publish ``` And `thing-I-dont-want-on-dev-install` will be run. It's worth noting that the `prepublish` lifecycle is _ALSO_ called when you build a tarball, so: ``` $ npm pack ``` Will call your `prepublish` lifecycle, but with the examplea above, `thing-I-dont-want-on-dev-install` won't be run. If you want this, you can use another helper included here: ```json "scripts": { "prepublish": "not-in-install && thing-I-dont-want-on-dev-install || in-install" } ``` The above will run your `thing-I-dont-want-on-dev-install` on `publish` and on `pack` but not on `install`. # on-headers [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Execute a listener when a response is about to write headers. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install on-headers ``` ## API <!-- eslint-disable no-unused-vars --> ```js var onHeaders = require('on-headers') ``` ### onHeaders(res, listener) This will add the listener `listener` to fire when headers are emitted for `res`. The listener is passed the `response` object as it's context (`this`). Headers are considered to be emitted only once, right before they are sent to the client. When this is called multiple times on the same `res`, the `listener`s are fired in the reverse order they were added. ## Examples ```js var http = require('http') var onHeaders = require('on-headers') http .createServer(onRequest) .listen(3000) function addPoweredBy () { // set if not set by end of request if (!this.getHeader('X-Powered-By')) { this.setHeader('X-Powered-By', 'Node.js') } } function onRequest (req, res) { onHeaders(res, addPoweredBy) res.setHeader('Content-Type', 'text/plain') res.end('hello!') } ``` ## Testing ```sh $ npm test ``` ## License [MIT](LICENSE) [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/on-headers/master [coveralls-url]: https://coveralls.io/r/jshttp/on-headers?branch=master [node-version-image]: https://badgen.net/npm/node/on-headers [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/on-headers [npm-url]: https://npmjs.org/package/on-headers [npm-version-image]: https://badgen.net/npm/v/on-headers [travis-image]: https://badgen.net/travis/jshttp/on-headers/master [travis-url]: https://travis-ci.org/jshttp/on-headers # Source Map This is a library to generate and consume the source map format [described here][format]. This library is written in the Asynchronous Module Definition format, and works in the following environments: * Modern Browsers supporting ECMAScript 5 (either after the build, or with an AMD loader such as RequireJS) * Inside Firefox (as a JSM file, after the build) * With NodeJS versions 0.8.X and higher ## Node $ npm install source-map ## Building from Source (for everywhere else) Install Node and then run $ git clone https://[email protected]/mozilla/source-map.git $ cd source-map $ npm link . Next, run $ node Makefile.dryice.js This should spew a bunch of stuff to stdout, and create the following files: * `dist/source-map.js` - The unminified browser version. * `dist/source-map.min.js` - The minified browser version. * `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source. ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // NodeJS var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox let sourceMap = {}; Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referrenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. * `column`: The column number in the generated source. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. * `column`: The column number in the original source, or null or null if this information is not available. * `name`: The original identifier, or null if this information is not available. #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. * `column`: The column number in the original source. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. * `column`: The column number in the generated source, or null. #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. * `column`: Optional. The column number in the original source. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. * `column`: The column number in the generated source, or null. #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `smc.sourceContentFor(s)` will succeed for every source `s` in `smc.sources`. #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new SourceMapGenerator based on a SourceMapConsumer * `sourceMapConsumer` The SourceMap. #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimium of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming whitespace from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ## Tests [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`. To add new tests, create a new file named `test/test-<your new test name>.js` and export your test functions with names that start with "test", for example ```js exports["test doing the foo bar"] = function (assert, util) { ... }; ``` The new test will be located automatically when you run the suite. The `util` argument is the test utility module located at `test/source-map/util`. The `assert` argument is a cut down version of node's assert module. You have access to the following assertion functions: * `doesNotThrow` * `equal` * `ok` * `strictEqual` * `throws` (The reason for the restricted set of test functions is because we need the tests to run inside Firefox's test suite as well and so the assert module is shimmed in that environment. See `build/assert-shim.js`.) [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit [feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap [Dryice]: https://github.com/mozilla/dryice # `react` React is a JavaScript library for creating user interfaces. The `react` package contains only the functionality necessary to define React components. It is typically used together with a React renderer like `react-dom` for the web, or `react-native` for the native environments. **Note:** by default, React will be in development mode. The development version includes extra warnings about common mistakes, whereas the production version includes extra performance optimizations and strips all error messages. Don't forget to use the [production build](https://reactjs.org/docs/optimizing-performance.html#use-the-production-build) when deploying your application. ## Example Usage ```js var React = require('react'); ``` # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) [![Coverage Status](https://coveralls.io/repos/yargs/yargs-parser/badge.svg?branch=)](https://coveralls.io/r/yargs/yargs-parser?branch=master) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://raw.githubusercontent.com/yargs/yargs-parser/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('./')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`. Indicate that keys should be parsed as an array and coerced to booleans / numbers: `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error), e.g. `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.number`: keys should be treated as numbers. * `opts['--']`: arguments after the end-of-options flag `--` will be set to the `argv.['--']` array instead of being set to the `argv._` array. **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * [optional] `--`: an array with arguments after the end-of-options flag `--`. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion. * `configuration`: the configuration loaded from the `yargs` stanza in package.json. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### combine arrays * default: `false` * key: `combine-arrays` Should arrays be combined when provided by both command line arguments and a configuration file. ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ### negation prefix * default: `no-` * key: `negation-prefix` The prefix to use for negated boolean variables. ```sh node example.js --no-foo { _: [], foo: false } ``` _if set to `quux`:_ ```sh node example.js --quuxfoo { _: [], foo: false } ``` ### populate -- * default: `false`. * key: `populate--` Should unparsed flags be stored in `--` or `_`. _If disabled:_ ```sh node example.js a -b -- x y { _: [ 'a', 'x', 'y' ], b: true } ``` _If enabled:_ ```sh node example.js a -b -- x y { _: [ 'a' ], '--': [ 'x', 'y' ], b: true } ``` ### set placeholder key * default: `false`. * key: `set-placeholder-key`. Should a placeholder be added for keys not set via the corresponding CLI argument? _If disabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, c: 2 } ``` _If enabled:_ ```sh node example.js -a 1 -c 2 { _: [], a: 1, b: undefined, c: 2 } ``` ### halt at non-option * default: `false`. * key: `halt-at-non-option`. Should parsing stop at the first text argument? This is similar to how e.g. `ssh` parses its command line. _If disabled:_ ```sh node example.js -a run b -x y { _: [ 'run', 'b', 'y' ], a: true, x: true } ``` _If enabled:_ ```sh node example.js -a run b -x y { _: [ 'run', 'b', '-x', 'y' ], a: true } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # node-http-signature node-http-signature is a node.js library that has client and server components for Joyent's [HTTP Signature Scheme](http_signing.md). ## Usage Note the example below signs a request with the same key/cert used to start an HTTP server. This is almost certainly not what you actually want, but is just used to illustrate the API calls; you will need to provide your own key management in addition to this library. ### Client ```js var fs = require('fs'); var https = require('https'); var httpSignature = require('http-signature'); var key = fs.readFileSync('./key.pem', 'ascii'); var options = { host: 'localhost', port: 8443, path: '/', method: 'GET', headers: {} }; // Adds a 'Date' header in, signs it, and adds the // 'Authorization' header in. var req = https.request(options, function(res) { console.log(res.statusCode); }); httpSignature.sign(req, { key: key, keyId: './cert.pem' }); req.end(); ``` ### Server ```js var fs = require('fs'); var https = require('https'); var httpSignature = require('http-signature'); var options = { key: fs.readFileSync('./key.pem'), cert: fs.readFileSync('./cert.pem') }; https.createServer(options, function (req, res) { var rc = 200; var parsed = httpSignature.parseRequest(req); var pub = fs.readFileSync(parsed.keyId, 'ascii'); if (!httpSignature.verifySignature(parsed, pub)) rc = 401; res.writeHead(rc); res.end(); }).listen(8443); ``` ## Installation npm install http-signature ## License MIT. ## Bugs See <https://github.com/joyent/node-http-signature/issues>. # Polyfill for `Object.setPrototypeOf` A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. ## Usage: ``` $ npm install --save setprototypeof ``` ```javascript var setPrototypeOf = require('setprototypeof'); var obj = {}; setPrototypeOf(obj, { foo: function() { return 'bar'; } }); obj.foo(); // bar ``` TypeScript is also supported: ```typescript import setPrototypeOf = require('setprototypeof'); ``` are-we-there-yet ---------------- Track complex hiearchies of asynchronous task completion statuses. This is intended to give you a way of recording and reporting the progress of the big recursive fan-out and gather type workflows that are so common in async. What you do with this completion data is up to you, but the most common use case is to feed it to one of the many progress bar modules. Most progress bar modules include a rudamentary version of this, but my needs were more complex. Usage ===== ```javascript var TrackerGroup = require("are-we-there-yet").TrackerGroup var top = new TrackerGroup("program") var single = top.newItem("one thing", 100) single.completeWork(20) console.log(top.completed()) // 0.2 fs.stat("file", function(er, stat) { if (er) throw er var stream = top.newStream("file", stat.size) console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete // and 50% * 20% == 10% fs.createReadStream("file").pipe(stream).on("data", function (chunk) { // do stuff with chunk }) top.on("change", function (name) { // called each time a chunk is read from "file" // top.completed() will start at 0.1 and fill up to 0.6 as the file is read }) }) ``` Shared Methods ============== * var completed = tracker.completed() Implemented in: `Tracker`, `TrackerGroup`, `TrackerStream` Returns the ratio of completed work to work to be done. Range of 0 to 1. * tracker.finish() Implemented in: `Tracker`, `TrackerGroup` Marks the tracker as completed. With a TrackerGroup this marks all of its components as completed. Marks all of the components of this tracker as finished, which in turn means that `tracker.completed()` for this will now be 1. This will result in one or more `change` events being emitted. Events ====== All tracker objects emit `change` events with the following arguments: ``` function (name, completed, tracker) ``` `name` is the name of the tracker that originally emitted the event, or if it didn't have one, the first containing tracker group that had one. `completed` is the percent complete (as returned by `tracker.completed()` method). `tracker` is the tracker object that you are listening for events on. TrackerGroup ============ * var tracker = new TrackerGroup(**name**) * **name** *(optional)* - The name of this tracker group, used in change notifications if the component updating didn't have a name. Defaults to undefined. Creates a new empty tracker aggregation group. These are trackers whose completion status is determined by the completion status of other trackers. * tracker.addUnit(**otherTracker**, **weight**) * **otherTracker** - Any of the other are-we-there-yet tracker objects * **weight** *(optional)* - The weight to give the tracker, defaults to 1. Adds the **otherTracker** to this aggregation group. The weight determines how long you expect this tracker to take to complete in proportion to other units. So for instance, if you add one tracker with a weight of 1 and another with a weight of 2, you're saying the second will take twice as long to complete as the first. As such, the first will account for 33% of the completion of this tracker and the second will account for the other 67%. Returns **otherTracker**. * var subGroup = tracker.newGroup(**name**, **weight**) The above is exactly equivalent to: ```javascript var subGroup = tracker.addUnit(new TrackerGroup(name), weight) ``` * var subItem = tracker.newItem(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subItem = tracker.addUnit(new Tracker(name, todo), weight) ``` * var subStream = tracker.newStream(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subStream = tracker.addUnit(new TrackerStream(name, todo), weight) ``` * console.log( tracker.debug() ) Returns a tree showing the completion of this tracker group and all of its children, including recursively entering all of the children. Tracker ======= * var tracker = new Tracker(**name**, **todo**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **todo** *(optional)* The amount of work todo (a number). Defaults to 0. Ordinarily these are constructed as a part of a tracker group (via `newItem`). * var completed = tracker.completed() Returns the ratio of completed work to work to be done. Range of 0 to 1. If total work to be done is 0 then it will return 0. * tracker.addWork(**todo**) * **todo** A number to add to the amount of work to be done. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. * tracker.completeWork(**completed**) * **completed** A number to add to the work complete Increase the amount of work complete, thus increasing the completion percentage. Will never increase the work completed past the amount of work todo. That is, percentages > 100% are not allowed. Triggers a `change` event. * tracker.finish() Marks this tracker as finished, tracker.completed() will now be 1. Triggers a `change` event. TrackerStream ============= * var tracker = new TrackerStream(**name**, **size**, **options**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **size** *(optional)* The number of bytes being sent through this stream. * **options** *(optional)* A hash of stream options The tracker stream object is a pass through stream that updates an internal tracker object each time a block passes through. It's intended to track downloads, file extraction and other related activities. You use it by piping your data source into it and then using it as your data source. If your data has a length attribute then that's used as the amount of work completed when the chunk is passed through. If it does not (eg, object streams) then each chunk counts as completing 1 unit of work, so your size should be the total number of objects being streamed. * tracker.addWork(**todo**) * **todo** Increase the expected overall size by **todo** bytes. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Release history ### v4.0.0 **Added** * `promise` support ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 64 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 19, 2017._ # invariant [![Build Status](https://travis-ci.org/zertosh/invariant.svg?branch=master)](https://travis-ci.org/zertosh/invariant) A mirror of Facebook's `invariant` (e.g. [React](https://github.com/facebook/react/blob/v0.13.3/src/vendor/core/invariant.js), [flux](https://github.com/facebook/flux/blob/2.0.2/src/invariant.js)). A way to provide descriptive errors in development but generic errors in production. ## Install With [npm](http://npmjs.org) do: ```sh npm install invariant ``` ## `invariant(condition, message)` ```js var invariant = require('invariant'); invariant(someTruthyVal, 'This will not throw'); // No errors invariant(someFalseyVal, 'This will throw an error with this message'); // Error: Invariant Violation: This will throw an error with this message ``` **Note:** When `process.env.NODE_ENV` is not `production`, the message is required. If omitted, `invariant` will throw regardless of the truthiness of the condition. When `process.env.NODE_ENV` is `production`, the message is optional – so they can be minified away. ### Browser When used with [browserify](https://github.com/substack/node-browserify), it'll use `browser.js` (instead of `invariant.js`) and the [envify](https://github.com/hughsk/envify) transform will inline the value of `process.env.NODE_ENV`. ### Node The node version is optimized around the performance implications of accessing `process.env`. The value of `process.env.NODE_ENV` is cached, and repeatedly used instead of reading `process.env`. See [Server rendering is slower with npm react #812](https://github.com/facebook/react/issues/812) # node-sass #### Supported Node.js versions vary by release, please consult the [releases page](https://github.com/sass/node-sass/releases) <table> <tr> <td> <img width="77px" alt="Sass logo" src="https://rawgit.com/sass/node-sass/master/media/logo.svg" /> </td> <td valign="bottom" align="right"> <a href="https://www.npmjs.com/package/node-sass"> <img width="100%" src="https://nodei.co/npm/node-sass.png?downloads=true&downloadRank=true&stars=true"> </a> </td> </tr> </table> [![Build Status](https://travis-ci.org/sass/node-sass.svg?branch=master&style=flat)](https://travis-ci.org/sass/node-sass) [![Build status](https://ci.appveyor.com/api/projects/status/22mjbk59kvd55m9y/branch/master?svg=true)](https://ci.appveyor.com/project/sass/node-sass/branch/master) [![npm version](https://badge.fury.io/js/node-sass.svg)](http://badge.fury.io/js/node-sass) [![Dependency Status](https://david-dm.org/sass/node-sass.svg?theme=shields.io)](https://david-dm.org/sass/node-sass) [![devDependency Status](https://david-dm.org/sass/node-sass/dev-status.svg?theme=shields.io)](https://david-dm.org/sass/node-sass#info=devDependencies) [![Coverage Status](https://coveralls.io/repos/sass/node-sass/badge.svg?branch=master)](https://coveralls.io/r/sass/node-sass?branch=master) [![Inline docs](http://inch-ci.org/github/sass/node-sass.svg?branch=master)](http://inch-ci.org/github/sass/node-sass) [![Join us in Slack](https://libsass-slack.herokuapp.com/badge.svg)](https://libsass-slack.herokuapp.com/) Node-sass is a library that provides binding for Node.js to [LibSass], the C version of the popular stylesheet preprocessor, Sass. It allows you to natively compile .scss files to css at incredible speed and automatically via a connect middleware. Find it on npm: <https://www.npmjs.com/package/node-sass> Follow @nodesass on twitter for release updates: <https://twitter.com/nodesass> ## Install ```shell npm install node-sass ``` Some users have reported issues installing on Ubuntu due to `node` being registered to another package. [Follow the official NodeJS docs](https://github.com/nodejs/node-v0.x-archive/wiki/Installing-Node.js-via-package-manager) to install NodeJS so that `#!/usr/bin/env node` correctly resolves. Compiling on Windows machines requires the [node-gyp prerequisites](https://github.com/nodejs/node-gyp#on-windows). Are you seeing the following error? Check out our [Troubleshooting guide](https://github.com/sass/node-sass/blob/master/TROUBLESHOOTING.md#installing-node-sass-4x-with-node--4).** ``` SyntaxError: Use of const in strict mode. ``` **Having installation troubles? Check out our [Troubleshooting guide](https://github.com/sass/node-sass/blob/master/TROUBLESHOOTING.md).** ### Install from mirror in China ```shell npm install -g mirror-config-china --registry=http://registry.npm.taobao.org npm install node-sass ``` ## Usage ```javascript var sass = require('node-sass'); sass.render({ file: scss_filename, [, options..] }, function(err, result) { /*...*/ }); // OR var result = sass.renderSync({ data: scss_content [, options..] }); ``` ## Options ### file * Type: `String` * Default: `null` **Special**: `file` or `data` must be specified Path to a file for [LibSass] to compile. ### data * Type: `String` * Default: `null` **Special**: `file` or `data` must be specified A string to pass to [LibSass] to compile. It is recommended that you use `includePaths` in conjunction with this so that [LibSass] can find files when using the `@import` directive. ### importer (>= v2.0.0) - _experimental_ **This is an experimental LibSass feature. Use with caution.** * Type: `Function | Function[]` signature `function(url, prev, done)` * Default: `undefined` Function Parameters and Information: * `url (String)` - the path in import **as-is**, which [LibSass] encountered * `prev (String)` - the previously resolved path * `done (Function)` - a callback function to invoke on async completion, takes an object literal containing * `file (String)` - an alternate path for [LibSass] to use **OR** * `contents (String)` - the imported contents (for example, read from memory or the file system) Handles when [LibSass] encounters the `@import` directive. A custom importer allows extension of the [LibSass] engine in both a synchronous and asynchronous manner. In both cases, the goal is to either `return` or call `done()` with an object literal. Depending on the value of the object literal, one of two things will happen. When returning or calling `done()` with `{ file: "String" }`, the new file path will be assumed for the `@import`. It's recommended to be mindful of the value of `prev` in instances where relative path resolution may be required. When returning or calling `done()` with `{ contents: "String" }`, the string value will be used as if the file was read in through an external source. Starting from v3.0.0: * `this` refers to a contextual scope for the immediate run of `sass.render` or `sass.renderSync` * importers can return error and LibSass will emit that error in response. For instance: ```javascript done(new Error('doesn\'t exist!')); // or return synchronously return new Error('nothing to do here'); ``` * importer can be an array of functions, which will be called by LibSass in the order of their occurrence in array. This helps user specify special importer for particular kind of path (filesystem, http). If an importer does not want to handle a particular path, it should return `null`. See [functions section](#functions--v300---experimental) for more details on Sass types. ### functions (>= v3.0.0) - _experimental_ **This is an experimental LibSass feature. Use with caution.** `functions` is an `Object` that holds a collection of custom functions that may be invoked by the sass files being compiled. They may take zero or more input parameters and must return a value either synchronously (`return ...;`) or asynchronously (`done();`). Those parameters will be instances of one of the constructors contained in the `require('node-sass').types` hash. The return value must be of one of these types as well. See the list of available types below: #### types.Number(value [, unit = ""]) * `getValue()`/ `setValue(value)` : gets / sets the numerical portion of the number * `getUnit()` / `setUnit(unit)` : gets / sets the unit portion of the number #### types.String(value) * `getValue()` / `setValue(value)` : gets / sets the enclosed string #### types.Color(r, g, b [, a = 1.0]) or types.Color(argb) * `getR()` / `setR(value)` : red component (integer from `0` to `255`) * `getG()` / `setG(value)` : green component (integer from `0` to `255`) * `getB()` / `setB(value)` : blue component (integer from `0` to `255`) * `getA()` / `setA(value)` : alpha component (number from `0` to `1.0`) Example: ```javascript var Color = require('node-sass').types.Color, c1 = new Color(255, 0, 0), c2 = new Color(0xff0088cc); ``` #### types.Boolean(value) * `getValue()` : gets the enclosed boolean * `types.Boolean.TRUE` : Singleton instance of `types.Boolean` that holds "true" * `types.Boolean.FALSE` : Singleton instance of `types.Boolean` that holds "false" #### types.List(length [, commaSeparator = true]) * `getValue(index)` / `setValue(index, value)` : `value` must itself be an instance of one of the constructors in `sass.types`. * `getSeparator()` / `setSeparator(isComma)` : whether to use commas as a separator * `getLength()` #### types.Map(length) * `getKey(index)` / `setKey(index, value)` * `getValue(index)` / `setValue(index, value)` * `getLength()` #### types.Null() * `types.Null.NULL` : Singleton instance of `types.Null`. #### Example ```javascript sass.renderSync({ data: '#{headings(2,5)} { color: #08c; }', functions: { 'headings($from: 0, $to: 6)': function(from, to) { var i, f = from.getValue(), t = to.getValue(), list = new sass.types.List(t - f + 1); for (i = f; i <= t; i++) { list.setValue(i - f, new sass.types.String('h' + i)); } return list; } } }); ``` ### includePaths * Type: `Array<String>` * Default: `[]` An array of paths that [LibSass] can look in to attempt to resolve your `@import` declarations. When using `data`, it is recommended that you use this. ### indentedSyntax * Type: `Boolean` * Default: `false` `true` values enable [Sass Indented Syntax](http://sass-lang.com/documentation/file.INDENTED_SYNTAX.html) for parsing the data string or file. __Note:__ node-sass/libsass will compile a mixed library of scss and indented syntax (.sass) files with the Default setting (false) as long as .sass and .scss extensions are used in filenames. ### indentType (>= v3.0.0) * Type: `String` * Default: `space` Used to determine whether to use space or tab character for indentation. ### indentWidth (>= v3.0.0) * Type: `Number` * Default: `2` * Maximum: `10` Used to determine the number of spaces or tabs to be used for indentation. ### linefeed (>= v3.0.0) * Type: `String` * Default: `lf` Used to determine whether to use `cr`, `crlf`, `lf` or `lfcr` sequence for line break. ### omitSourceMapUrl * Type: `Boolean` * Default: `false` **Special:** When using this, you should also specify `outFile` to avoid unexpected behavior. `true` values disable the inclusion of source map information in the output file. ### outFile * Type: `String | null` * Default: `null` **Special:** Required when `sourceMap` is a truthy value Specify the intended location of the output file. Strongly recommended when outputting source maps so that they can properly refer back to their intended files. **Attention** enabling this option will **not** write the file on disk for you, it's for internal reference purpose only (to generate the map for example). Example on how to write it on the disk ```javascript sass.render({ ... outFile: yourPathTotheFile, }, function(error, result) { // node-style callback from v3.0.0 onwards if(!error){ // No errors during the compilation, write this result on the disk fs.writeFile(yourPathTotheFile, result.css, function(err){ if(!err){ //file written on disk } }); } }); }); ``` ### outputStyle * Type: `String` * Default: `nested` * Values: `nested`, `expanded`, `compact`, `compressed` Determines the output format of the final CSS style. ### precision * Type: `Integer` * Default: `5` Used to determine how many digits after the decimal will be allowed. For instance, if you had a decimal number of `1.23456789` and a precision of `5`, the result will be `1.23457` in the final CSS. ### sourceComments * Type: `Boolean` * Default: `false` `true` Enables the line number and file where a selector is defined to be emitted into the compiled CSS as a comment. Useful for debugging, especially when using imports and mixins. ### sourceMap * Type: `Boolean | String | undefined` * Default: `undefined` **Special:** Setting the `sourceMap` option requires also setting the `outFile` option Enables the outputting of a source map during `render` and `renderSync`. When `sourceMap === true`, the value of `outFile` is used as the target output location for the source map. When `typeof sourceMap === "string"`, the value of `sourceMap` will be used as the writing location for the file. ### sourceMapContents * Type: `Boolean` * Default: `false` `true` includes the `contents` in the source map information ### sourceMapEmbed * Type: `Boolean` * Default: `false` `true` embeds the source map as a data URI ### sourceMapRoot * Type: `String` * Default: `undefined` the value will be emitted as `sourceRoot` in the source map information ## `render` Callback (>= v3.0.0) node-sass supports standard node style asynchronous callbacks with the signature of `function(err, result)`. In error conditions, the `error` argument is populated with the error object. In success conditions, the `result` object is populated with an object describing the result of the render call. ### Error Object * `message` (String) - The error message. * `line` (Number) - The line number of error. * `column` (Number) - The column number of error. * `status` (Number) - The status code. * `file` (String) - The filename of error. In case `file` option was not set (in favour of `data`), this will reflect the value `stdin`. ### Result Object * `css` (Buffer) - The compiled CSS. Write this to a file, or serve it out as needed. * `map` (Buffer) - The source map * `stats` (Object) - An object containing information about the compile. It contains the following keys: * `entry` (String) - The path to the scss file, or `data` if the source was not a file * `start` (Number) - Date.now() before the compilation * `end` (Number) - Date.now() after the compilation * `duration` (Number) - *end* - *start* * `includedFiles` (Array) - Absolute paths to all related scss files in no particular order. ### Examples ```javascript var sass = require('node-sass'); sass.render({ file: '/path/to/myFile.scss', data: 'body{background:blue; a{color:black;}}', importer: function(url, prev, done) { // url is the path in import as is, which LibSass encountered. // prev is the previously resolved path. // done is an optional callback, either consume it or return value synchronously. // this.options contains this options hash, this.callback contains the node-style callback someAsyncFunction(url, prev, function(result){ done({ file: result.path, // only one of them is required, see section Special Behaviours. contents: result.data }); }); // OR var result = someSyncFunction(url, prev); return {file: result.path, contents: result.data}; }, includePaths: [ 'lib/', 'mod/' ], outputStyle: 'compressed' }, function(error, result) { // node-style callback from v3.0.0 onwards if (error) { console.log(error.status); // used to be "code" in v2x and below console.log(error.column); console.log(error.message); console.log(error.line); } else { console.log(result.css.toString()); console.log(result.stats); console.log(result.map.toString()); // or better console.log(JSON.stringify(result.map)); // note, JSON.stringify accepts Buffer too } }); // OR var result = sass.renderSync({ file: '/path/to/file.scss', data: 'body{background:blue; a{color:black;}}', outputStyle: 'compressed', outFile: '/to/my/output.css', sourceMap: true, // or an absolute or relative (to outFile) path importer: function(url, prev, done) { // url is the path in import as is, which LibSass encountered. // prev is the previously resolved path. // done is an optional callback, either consume it or return value synchronously. // this.options contains this options hash someAsyncFunction(url, prev, function(result){ done({ file: result.path, // only one of them is required, see section Special Behaviours. contents: result.data }); }); // OR var result = someSyncFunction(url, prev); return {file: result.path, contents: result.data}; } })); console.log(result.css); console.log(result.map); console.log(result.stats); ``` ### Special behaviours * In the case that both `file` and `data` options are set, node-sass will give precedence to `data` and use `file` to calculate paths in sourcemaps. ### Version information (>= v2.0.0) Both `node-sass` and `libsass` version info is now exposed via the `info` method: ```javascript var sass = require('node-sass'); console.log(sass.info); /* it will output something like: node-sass 2.0.1 (Wrapper) [JavaScript] libsass 3.1.0 (Sass Compiler) [C/C++] */ ``` Since node-sass >=v3.0.0 LibSass version is determined at run time. ## Integrations Listing of community uses of node-sass in build tools and frameworks. ### Brackets extension [@jasonsanjose](https://github.com/jasonsanjose) has created a [Brackets](http://brackets.io) extension based on node-sass: <https://github.com/jasonsanjose/brackets-sass>. When editing Sass files, the extension compiles changes on save. The extension also integrates with Live Preview to show Sass changes in the browser without saving or compiling. ### Brunch plugin [Brunch](http://brunch.io)'s official sass plugin uses node-sass by default, and automatically falls back to ruby if use of Compass is detected: <https://github.com/brunch/sass-brunch> ### Connect/Express middleware Recompile `.scss` files automatically for connect and express based http servers. This functionality has been moved to [`node-sass-middleware`](https://github.com/sass/node-sass-middleware) in node-sass v1.0.0 ### DocPad Plugin [@10xLaCroixDrinker](https://github.com/10xLaCroixDrinker) wrote a [DocPad](http://docpad.org/) plugin that compiles `.scss` files using node-sass: <https://github.com/10xLaCroixDrinker/docpad-plugin-nodesass> ### Duo.js extension [@stephenway](https://github.com/stephenway) has created an extension that transpiles Sass to CSS using node-sass with [duo.js](http://duojs.org/) <https://github.com/duojs/sass> ### Grunt extension [@sindresorhus](https://github.com/sindresorhus/) has created a set of grunt tasks based on node-sass: <https://github.com/sindresorhus/grunt-sass> ### Gulp extension [@dlmanning](https://github.com/dlmanning/) has created a gulp sass plugin based on node-sass: <https://github.com/dlmanning/gulp-sass> ### Harp [@sintaxi](https://github.com/sintaxi)’s Harp web server implicitly compiles `.scss` files using node-sass: <https://github.com/sintaxi/harp> ### Metalsmith plugin [@stevenschobert](https://github.com/stevenschobert/) has created a metalsmith plugin based on node-sass: <https://github.com/stevenschobert/metalsmith-sass> ### Meteor plugin [@fourseven](https://github.com/fourseven) has created a meteor plugin based on node-sass: <https://github.com/fourseven/meteor-scss> ### Mimosa module [@dbashford](https://github.com/dbashford) has created a Mimosa module for sass which includes node-sass: <https://github.com/dbashford/mimosa-sass> ## Example App There is also an example connect app here: <https://github.com/andrew/node-sass-example> ## Rebuilding binaries Node-sass includes pre-compiled binaries for popular platforms, to add a binary for your platform follow these steps: Check out the project: ```bash git clone --recursive https://github.com/sass/node-sass.git cd node-sass npm install node scripts/build -f # use -d switch for debug release # if succeeded, it will generate and move # the binary in vendor directory. ``` ## Command Line Interface The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section. Output will be sent to stdout if the `--output` flag is omitted. ### Usage `node-sass [options] <input> [output]` Or: `cat <input> | node-sass > output` Example: `node-sass src/style.scss dest/style.css` **Options:** ```bash -w, --watch Watch a directory or file -r, --recursive Recursively watch directories or files -o, --output Output directory -x, --omit-source-map-url Omit source map URL comment from output -i, --indented-syntax Treat data from stdin as sass code (versus scss) -q, --quiet Suppress log output except on error -v, --version Prints version info --output-style CSS output style (nested | expanded | compact | compressed) --indent-type Indent type for output CSS (space | tab) --indent-width Indent width; number of spaces or tabs (maximum value: 10) --linefeed Linefeed style (cr | crlf | lf | lfcr) --source-comments Include debug info in output --source-map Emit source map --source-map-contents Embed include contents in map --source-map-embed Embed sourceMappingUrl as data URI --source-map-root Base path, will be emitted in source-map as is --include-path Path to look for imported files --follow Follow symlinked directories --precision The amount of precision allowed in decimal numbers --error-bell Output a bell character on errors --importer Path to .js file containing custom importer --functions Path to .js file containing custom functions --help Print usage info ``` The `input` can be either a single `.scss` or `.sass`, or a directory. If the input is a directory the `--output` flag must also be supplied. Also, note `--importer` takes the (absolute or relative to pwd) path to a js file, which needs to have a default `module.exports` set to the importer function. See our test [fixtures](https://github.com/sass/node-sass/tree/974f93e76ddd08ea850e3e663cfe64bb6a059dd3/test/fixtures/extras) for example. The `--source-map` option accepts a boolean value, in which case it replaces destination extension with `.css.map`. It also accepts path to `.map` file and even path to the desired directory. When compiling a directory `--source-map` can either be a boolean value or a directory. ## Binary configuration parameters node-sass supports different configuration parameters to change settings related to the sass binary such as binary name, binary path or alternative download path. Following parameters are supported by node-sass: Variable name | .npmrc parameter | Process argument | Value -----------------|------------------|--------------------|------ SASS_BINARY_NAME | sass_binary_name | --sass-binary-name | path SASS_BINARY_SITE | sass_binary_site | --sass-binary-site | URL SASS_BINARY_PATH | sass_binary_path | --sass-binary-path | path SASS_BINARY_DIR | sass_binary_dir | --sass-binary-dir | path These parameters can be used as environment variable: * E.g. `export SASS_BINARY_SITE=http://example.com/` As local or global [.npmrc](https://docs.npmjs.com/misc/config) configuration file: * E.g. `sass_binary_site=http://example.com/` As a process argument: * E.g. `npm install node-sass --sass-binary-site=http://example.com/` ## Post-install Build Install runs only two Mocha tests to see if your machine can use the pre-built [LibSass] which will save some time during install. If any tests fail it will build from source. ## Maintainers This module is brought to you and maintained by the following people: * Michael Mifsud - Project Lead ([Github](https://github.com/xzyfer) / [Twitter](https://twitter.com/xzyfer)) * Andrew Nesbitt ([Github](https://github.com/andrew) / [Twitter](https://twitter.com/teabass)) * Dean Mao ([Github](https://github.com/deanmao) / [Twitter](https://twitter.com/deanmao)) * Brett Wilkins ([Github](https://github.com/bwilkins) / [Twitter](https://twitter.com/bjmaz)) * Keith Cirkel ([Github](https://github.com/keithamus) / [Twitter](https://twitter.com/Keithamus)) * Laurent Goderre ([Github](https://github.com/laurentgoderre) / [Twitter](https://twitter.com/laurentgoderre)) * Nick Schonning ([Github](https://github.com/nschonni) / [Twitter](https://twitter.com/nschonni)) * Adam Yeats ([Github](https://github.com/adamyeats) / [Twitter](https://twitter.com/adamyeats)) * Adeel Mujahid ([Github](https://github.com/am11) / [Twitter](https://twitter.com/adeelbm)) ## Contributors We <3 our contributors! A special thanks to all those who have clocked in some dev time on this project, we really appreciate your hard work. You can find [a full list of those people here.](https://github.com/sass/node-sass/graphs/contributors) ### Note on Patches/Pull Requests Check out our [Contributing guide](/.github/CONTRIBUTING.md) ## Copyright Copyright (c) 2015 Andrew Nesbitt. See [LICENSE](https://github.com/sass/node-sass/blob/master/LICENSE) for details. [LibSass]: https://github.com/sass/libsass # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # globule [![Build Status: Linux](https://travis-ci.org/cowboy/node-globule.svg?branch=master)](https://travis-ci.org/cowboy/node-globule) [![Build Status: Windows](https://ci.appveyor.com/api/projects/status/i9fnc38q952r9nc0/branch/master?svg=true)](https://ci.appveyor.com/project/gruntjs/node-globule/branch/master) An easy-to-use wildcard globbing library. ## Getting Started Install the module with: `npm install globule` ```javascript var globule = require('globule'); var filepaths = globule.find('**/*.js'); ``` ## Documentation ### globule.find Returns a unique array of all file or directory paths that match the given globbing pattern(s). This method accepts either comma separated globbing patterns or an array of globbing patterns. Paths matching patterns that begin with `!` will be excluded from the returned array. Patterns are processed in order, so inclusion and exclusion order is significant. Patterns may be specified as function arguments or as a `src` property of the options object. ```js globule.find(patterns [, patterns [, ...]] [, options]) globule.find({src: patterns, /* other options */}) ``` The `options` object supports all [glob][] library options, along with a few extras. These are the most commonly used: * `src` This property may be used instead of specifying patterns as function arguments. * `filter` Either a valid [fs.Stats method name](http://nodejs.org/docs/latest/api/fs.html#fs_class_fs_stats) or a function that will be passed the matched `src` filepath and `options` object as arguments. This function should return a `Boolean` value. * `nonull` Retain globbing patterns in result set even if they fail to match files. * `matchBase` Patterns without slashes will match just the basename part. Eg. this makes `*.js` work like `**/*.js`. * `srcBase` Patterns will be matched relative to the specified path instead of the current working directory. This is a synonym for `cwd`. * `prefixBase` Any specified `srcBase` will be prefixed to all returned filepaths. [glob]: https://github.com/isaacs/node-glob ### globule.match Match one or more globbing patterns against one or more file paths. Returns a uniqued array of all file paths that match any of the specified globbing patterns. Both the `patterns` and `filepaths` arguments can be a single string or array of strings. Paths matching patterns that begin with `!` will be excluded from the returned array. Patterns are processed in order, so inclusion and exclusion order is significant. ```js globule.match(patterns, filepaths [, options]) ``` ### globule.isMatch This method contains the same signature and logic as the `globule.match` method, but returns `true` if any files were matched, otherwise `false`. ```js globule.isMatch(patterns, filepaths [, options]) ``` ### globule.mapping Given a set of source file paths, returns an array of src-dest file mapping objects. Both src and dest paths may be renamed, depending on the options specified. Patterns may be specified as function arguments or as a `src` property of the options object. ```js globule.mapping(filepaths [, filepaths [, ...]] [, options]) globule.mapping({src: filepaths, /* other options */}) ``` In addition to the options the `globule.find` method supports, the options object also supports these properties: * `srcBase` The directory from which patterns are matched. Any string specified as `srcBase` is effectively stripped from the beginning of all matched paths. * `destBase` The specified path is prefixed to all `dest` filepaths. * `ext` Remove anything after (and including) the first `.` in the destination path, then append this value. * `extDot` Change the behavior of `ext`, `"first"` and `"last"` will remove anything after the first or last `.` in the destination filename, respectively. Defaults to `"first"`. * `flatten` Remove the path component from all matched src files. The src file path is still joined to the specified destBase. * `rename` If specified, this function will be responsible for returning the final `dest` filepath. By default, it flattens paths (if specified), changes extensions (if specified) and joins the matched path to the `destBase`. ### globule.findMapping This method is a convenience wrapper around the `globule.find` and `globule.mapping` methods. ```js globule.findMapping(patterns [, options]) ``` ## Examples Given the files `foo/a.js` and `foo/b.js`: ### srcBase and destBase ```js globule.find("foo/*.js") // ["foo/a.js", "foo/b.js"] globule.find("*.js", {srcBase: "foo"}) // ["a.js", "b.js"] globule.find({src: "*.js", srcBase: "foo", prefixBase: true}) // ["foo/a.js", "foo/b.js"] ``` ```js globule.findMapping("foo/*.js") // [{src: ["foo/a.js"], dest: "foo/a.js"}, {src: ["foo/b.js"], dest: "foo/b.js"}] globule.findMapping("foo/*.js", {destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/foo/a.js"}, {src: ["foo/b.js"], dest: "bar/foo/b.js"}] globule.findMapping({src: "*.js", srcBase: "foo", destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/a.js"}, {src: ["foo/b.js"], dest: "bar/b.js"}] ``` ```js globule.mapping(["foo/a.js", "foo/b.js"]) // [{src: ["foo/a.js"], dest: "foo/a.js"}, {src: ["foo/b.js"], dest: "foo/b.js"}] globule.mapping(["foo/a.js", "foo/b.js"], {destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/foo/a.js"}, {src: ["foo/b.js"], dest: "bar/foo/b.js"}] globule.mapping("foo/a.js", "foo/b.js", {destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/foo/a.js"}, {src: ["foo/b.js"], dest: "bar/foo/b.js"}] globule.mapping(["a.js", "b.js"], {srcBase: "foo", destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/a.js"}, {src: ["foo/b.js"], dest: "bar/b.js"}] globule.mapping({src: ["a.js", "b.js"], srcBase: "foo", destBase: "bar"}) // [{src: ["foo/a.js"], dest: "bar/a.js"}, {src: ["foo/b.js"], dest: "bar/b.js"}] ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). ## Release History 2018-05-29 - v1.2.1 - Update dependencies, [email protected] to avoid errant security warnings. 2017-06-10 - v1.2.0 - Update dependencies, [email protected]. 2016-10-23 - v1.1.0 - Update dependencies, [email protected], [email protected]. 2016-04-14 - v1.0.0 - Update dependencies, [email protected], [email protected], [email protected]. Paths are unix-style with prefixBase enabled. 2014-01-07 - v0.2.0 - Updated dependencies. Added `src` option. Improved exclusion speed significantly. 2013-04-11 - v0.1.0 - Initial release. ## License Copyright (c) 2018 "Cowboy" Ben Alman Licensed under the MIT license. # EventEmitter3 [![Version npm](https://img.shields.io/npm/v/eventemitter3.svg?style=flat-square)](https://www.npmjs.com/package/eventemitter3)[![Build Status](https://img.shields.io/travis/primus/eventemitter3/master.svg?style=flat-square)](https://travis-ci.org/primus/eventemitter3)[![Dependencies](https://img.shields.io/david/primus/eventemitter3.svg?style=flat-square)](https://david-dm.org/primus/eventemitter3)[![Coverage Status](https://img.shields.io/coveralls/primus/eventemitter3/master.svg?style=flat-square)](https://coveralls.io/r/primus/eventemitter3?branch=master)[![IRC channel](https://img.shields.io/badge/IRC-irc.freenode.net%23primus-00a8ff.svg?style=flat-square)](https://webchat.freenode.net/?channels=primus) [![Sauce Test Status](https://saucelabs.com/browser-matrix/eventemitter3.svg)](https://saucelabs.com/u/eventemitter3) EventEmitter3 is a high performance EventEmitter. It has been micro-optimized for various of code paths making this, one of, if not the fastest EventEmitter available for Node.js and browsers. The module is API compatible with the EventEmitter that ships by default with Node.js but there are some slight differences: - Domain support has been removed. - We do not `throw` an error when you emit an `error` event and nobody is listening. - The `newListener` and `removeListener` events have been removed as they are useful only in some uncommon use-cases. - The `setMaxListeners`, `getMaxListeners`, `prependListener` and `preperndOnceListener` methods are not available. - Support for custom context for events so there is no need to use `fn.bind`. - The `removeListener` method removes all matching listeners, not only the first. It's a drop in replacement for existing EventEmitters, but just faster. Free performance, who wouldn't want that? The EventEmitter is written in EcmaScript 3 so it will work in the oldest browsers and node versions that you need to support. ## Installation ```bash $ npm install --save eventemitter3 ``` ## CDN Recommended CDN: ```text https://unpkg.com/eventemitter3@latest/umd/eventemitter3.min.js ``` ## Usage After installation the only thing you need to do is require the module: ```js var EventEmitter = require('eventemitter3'); ``` And you're ready to create your own EventEmitter instances. For the API documentation, please follow the official Node.js documentation: http://nodejs.org/api/events.html ### Contextual emits We've upgraded the API of the `EventEmitter.on`, `EventEmitter.once` and `EventEmitter.removeListener` to accept an extra argument which is the `context` or `this` value that should be set for the emitted events. This means you no longer have the overhead of an event that required `fn.bind` in order to get a custom `this` value. ```js var EE = new EventEmitter() , context = { foo: 'bar' }; function emitted() { console.log(this === context); // true } EE.once('event-name', emitted, context); EE.on('another-event', emitted, context); EE.removeListener('another-event', emitted, context); ``` ### Tests and benchmarks This module is well tested. You can run: - `npm test` to run the tests under Node.js. - `npm run test-browser` to run the tests in real browsers via Sauce Labs. We also have a set of benchmarks to compare EventEmitter3 with some available alternatives. To run the benchmarks run `npm run benchmark`. Tests and benchmarks are not included in the npm package. If you want to play with them you have to clone the GitHub repository. ## License [MIT](LICENSE) # Merge Descriptors [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Merge objects using descriptors. ```js var thing = { get name() { return 'jon' } } var animal = { } merge(animal, thing) animal.name === 'jon' ``` ## API ### merge(destination, source) Redefines `destination`'s descriptors with `source`'s. ### merge(destination, source, false) Defines `source`'s descriptors on `destination` if `destination` does not have a descriptor by the same name. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg [npm-url]: https://npmjs.org/package/merge-descriptors [travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg [travis-url]: https://travis-ci.org/component/merge-descriptors [coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg [coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master [downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg [downloads-url]: https://npmjs.org/package/merge-descriptors # for-in [![NPM version](https://img.shields.io/npm/v/for-in.svg?style=flat)](https://www.npmjs.com/package/for-in) [![NPM monthly downloads](https://img.shields.io/npm/dm/for-in.svg?style=flat)](https://npmjs.org/package/for-in) [![NPM total downloads](https://img.shields.io/npm/dt/for-in.svg?style=flat)](https://npmjs.org/package/for-in) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/for-in.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/for-in) > Iterate over the own and inherited enumerable properties of an object, and return an object with properties that evaluate to true from the callback. Exit early by returning `false`. JavaScript/Node.js ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save for-in ``` ## Usage ```js var forIn = require('for-in'); var obj = {a: 'foo', b: 'bar', c: 'baz'}; var values = []; var keys = []; forIn(obj, function (value, key, o) { keys.push(key); values.push(value); }); console.log(keys); //=> ['a', 'b', 'c']; console.log(values); //=> ['foo', 'bar', 'baz']; ``` ## About ### Related projects * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten) * [collection-map](https://www.npmjs.com/package/collection-map): Returns an array of mapped values from an array or object. | [homepage](https://github.com/jonschlinkert/collection-map) * [for-own](https://www.npmjs.com/package/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) | [homepage](https://github.com/jonschlinkert/for-own) ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 11 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [paulirish](https://github.com/paulirish) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 26, 2017._ # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # JSON5 – JSON for Humans [![Build Status](https://travis-ci.org/json5/json5.svg)][Build Status] [![Coverage Status](https://coveralls.io/repos/github/json5/json5/badge.svg)][Coverage Status] The JSON5 Data Interchange Format (JSON5) is a superset of [JSON] that aims to alleviate some of the limitations of JSON by expanding its syntax to include some productions from [ECMAScript 5.1]. This JavaScript library is the official reference implementation for JSON5 parsing and serialization libraries. [Build Status]: https://travis-ci.org/json5/json5 [Coverage Status]: https://coveralls.io/github/json5/json5 [JSON]: https://tools.ietf.org/html/rfc7159 [ECMAScript 5.1]: https://www.ecma-international.org/ecma-262/5.1/ ## Summary of Features The following ECMAScript 5.1 features, which are not supported in JSON, have been extended to JSON5. ### Objects - Object keys may be an ECMAScript 5.1 _[IdentifierName]_. - Objects may have a single trailing comma. ### Arrays - Arrays may have a single trailing comma. ### Strings - Strings may be single quoted. - Strings may span multiple lines by escaping new line characters. - Strings may include character escapes. ### Numbers - Numbers may be hexadecimal. - Numbers may have a leading or trailing decimal point. - Numbers may be [IEEE 754] positive infinity, negative infinity, and NaN. - Numbers may begin with an explicit plus sign. ### Comments - Single and multi-line comments are allowed. ### White Space - Additional white space characters are allowed. [IdentifierName]: https://www.ecma-international.org/ecma-262/5.1/#sec-7.6 [IEEE 754]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 ## Short Example ```js { // comments unquoted: 'and you can quote me on that', singleQuotes: 'I can use "double quotes" here', lineBreaks: "Look, Mom! \ No \\n's!", hexadecimal: 0xdecaf, leadingDecimalPoint: .8675309, andTrailing: 8675309., positiveSign: +1, trailingComma: 'in objects', andIn: ['arrays',], "backwardsCompatible": "with JSON", } ``` ## Specification For a detailed explanation of the JSON5 format, please read the [official specification](https://json5.github.io/json5-spec/). ## Installation ### Node.js ```sh npm install json5 ``` ```js const JSON5 = require('json5') ``` ### Browsers ```html <script src="https://unpkg.com/json5@^1.0.0"></script> ``` This will create a global `JSON5` variable. ## API The JSON5 API is compatible with the [JSON API]. [JSON API]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON ### JSON5.parse() Parses a JSON5 string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. #### Syntax JSON5.parse(text[, reviver]) #### Parameters - `text`: The string to parse as JSON5. - `reviver`: If a function, this prescribes how the value originally produced by parsing is transformed, before being returned. #### Return value The object corresponding to the given JSON5 text. ### JSON5.stringify() Converts a JavaScript value to a JSON5 string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified. #### Syntax JSON5.stringify(value[, replacer[, space]]) JSON5.stringify(value[, options]) #### Parameters - `value`: The value to convert to a JSON5 string. - `replacer`: A function that alters the behavior of the stringification process, 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 JSON5 string. If this value is null or not provided, all properties of the object are included in the resulting JSON5 string. - `space`: A String or Number object that's used to insert white space into the output JSON5 string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used. If white space is used, trailing commas will be used in objects and arrays. - `options`: An object with the following properties: - `replacer`: Same as the `replacer` parameter. - `space`: Same as the `space` parameter. - `quote`: A String representing the quote character to use when serializing strings. #### Return value A JSON5 string representing the value. ### Node.js `require()` JSON5 files When using Node.js, you can `require()` JSON5 files by adding the following statement. ```js require('json5/lib/register') ``` Then you can load a JSON5 file with a Node.js `require()` statement. For example: ```js const config = require('./config.json5') ``` ## CLI Since JSON is more widely used than JSON5, this package includes a CLI for converting JSON5 to JSON and for validating the syntax of JSON5 documents. ### Installation ```sh npm install --global json5 ``` ### Usage ```sh json5 [options] <file> ``` If `<file>` is not provided, then STDIN is used. #### Options: - `-s`, `--space`: The number of spaces to indent or `t` for tabs - `-o`, `--out-file [file]`: Output to the specified file, otherwise STDOUT - `-v`, `--validate`: Validate JSON5 but do not output JSON - `-V`, `--version`: Output the version number - `-h`, `--help`: Output usage information ## Contibuting ### Development ```sh git clone https://github.com/json5/json5 cd json5 npm install ``` When contributing code, please write relevant tests and run `npm test` and `npm run lint` before submitting pull requests. Please use an editor that supports [EditorConfig](http://editorconfig.org/). ### Issues To report bugs or request features regarding the JSON5 data format, please submit an issue to the [official specification repository](https://github.com/json5/json5-spec). To report bugs or request features regarding the JavaScript implentation of JSON5, please submit an issue to this repository. ## License MIT. See [LICENSE.md](./LICENSE.md) for details. ## Credits [Assem Kishore](https://github.com/aseemk) founded this project. [Michael Bolin](http://bolinfest.com/) independently arrived at and published some of these same ideas with awesome explanations and detail. Recommended reading: [Suggested Improvements to JSON](http://bolinfest.com/essays/json.html) [Douglas Crockford](http://www.crockford.com/) of course designed and built JSON, but his state machine diagrams on the [JSON website](http://json.org/), as cheesy as it may sound, gave us motivation and confidence that building a new parser to implement these ideas was within reach! The original implementation of JSON5 was also modeled directly off of Doug’s open-source [json_parse.js] parser. We’re grateful for that clean and well-documented code. [json_parse.js]: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js [Max Nanasy](https://github.com/MaxNanasy) has been an early and prolific supporter, contributing multiple patches and ideas. [Andrew Eisenberg](https://github.com/aeisenberg) contributed the original `stringify` method. [Jordan Tucker](https://github.com/jordanbtucker) has aligned JSON5 more closely with ES5, wrote the official JSON5 specification, completely rewrote the codebase from the ground up, and is actively maintaining this project. #is-symbol <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] [![browser support][9]][10] Is this an ES6 Symbol value? ## Example ```js var isSymbol = require('is-symbol'); assert(!isSymbol(function () {})); assert(!isSymbol(null)); assert(!isSymbol(function* () { yield 42; return Infinity; }); assert(isSymbol(Symbol.iterator)); assert(isSymbol(Symbol('foo'))); assert(isSymbol(Symbol.for('foo'))); assert(isSymbol(Object(Symbol('foo')))); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-symbol [2]: http://versionbadg.es/ljharb/is-symbol.svg [3]: https://travis-ci.org/ljharb/is-symbol.svg [4]: https://travis-ci.org/ljharb/is-symbol [5]: https://david-dm.org/ljharb/is-symbol.svg [6]: https://david-dm.org/ljharb/is-symbol [7]: https://david-dm.org/ljharb/is-symbol/dev-status.svg [8]: https://david-dm.org/ljharb/is-symbol#info=devDependencies [9]: https://ci.testling.com/ljharb/is-symbol.png [10]: https://ci.testling.com/ljharb/is-symbol [11]: https://nodei.co/npm/is-symbol.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/is-symbol.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/is-symbol.svg [downloads-url]: http://npm-stat.com/charts.html?package=is-symbol # nice-try [![Travis Build Status](https://travis-ci.org/electerious/nice-try.svg?branch=master)](https://travis-ci.org/electerious/nice-try) [![AppVeyor Status](https://ci.appveyor.com/api/projects/status/8tqb09wrwci3xf8l?svg=true)](https://ci.appveyor.com/project/electerious/nice-try) [![Coverage Status](https://coveralls.io/repos/github/electerious/nice-try/badge.svg?branch=master)](https://coveralls.io/github/electerious/nice-try?branch=master) [![Dependencies](https://david-dm.org/electerious/nice-try.svg)](https://david-dm.org/electerious/nice-try#info=dependencies) [![Greenkeeper badge](https://badges.greenkeeper.io/electerious/nice-try.svg)](https://greenkeeper.io/) A function that tries to execute a function and discards any error that occurs. ## Install ``` npm install nice-try ``` ## Usage ```js const niceTry = require('nice-try') niceTry(() => JSON.parse('true')) // true niceTry(() => JSON.parse('truee')) // undefined niceTry() // undefined niceTry(true) // undefined ``` ## API ### Parameters - `fn` `{Function}` Function that might or might not throw an error. ### Returns - `{?*}` Return-value of the function when no error occurred. # asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit) Minimal async jobs utility library, with streams support. [![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit) [![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit) [![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master) [![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit) [![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit) <!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) --> AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects. Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method. It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators. | compression | size | | :----------------- | -------: | | asynckit.js | 12.34 kB | | asynckit.min.js | 4.11 kB | | asynckit.min.js.gz | 1.47 kB | ## Install ```sh $ npm install --save asynckit ``` ## Examples ### Parallel Jobs Runs iterator over provided array in parallel. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will terminate rest of the active jobs (if abort function is provided) and return error along with salvaged data to the main callback function. #### Input Array ```javascript var parallel = require('asynckit').parallel , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , target = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // async job accepts one element from the array // and a callback function function asyncJob(item, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var parallel = require('asynckit/parallel') , assert = require('assert') ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ] , expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ] , target = [] , keys = [] ; parallel(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); assert.deepEqual(keys, expectedKeys); }); // supports full value, key, callback (shortcut) interface function asyncJob(item, key, cb) { // different delays (in ms) per item var delay = item * 25; // pretend different jobs take different time to finish // and not in consequential order var timeoutId = setTimeout(function() { keys.push(key); target.push(item); cb(null, item * 2); }, delay); // allow to cancel "leftover" jobs upon error // return function, invoking of which will abort this job return clearTimeout.bind(null, timeoutId); } ``` More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js). ### Serial Jobs Runs iterator over provided array sequentially. Stores output in the `result` array, on the matching positions. In unlikely event of an error from one of the jobs, will not proceed to the rest of the items in the list and return error along with salvaged data to the main callback function. #### Input Array ```javascript var serial = require('asynckit/serial') , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // extended interface (item, key, callback) // also supported for arrays function asyncJob(item, key, cb) { target.push(key); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-array.js](test/test-serial-array.js). #### Input Object Also it supports named jobs, listed via object. ```javascript var serial = require('asynckit').serial , assert = require('assert') ; var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ] , expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ] , target = [] ; var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 } , expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 } , expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ] , target = [] ; serial(source, asyncJob, function(err, result) { assert.deepEqual(result, expectedResult); assert.deepEqual(target, expectedTarget); }); // shortcut interface (item, callback) // works for object as well as for the arrays function asyncJob(item, cb) { target.push(item); // it will be automatically made async // even it iterator "returns" in the same event loop cb(null, item * 2); } ``` More examples could be found in [test/test-serial-object.js](test/test-serial-object.js). _Note: Since _object_ is an _unordered_ collection of properties, it may produce unexpected results with sequential iterations. Whenever order of the jobs' execution is important please use `serialOrdered` method._ ### Ordered Serial Iterations TBD For example [compare-property](compare-property) package. ### Streaming interface TBD ## Want to Know More? More examples can be found in [test folder](test/). Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions. ## License AsyncKit is licensed under the MIT license. # assign-symbols [![NPM version](https://badge.fury.io/js/assign-symbols.svg)](http://badge.fury.io/js/assign-symbols) > Assign the enumerable es6 Symbol properties from an object (or objects) to the first object passed on the arguments. Can be used as a supplement to other extend, assign or merge methods as a polyfill for the Symbols part of the es6 Object.assign method. From the [Mozilla Developer docs for Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol): > A symbol is a unique and immutable data type and may be used as an identifier for object properties. The symbol object is an implicit object wrapper for the symbol primitive data type. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i assign-symbols --save ``` ## Usage ```js var assignSymbols = require('assign-symbols'); var obj = {}; var one = {}; var symbolOne = Symbol('aaa'); one[symbolOne] = 'bbb'; var two = {}; var symbolTwo = Symbol('ccc'); two[symbolTwo] = 'ddd'; assignSymbols(obj, one, two); console.log(obj[symbolOne]); //=> 'bbb' console.log(obj[symbolTwo]); //=> 'ddd' ``` ## Similar projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties of source objects to a destination object. | [homepage](https://github.com/jonschlinkert/assign-deep) * [clone-deep](https://www.npmjs.com/package/clone-deep): Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives. | [homepage](https://github.com/jonschlinkert/clone-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/assign-symbols/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on November 06, 2015._ # React Hot Loader [![Build Status][build-badge]][build] [![version][version-badge]][package] [![Code Coverage][coverage-badge]][coverage] [![MIT License][license-badge]][license] [![PRs Welcome][prs-badge]][prs] [![Chat][chat-badge]][chat] [![Backers on Open Collective][oc-backer-badge]](#backers) [![Sponsors on Open Collective][oc-sponsor-badge]](#sponsors) [![Watch on GitHub][github-watch-badge]][github-watch] [![Star on GitHub][github-star-badge]][github-star] Tweak React components in real time ⚛️⚡️ Watch **[Dan Abramov's talk on Hot Reloading with Time Travel](https://www.youtube.com/watch?v=xsSnOQynTHs).** ## Install ``` npm install react-hot-loader ``` > Note: You can safely install react-hot-loader as a regular dependency instead > of a dev dependency as it automatically ensures it is not executed in > production and the footprint is minimal. ## 🔥 HOT-LABS 🔥 Latest (4.5.0+) version of React-Hot-Loader could be quite 🔥! > RHL will patch React, replace React-DOM by React-🔥-DOM and work with fiber directly * (required) [use webpack plugin](https://github.com/gaearon/react-hot-loader#webpack-plugin) to let RHL patch React-DOM for you. * (alternative) [use react-🔥-dom](https://github.com/gaearon/react-hot-loader#react--dom) to use already patched React-DOM. ## Getting started 1. Add `react-hot-loader/babel` to your `.babelrc`: ```js // .babelrc { "plugins": ["react-hot-loader/babel"] } ``` 2. Mark your root component as _hot-exported_: ```js // App.js import { hot } from 'react-hot-loader/root' const App = () => <div>Hello World!</div> export default hot(App) ``` 3. Make sure `react-hot-loader` is required before `react`. * or `import 'react-hot-loader'` in your main file (before React) * or have at least one variable in the same file (babel/webpack plugin would import react-hot-loader then) * or prepend your webpack entry point with `react-hot-loader/patch`, which will `import 'react-hot-loader'`, and nothing more. Keep in mind - the same rule is applied to `react-dom`, as long as it would (since 16.8.6) import `react` internally. React-hot-loader, to prevent dependency cycles(#1209), caused by the code it injects, **should be imported first**. ### Old API **Note:** There is also an old version of `hot`, used prior to version 4.5.4. **Please use the new one**, as it is much more resilient to js errors that you may make during development. Meanwhile, not all the bundlers are compatible with new `/root` API, for example **[parcel](http://parceljs.org/) is not**. React-Hot-Load will throw an error, asking you to use the old API, if such incompatibility would be detected. It is almost the same, but you have to pass `module` inside `hot`. ```js import { hot } from 'react-hot-loader' const App = () => <div>Hello World!</div> export default hot(module)(App) ``` 3. [Run webpack with Hot Module Replacement](https://webpack.js.org/guides/hot-module-replacement/#enabling-hmr): ```sh webpack-dev-server --hot ``` ## Limitations * (that's the goal) React-Hot-Loader would not change the past, only update the present - no lifecycle event would be called on component update. As a result - all the code changes, you may made among `componentWillUnmount` or `componentDidMount`, would be ignored for already created components. * (that's the goal) React-Hot-Loader would not update any object, including component `state`. * (1%) React-Hot-Loader could not reply some changes you may made in components `constructors`. As long as components would not be recreated - RHL have to _inject_ new data onto existing components, but there is no way to detect the actual change and the way reply it. React-Hot-Loader knows what class method is, not how you created it. See #1001 for details. ## Recipes ### Migrating from [create-react-app](https://github.com/facebookincubator/create-react-app) 1. Run `npm run eject` 2. Install React Hot Loader (`npm install --save-dev react-hot-loader`) 3. In `config/webpack.config.dev.js`, add `'react-hot-loader/babel'` to Babel loader configuration. The loader should now look like: ```js { test: /\.(js|jsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, plugins: ['react-hot-loader/babel'], }, } ``` 4. Mark your App (`src/App.js`) as _hot-exported_: ```js // ./containers/App.js import React from 'react' import { hot } from 'react-hot-loader' const App = () => <div>Hello World!</div> export default hot(module)(App) ``` ### Migrating from [create-react-app](https://github.com/facebookincubator/create-react-app) without ejecting Users [report](https://github.com/gaearon/react-hot-loader/pull/729#issuecomment-354097936), that it is possible to use [react-app-rewire-hot-loader](https://github.com/cdharris/react-app-rewire-hot-loader) to setup React-hot-loader without ejecting. ### TypeScript As of version 4, React Hot Loader requires you to pass your code through [Babel](http://babeljs.io/) to transform it so that it can be hot-reloaded. This can be a pain point for TypeScript users, who usually do not need to integrate Babel as part of their build process. Fortunately, it's simpler than it may seem! Babel will happily parse TypeScript syntax and can act as an alternative to the TypeScript compiler, so you can safely replace `ts-loader` or `awesome-typescript-loader` in your Webpack configuration with `babel-loader`. Babel won't typecheck your code, but you can use [`fork-ts-checker-webpack-plugin`](https://github.com/Realytics/fork-ts-checker-webpack-plugin) (and/or invoke `tsc --noEmit`) as part of your build process instead. A sample configuration: ```js { // ...you'll probably need to configure the usual Webpack fields like "mode" and "entry", too. resolve: { extensions: [".ts", ".tsx", ".js", ".jsx"] }, module: { rules: [ { test: /\.(j|t)sx?$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { cacheDirectory: true, babelrc: false, presets: [ [ "@babel/preset-env", { targets: { browsers: "last 2 versions" } } // or whatever your project requires ], "@babel/preset-typescript", "@babel/preset-react" ], plugins: [ // plugin-proposal-decorators is only needed if you're using experimental decorators in TypeScript ["@babel/plugin-proposal-decorators", { legacy: true }], ["@babel/plugin-proposal-class-properties", { loose: true }], "react-hot-loader/babel" ] } } } ] }, plugins: [ new ForkTsCheckerWebpackPlugin() ] }; ``` For a full example configuration of TypeScript with React Hot Loader and newest beta version of Babel, check [here](https://github.com/gaearon/react-hot-loader/tree/master/examples/typescript). As an alternative to this approach, it's possible to chain Webpack loaders so that your code passes through Babel and then TypeScript (or TypeScript and then Babel), but this approach is not recommended as it is more complex and may be significantly less performant. Read more [discussion here](https://github.com/gaearon/react-hot-loader/issues/884). ### Parcel Parcel supports Hot Module Reloading out of the box, just follow step 1 and 2 of [Getting Started](https://github.com/gaearon/react-hot-loader/tree/master#getting-started). We also have a [full example running Parcel + React Hot Loader](https://github.com/gaearon/react-hot-loader/tree/master/examples/parcel). ### Electron You need something to mark your modules as hot in order to use React Hot Loader. One way of doing this with Electron is to simply use webpack like any web-based project might do and the general guide above describes. See also [this example Electron app](https://github.com/s-h-a-d-o-w/rhl-electron-quick-start). A webpack-less way of doing it to use `electron-compile` (which is also used by [`electron-forge`](https://electronforge.io)) - see [this example](https://github.com/rllola/hmr-example-issue-2). While it requires less configuration, something to keep in mind is that `electron-compile`'s HMR will always reload all modules, regardless of what was actually edited. ### Source Maps If you use `devtool: 'source-map'` (or its equivalent), source maps will be emitted to hide hot reloading code. Source maps slow down your project. Use `devtool: 'eval'` for best build performance. Hot reloading code is just one line in the beginning and one line at the end of each module so you might not need source maps at all. ## Preact React-hot-loader should work out of the box with `preact-compat`, but, in case of pure preact, you will need to configure it: * create configuration file (setupHotLoader.js) ```js import reactHotLoader from 'react-hot-loader' import preact from 'preact' reactHotLoader.preact(preact) ``` * dont forget to import it #### Preact limitations * HOCs and Decorators as not supported yet. For Preact React-Hot-Loader v4 behave as v3. ## React Native React Native **[supports hot reloading natively](https://facebook.github.io/react-native/blog/2016/03/24/introducing-hot-reloading.html)** as of version 0.22. Using React Hot Loader with React Native can cause unexpected issues (see #824) and is not recommended. ## Webpack plugin We recommend using the `babel` plugin, but there are some situations where you are unable to. If so, try the `webpack` plugin / `webpack-loader` (as seen in v3). Remember - the `webpack` plugin is **not compatible** with class-based components. The `babel` plugin will inject special methods to every class, to make `class members` (like onClick) hot-updatable, while the `webpack` plugin would leave classes as is, without any _instrumentation_. ```js class MyComponent extends React.Component { onClick = () => this.setState() // COULD NOT UPDATE variable = 1 // this is ok render() {} // this is ok } ``` But `webpack-loader` could help with TypeScript or _spreading_ "cold API" [to all node_modules](https://github.com/gaearon/react-hot-loader#disabling-a-type-change-for-all-node_modules). > It is safe to enable this loader for all the files. But place it after babel-loader, if babel-loader is present. ```js // webpack.config.js module.exports = { module: { rules: [ { test: /\.jsx?$/, include: /node_modules/, use: ['react-hot-loader/webpack'], }, ], }, } ``` Webpack plugin will also land a "hot" patch to react-dom, making React-Hot-Loader more compliant to [the principles](https://github.com/gaearon/react-hot-loader/issues/1118). ## React-🔥-Dom Another way to make RHL more compliant is to use _our_ version of React-Dom - [hot-loader/react-dom](https://github.com/hot-loader/react-dom) It is the same React-Dom, with the same version, just with our patches already landed inside. There is 2 ways to install it: * Use **yarn** name resolution, so `@hot-loader/react-dom` would be installed instead of `react-dom` ``` yarn add react-dom@npm:@hot-loader/react-dom ``` * Use webpack **aliases** ```js // webpack.conf ... resolve: { alias: { 'react-dom': '@hot-loader/react-dom' } } ... ``` ### Code Splitting If you want to use Code Splitting + React Hot Loader, the simplest solution is to pick one of our compatible library: * [Loadable Components](https://github.com/smooth-code/loadable-components/) * [Imported Component](https://github.com/theKashey/react-imported-component) * [React Universal Component](https://github.com/faceyspacey/react-universal-component) * [React-Loadable](https://github.com/jamiebuilds/react-loadable) If you use a non-yet-friendly library, like [react-async-component](github.com/ctrlplusb/react-async-component) you have to mark all your "loaded components" as _hot-exported_: ```js // AsyncHello.js import { asyncComponent } from 'react-async-component' // asyncComponent could not `hot-reload` itself. const AsyncHello = asyncComponent({ resolve: () => import('./Hello'), }) export default AsyncHello ``` ```js // Hello.js import { hot } from 'react-hot-loader' const Hello = () => 'Hello' export default hot(module)(Hello) // <-- module will reload itself ``` ### Checking Element `type`s Because React Hot Loader creates proxied versions of your components, comparing reference types of elements won't work: ```js const element = <Component /> console.log(element.type === Component) // false ``` React Hot Loader exposes a function `areComponentsEqual` to make it possible: ```js import { areComponentsEqual } from 'react-hot-loader' const element = <Component /> areComponentsEqual(element.type, Component) // true ``` Another way - compare "rendered" element type ```js const element = <Component /> console.log(element.type === <Component />.type) // true // better - precache rendered type const element = <Component /> const ComponentType = <Component />.type console.log(element.type === ComponentType) // true ``` But you might have to provide all required props. See [original issue](https://github.com/gaearon/react-hot-loader/issues/304). This is most reliable way to compare components, but it will not work with required props. Another way - compare Component name. > Not all components has a name. **In production displayName could not exists.** ```js const element = <Component /> console.log(element.displayName === 'Component') // true ``` This is something we did not solve yet. Cold API could help keep original types. ### Webpack ExtractTextPlugin webpack ExtractTextPlugin is not compatible with React Hot Loader. Please disable it in development: ```js new ExtractTextPlugin({ filename: 'styles/[name].[contenthash].css', disable: NODE_ENV !== 'production', }) ``` #### Disabling a type change (❄️) It is possible to disable React-Hot-Loader for a specific component, especially to enable common way to type comparison. See #991 for the idea behind ⛄️, and #304 about "type comparison" problem. ```js import { cold } from 'react-hot-loader'; cold(SomeComponent) // this component will ignored by React-Hot-Loader <SomeComponent />.type === SomeComponent // true ``` If you will update `cold` component React-Hot-Loader will complain (on error level), and then React will cold-replace Component with a internal state lose. > Reach-Hot-Loader: cold element got updated ##### Disabling a type change for all node_modules You may _cold_ all components from node_modules. This will not work for HOC(like Redux) or dynamically created Components, but might help in most of situations, when type changes are not welcomed, and modules are not expected to change. ```js import { setConfig, cold } from 'react-hot-loader' setConfig({ onComponentRegister: (type, name, file) => file.indexOf('node_modules') > 0 && cold(type), // some components are not visible as top level variables, // thus its not known where they were created onComponentCreate: (type, name) => name.indexOf('styled') > 0 && cold(type), }) ``` ! To be able to "cold" components from 'node_modules' you have to apply babel to node_modules, while this folder is usually excluded. You may add one more babel-loader, with only one React-Hot-Loader plugin inside to solve this. **Consider using webpack-loader** for this. ##### React-Hooks React hooks are not _really_ supported by React-Hot-Loader. Mostly due to our internal processes of re-rendering React Tree, which is required to reconcile an updated application before React will try to rerender it, and fail to do that, obviously. * hooks **should work** for versions 4.6.0 and above (`pureSFC` is enabled by default). * hooks will produce **errors** on every hot-update without patches to `react-dom`. * hooks **may loss the state** without patches to `react-dom`. * hooks does not support adding new hooks on the fly * change in hooks for a mounted components will cause a runtime exception, and a `retry` button (at the nearest class component) will be shown. Pressing a `retry` button will basically remount tree branch. To mitigate any hook-related issues (and disable their hot-reloadability) - `cold` them. * _cold_ components using hooks. ```js import { setConfig, cold } from 'react-hot-loader' setConfig({ onComponentCreate: (type, name) => (String(type).indexOf('useState') > 0 || String(type).indexOf('useEffect') > 0) && cold(type), }) ``` ## API ### `hot(Component, options)` Mark a component as hot. #### Babel plugin Right now babel plugin has only one option, enabled by default. * `safetyNet` - will help you properly setup ReactHotLoader. You may disable it to get more control on the module execution order. ```js //.babelrc { "plugins": [ [ "react-hot-loader/babel", { "safetyNet": false } ] ] } ``` #### Important **!!** Use `hot` only for module `exports`, not for module `imports`. **!!** ```js import { hot } from 'react-hot-loader/root' const App = () => 'Hello World!' export default hot(App) ``` Keep in mind - by importing `react-hot-loader/root` you are setting up a boundary for update event propagation. The higher(in module hierarchy) you have it - the more stuff would be updated on Hot Module Replacement. To make RHL more reliable and safe, please place `hot` _below_ (ie somewhere in _imported_ modules): * react-dom * redux store creation * any data, you want to preserve between updates * big libraries You may(but it's not required) place `hot` to the every route/page/feature/lazy chunk, thus make updates more scoped. You don't need to wrap every component with `hot`, application work work fine with a single one. ### (old)`hot(module, options)(Component, options)` Mark a component as hot. The "new" hot is just hidding the first part - `hot(module)`, giving you only the second `(App)`. The "new" hot is using old API. ```js import { hot } from 'react-hot-loader' const App = () => 'Hello World!' export default hot(module)(App) ``` ### `AppContainer` Mark application as hot reloadable. (**Prefer** using `hot` helper, see below for migration details). This low-level approach lets you make **hot **imports\_\_, not exports. ```js import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './containers/App' const render = Component => { ReactDOM.render( <AppContainer> <Component /> </AppContainer>, document.getElementById('root'), ) } render(App) // webpack Hot Module Replacement API if (module.hot) { // keep in mind - here you are configuring HMR to accept CHILDREN MODULE // while `hot` would configure HMR for the CURRENT module module.hot.accept('./containers/App', () => { // if you are using harmony modules ({modules:false}) render(App) // in all other cases - re-require App manually render(require('./containers/App')) }) } ``` ### areComponentsEqual(Component1, Component2) Test if two components have the same type. ```js import { areComponentsEqual } from 'react-hot-loader' import Component1 from './Component1' import Component2 from './Component2' areComponentsEqual(Component1, Component2) // true or false ``` ### setConfig(config) Set a new configuration for React Hot Loader. Available options are: * `logLevel`: specify log level, default to `"error"`, available values are: `['debug', 'log', 'warn', 'error']` * `pureSFC`: enable Stateless Functional Component. If disabled they will be converted to React Components. Default value: false. * `ignoreSFC`: skip "patch" for SFC. "Hot loading" could still work, wit webpack-patch present * `pureRender`: do not amend `render` method of any component. * for the rest see [index.d.ts](https://github.com/gaearon/react-hot-loader/blob/master/index.d.ts#L62-L133). ```js // rhlConfig.js import { setConfig } from 'react-hot-loader' setConfig({ logLevel: 'debug' }) ``` **It is important** to set configuration before any other action will take a place ```js // index.js import './rhlConfig' // <-- extract configuration to a separate file, and import it in the beggining import React from 'react' .... ``` ## Migrating from v3 ### AppContainer vs hot Prior v4 the right way to setup React Hot Loader was to wrap your Application with `AppContainer`, set setup module acceptance by yourself. This approach is still valid but only for advanced use cases, prefer using `hot` helper. **React Hot Loader v3:** ```js // App.js import React from 'react' const App = () => <div>Hello world!</div> export default App ``` ```js // main.js import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './containers/App' const render = Component => { ReactDOM.render( <AppContainer> <Component /> </AppContainer>, document.getElementById('root'), ) } render(App) // webpack Hot Module Replacement API if (module.hot) { module.hot.accept('./containers/App', () => { // if you are using harmony modules ({modules:false}) render(App) // in all other cases - re-require App manually render(require('./containers/App')) }) } ``` **React Hot Loader v4:** ```js // App.js import React from 'react' import { hot } from 'react-hot-loader' const App = () => <div>Hello world!</div> export default hot(module)(App) ``` ```js // main.js import React from 'react' import ReactDOM from 'react-dom' import App from './containers/App' ReactDOM.render(<App />, document.getElementById('root')) ``` ### Patch is optional > Since 4.0 till 4.8 Code is automatically patched, you can safely remove `react-hot-loader/patch` from your webpack config, if react-hot-loader is required before React in any other way. ### Error Boundary is inside every component > Since 4.5.4 On Hot Module Update we will inject `componentDidCatch` and a _special_ `render` to every Class-based component you have, making [Error Boundaries](https://reactjs.org/docs/error-boundaries.html#introducing-error-boundaries) more local. After update we will remove all sugar, keeping only Boundaries you've created. You can provide your own `errorReporter`, via `setConfig({errorReporter})` or opt-out from root ErrorBoundaries setting `errorBoundary={false}` prop on `AppContainer` or `hot`. However - this option affects only SFC behavior, and any ClassComponent would boundary itself. ```js import { setConfig } from 'react-hot-loader' import ErrorBoundary from './ErrorBoundary' // ErrorBoundary will be given error and errorInfo prop. setConfig({ errorReporter: ErrorBoundary }) ``` If `errorReporter` is not set - full screen error overlay would be shown. #### Setting global Error Reporter Global Error Reporter would, created a fixed overlay on top the page, would be used to display errors, not handled by `errorReporter`, and any HMR error. You may change, or disable this global error overlay ```js // to disable setConfig({ ErrorOverlay: () => null }) // to change setConfig({ ErrorOverlay: MyErrorOverlay }) ``` The UX of existing overlay is a subject to change, and we are open to any proposals. ## Known limitations and side effects ### Note about `hot` `hot` accepts only React Component (Stateful or Stateless), resulting the `HotExported` variant of it. The `hot` function will setup current module to _self-accept_ itself on reload, and will **ignore** all the changes, made for non-React components. You may mark as many modules as you want. But `HotExportedComponent` **should be the only used export** of a _hot_-module. > Note: Please note how often we have used `exported` keyword. `hot` is for exports. > Note: Does nothing in production mode, just passes App through. ### New Components keep executing the old code There is no way to hot-update constructor code, as result even new components will be born as the first ones, and then grow into the last ones. As of today, this issue cannot be solved. ## Troubleshooting If it doesn't work, in 99% of cases it's a configuration issue. A missing option, a wrong path or port. webpack is very strict about configuration, and the best way to find out what's wrong is to compare your project to an already working setup, check out **[examples](https://github.com/gaearon/react-hot-loader/tree/master/examples)**, bit by bit. If something doesn't work, in 99% of cases it's an issue with your code. The Component didn't get registered, due to HOC or Decorator around it, which is making it invisible to the Babel plugin or webpack loader. We're also gathering **[Troubleshooting Recipes](https://github.com/gaearon/react-hot-loader/blob/master/docs/Troubleshooting.md)** so send a PR if you have a lesson to share! ### Switch into debug mode Debug mode adds additional warnings and can tells you why React Hot Loader is not working properly in your application. ```js import { setConfig } from 'react-hot-loader' setConfig({ logLevel: 'debug' }) ``` ## Contributors This project exists thanks to all the people who contribute. [Contribute](CONTRIBUTING.md). [![contributors][oc-contributors-img]](https://github.com/gaearon/react-hot-loader/graphs/contributors) ## Backers Thank you to all our backers! 🙏 [Become a backer][oc-backer-link] [![backers][oc-backer-img]][oc-backer-link] ## Sponsors Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor][oc-sponsor-link] <a href="https://opencollective.com/react-hot-loader/sponsor/0/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/1/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/2/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/3/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/4/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/5/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/6/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/7/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/8/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/react-hot-loader/sponsor/9/website" target="_blank"><img src="https://opencollective.com/react-hot-loader/sponsor/9/avatar.svg"></a> ## License MIT [build-badge]: https://img.shields.io/travis/gaearon/react-hot-loader.svg?style=flat-square [build]: https://travis-ci.org/gaearon/react-hot-loader [coverage-badge]: https://img.shields.io/codecov/c/github/gaearon/react-hot-loader.svg?style=flat-square [coverage]: https://codecov.io/github/gaearon/react-hot-loader [version-badge]: https://img.shields.io/npm/v/react-hot-loader.svg?style=flat-square [package]: https://www.npmjs.com/package/react-hot-loader [license-badge]: https://img.shields.io/npm/l/react-hot-loader.svg?style=flat-square [license]: https://github.com/gaearon/react-hot-loader/blob/next/LICENSE [prs-badge]: https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square [prs]: http://makeapullrequest.com [chat]: https://gitter.im/gaearon/react-hot-loader [chat-badge]: https://img.shields.io/gitter/room/gaearon/react-hot-loader.svg?style=flat-square [github-watch-badge]: https://img.shields.io/github/watchers/gaearon/react-hot-loader.svg?style=social [github-watch]: https://github.com/gaearon/react-hot-loader/watchers [github-star-badge]: https://img.shields.io/github/stars/gaearon/react-hot-loader.svg?style=social [github-star]: https://github.com/gaearon/react-hot-loader/stargazers [oc-backer-badge]: https://opencollective.com/react-hot-loader/backers/badge.svg [oc-sponsor-badge]: https://opencollective.com/react-hot-loader/sponsors/badge.svg [oc-contributors-img]: https://opencollective.com/react-hot-loader/contributors.svg?width=890&button=false [oc-backer-img]: https://opencollective.com/react-hot-loader/backers.svg?width=890 [oc-backer-link]: https://opencollective.com/react-hot-loader#backers [oc-sponsor-link]: https://opencollective.com/react-hot-loader#sponsor # verror: rich JavaScript errors This module provides several classes in support of Joyent's [Best Practices for Error Handling in Node.js](http://www.joyent.com/developers/node/design/errors). If you find any of the behavior here confusing or surprising, check out that document first. The error classes here support: * printf-style arguments for the message * chains of causes * properties to provide extra information about the error * creating your own subclasses that support all of these The classes here are: * **VError**, for chaining errors while preserving each one's error message. This is useful in servers and command-line utilities when you want to propagate an error up a call stack, but allow various levels to add their own context. See examples below. * **WError**, for wrapping errors while hiding the lower-level messages from the top-level error. This is useful for API endpoints where you don't want to expose internal error messages, but you still want to preserve the error chain for logging and debugging. * **SError**, which is just like VError but interprets printf-style arguments more strictly. * **MultiError**, which is just an Error that encapsulates one or more other errors. (This is used for parallel operations that return several errors.) # Quick start First, install the package: npm install verror If nothing else, you can use VError as a drop-in replacement for the built-in JavaScript Error class, with the addition of printf-style messages: ```javascript var err = new VError('missing file: "%s"', '/etc/passwd'); console.log(err.message); ``` This prints: missing file: "/etc/passwd" You can also pass a `cause` argument, which is any other Error object: ```javascript var fs = require('fs'); var filename = '/nonexistent'; fs.stat(filename, function (err1) { var err2 = new VError(err1, 'stat "%s"', filename); console.error(err2.message); }); ``` This prints out: stat "/nonexistent": ENOENT, stat '/nonexistent' which resembles how Unix programs typically report errors: $ sort /nonexistent sort: open failed: /nonexistent: No such file or directory To match the Unixy feel, when you print out the error, just prepend the program's name to the VError's `message`. Or just call [node-cmdutil.fail(your_verror)](https://github.com/joyent/node-cmdutil), which does this for you. You can get the next-level Error using `err.cause()`: ```javascript console.error(err2.cause().message); ``` prints: ENOENT, stat '/nonexistent' Of course, you can chain these as many times as you want, and it works with any kind of Error: ```javascript var err1 = new Error('No such file or directory'); var err2 = new VError(err1, 'failed to stat "%s"', '/junk'); var err3 = new VError(err2, 'request failed'); console.error(err3.message); ``` This prints: request failed: failed to stat "/junk": No such file or directory The idea is that each layer in the stack annotates the error with a description of what it was doing. The end result is a message that explains what happened at each level. You can also decorate Error objects with additional information so that callers can not only handle each kind of error differently, but also construct their own error messages (e.g., to localize them, format them, group them by type, and so on). See the example below. # Deeper dive The two main goals for VError are: * **Make it easy to construct clear, complete error messages intended for people.** Clear error messages greatly improve both user experience and debuggability, so we wanted to make it easy to build them. That's why the constructor takes printf-style arguments. * **Make it easy to construct objects with programmatically-accessible metadata** (which we call _informational properties_). Instead of just saying "connection refused while connecting to 192.168.1.2:80", you can add properties like `"ip": "192.168.1.2"` and `"tcpPort": 80`. This can be used for feeding into monitoring systems, analyzing large numbers of Errors (as from a log file), or localizing error messages. To really make this useful, it also needs to be easy to compose Errors: higher-level code should be able to augment the Errors reported by lower-level code to provide a more complete description of what happened. Instead of saying "connection refused", you can say "operation X failed: connection refused". That's why VError supports `causes`. In order for all this to work, programmers need to know that it's generally safe to wrap lower-level Errors with higher-level ones. If you have existing code that handles Errors produced by a library, you should be able to wrap those Errors with a VError to add information without breaking the error handling code. There are two obvious ways that this could break such consumers: * The error's name might change. People typically use `name` to determine what kind of Error they've got. To ensure compatibility, you can create VErrors with custom names, but this approach isn't great because it prevents you from representing complex failures. For this reason, VError provides `findCauseByName`, which essentially asks: does this Error _or any of its causes_ have this specific type? If error handling code uses `findCauseByName`, then subsystems can construct very specific causal chains for debuggability and still let people handle simple cases easily. There's an example below. * The error's properties might change. People often hang additional properties off of Error objects. If we wrap an existing Error in a new Error, those properties would be lost unless we copied them. But there are a variety of both standard and non-standard Error properties that should _not_ be copied in this way: most obviously `name`, `message`, and `stack`, but also `fileName`, `lineNumber`, and a few others. Plus, it's useful for some Error subclasses to have their own private properties -- and there'd be no way to know whether these should be copied. For these reasons, VError first-classes these information properties. You have to provide them in the constructor, you can only fetch them with the `info()` function, and VError takes care of making sure properties from causes wind up in the `info()` output. Let's put this all together with an example from the node-fast RPC library. node-fast implements a simple RPC protocol for Node programs. There's a server and client interface, and clients make RPC requests to servers. Let's say the server fails with an UnauthorizedError with message "user 'bob' is not authorized". The client wraps all server errors with a FastServerError. The client also wraps all request errors with a FastRequestError that includes the name of the RPC call being made. The result of this failed RPC might look like this: name: FastRequestError message: "request failed: server error: user 'bob' is not authorized" rpcMsgid: <unique identifier for this request> rpcMethod: GetObject cause: name: FastServerError message: "server error: user 'bob' is not authorized" cause: name: UnauthorizedError message: "user 'bob' is not authorized" rpcUser: "bob" When the caller uses `VError.info()`, the information properties are collapsed so that it looks like this: message: "request failed: server error: user 'bob' is not authorized" rpcMsgid: <unique identifier for this request> rpcMethod: GetObject rpcUser: "bob" Taking this apart: * The error's message is a complete description of the problem. The caller can report this directly to its caller, which can potentially make its way back to an end user (if appropriate). It can also be logged. * The caller can tell that the request failed on the server, rather than as a result of a client problem (e.g., failure to serialize the request), a transport problem (e.g., failure to connect to the server), or something else (e.g., a timeout). They do this using `findCauseByName('FastServerError')` rather than checking the `name` field directly. * If the caller logs this error, the logs can be analyzed to aggregate errors by cause, by RPC method name, by user, or whatever. Or the error can be correlated with other events for the same rpcMsgid. * It wasn't very hard for any part of the code to contribute to this Error. Each part of the stack has just a few lines to provide exactly what it knows, with very little boilerplate. It's not expected that you'd use these complex forms all the time. Despite supporting the complex case above, you can still just do: new VError("my service isn't working"); for the simple cases. # Reference: VError, WError, SError VError, WError, and SError are convenient drop-in replacements for `Error` that support printf-style arguments, first-class causes, informational properties, and other useful features. ## Constructors The VError constructor has several forms: ```javascript /* * This is the most general form. You can specify any supported options * (including "cause" and "info") this way. */ new VError(options, sprintf_args...) /* * This is a useful shorthand when the only option you need is "cause". */ new VError(cause, sprintf_args...) /* * This is a useful shorthand when you don't need any options at all. */ new VError(sprintf_args...) ``` All of these forms construct a new VError that behaves just like the built-in JavaScript `Error` class, with some additional methods described below. In the first form, `options` is a plain object with any of the following optional properties: Option name | Type | Meaning ---------------- | ---------------- | ------- `name` | string | Describes what kind of error this is. This is intended for programmatic use to distinguish between different kinds of errors. Note that in modern versions of Node.js, this name is ignored in the `stack` property value, but callers can still use the `name` property to get at it. `cause` | any Error object | Indicates that the new error was caused by `cause`. See `cause()` below. If unspecified, the cause will be `null`. `strict` | boolean | If true, then `null` and `undefined` values in `sprintf_args` are passed through to `sprintf()`. Otherwise, these are replaced with the strings `'null'`, and '`undefined`', respectively. `constructorOpt` | function | If specified, then the stack trace for this error ends at function `constructorOpt`. Functions called by `constructorOpt` will not show up in the stack. This is useful when this class is subclassed. `info` | object | Specifies arbitrary informational properties that are available through the `VError.info(err)` static class method. See that method for details. The second form is equivalent to using the first form with the specified `cause` as the error's cause. This form is distinguished from the first form because the first argument is an Error. The third form is equivalent to using the first form with all default option values. This form is distinguished from the other forms because the first argument is not an object or an Error. The `WError` constructor is used exactly the same way as the `VError` constructor. The `SError` constructor is also used the same way as the `VError` constructor except that in all cases, the `strict` property is overriden to `true. ## Public properties `VError`, `WError`, and `SError` all provide the same public properties as JavaScript's built-in Error objects. Property name | Type | Meaning ------------- | ------ | ------- `name` | string | Programmatically-usable name of the error. `message` | string | Human-readable summary of the failure. Programmatically-accessible details are provided through `VError.info(err)` class method. `stack` | string | Human-readable stack trace where the Error was constructed. For all of these classes, the printf-style arguments passed to the constructor are processed with `sprintf()` to form a message. For `WError`, this becomes the complete `message` property. For `SError` and `VError`, this message is prepended to the message of the cause, if any (with a suitable separator), and the result becomes the `message` property. The `stack` property is managed entirely by the underlying JavaScript implementation. It's generally implemented using a getter function because constructing the human-readable stack trace is somewhat expensive. ## Class methods The following methods are defined on the `VError` class and as exported functions on the `verror` module. They're defined this way rather than using methods on VError instances so that they can be used on Errors not created with `VError`. ### `VError.cause(err)` The `cause()` function returns the next Error in the cause chain for `err`, or `null` if there is no next error. See the `cause` argument to the constructor. Errors can have arbitrarily long cause chains. You can walk the `cause` chain by invoking `VError.cause(err)` on each subsequent return value. If `err` is not a `VError`, the cause is `null`. ### `VError.info(err)` Returns an object with all of the extra error information that's been associated with this Error and all of its causes. These are the properties passed in using the `info` option to the constructor. Properties not specified in the constructor for this Error are implicitly inherited from this error's cause. These properties are intended to provide programmatically-accessible metadata about the error. For an error that indicates a failure to resolve a DNS name, informational properties might include the DNS name to be resolved, or even the list of resolvers used to resolve it. The values of these properties should generally be plain objects (i.e., consisting only of null, undefined, numbers, booleans, strings, and objects and arrays containing only other plain objects). ### `VError.fullStack(err)` Returns a string containing the full stack trace, with all nested errors recursively reported as `'caused by:' + err.stack`. ### `VError.findCauseByName(err, name)` The `findCauseByName()` function traverses the cause chain for `err`, looking for an error whose `name` property matches the passed in `name` value. If no match is found, `null` is returned. If all you want is to know _whether_ there's a cause (and you don't care what it is), you can use `VError.hasCauseWithName(err, name)`. If a vanilla error or a non-VError error is passed in, then there is no cause chain to traverse. In this scenario, the function will check the `name` property of only `err`. ### `VError.hasCauseWithName(err, name)` Returns true if and only if `VError.findCauseByName(err, name)` would return a non-null value. This essentially determines whether `err` has any cause in its cause chain that has name `name`. ### `VError.errorFromList(errors)` Given an array of Error objects (possibly empty), return a single error representing the whole collection of errors. If the list has: * 0 elements, returns `null` * 1 element, returns the sole error * more than 1 element, returns a MultiError referencing the whole list This is useful for cases where an operation may produce any number of errors, and you ultimately want to implement the usual `callback(err)` pattern. You can accumulate the errors in an array and then invoke `callback(VError.errorFromList(errors))` when the operation is complete. ### `VError.errorForEach(err, func)` Convenience function for iterating an error that may itself be a MultiError. In all cases, `err` must be an Error. If `err` is a MultiError, then `func` is invoked as `func(errorN)` for each of the underlying errors of the MultiError. If `err` is any other kind of error, `func` is invoked once as `func(err)`. In all cases, `func` is invoked synchronously. This is useful for cases where an operation may produce any number of warnings that may be encapsulated with a MultiError -- but may not be. This function does not iterate an error's cause chain. ## Examples The "Demo" section above covers several basic cases. Here's a more advanced case: ```javascript var err1 = new VError('something bad happened'); /* ... */ var err2 = new VError({ 'name': 'ConnectionError', 'cause': err1, 'info': { 'errno': 'ECONNREFUSED', 'remote_ip': '127.0.0.1', 'port': 215 } }, 'failed to connect to "%s:%d"', '127.0.0.1', 215); console.log(err2.message); console.log(err2.name); console.log(VError.info(err2)); console.log(err2.stack); ``` This outputs: failed to connect to "127.0.0.1:215": something bad happened ConnectionError { errno: 'ECONNREFUSED', remote_ip: '127.0.0.1', port: 215 } ConnectionError: failed to connect to "127.0.0.1:215": something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/info.js:5:12) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:935:3 Information properties are inherited up the cause chain, with values at the top of the chain overriding same-named values lower in the chain. To continue that example: ```javascript var err3 = new VError({ 'name': 'RequestError', 'cause': err2, 'info': { 'errno': 'EBADREQUEST' } }, 'request failed'); console.log(err3.message); console.log(err3.name); console.log(VError.info(err3)); console.log(err3.stack); ``` This outputs: request failed: failed to connect to "127.0.0.1:215": something bad happened RequestError { errno: 'EBADREQUEST', remote_ip: '127.0.0.1', port: 215 } RequestError: request failed: failed to connect to "127.0.0.1:215": something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/info.js:20:12) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12) at Function.Module.runMain (module.js:497:10) at startup (node.js:119:16) at node.js:935:3 You can also print the complete stack trace of combined `Error`s by using `VError.fullStack(err).` ```javascript var err1 = new VError('something bad happened'); /* ... */ var err2 = new VError(err1, 'something really bad happened here'); console.log(VError.fullStack(err2)); ``` This outputs: VError: something really bad happened here: something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:5:12) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 caused by: VError: something bad happened at Object.<anonymous> (/home/dap/node-verror/examples/fullStack.js:3:12) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3 `VError.fullStack` is also safe to use on regular `Error`s, so feel free to use it whenever you need to extract the stack trace from an `Error`, regardless if it's a `VError` or not. # Reference: MultiError MultiError is an Error class that represents a group of Errors. This is used when you logically need to provide a single Error, but you want to preserve information about multiple underying Errors. A common case is when you execute several operations in parallel and some of them fail. MultiErrors are constructed as: ```javascript new MultiError(error_list) ``` `error_list` is an array of at least one `Error` object. The cause of the MultiError is the first error provided. None of the other `VError` options are supported. The `message` for a MultiError consists the `message` from the first error, prepended with a message indicating that there were other errors. For example: ```javascript err = new MultiError([ new Error('failed to resolve DNS name "abc.example.com"'), new Error('failed to resolve DNS name "def.example.com"'), ]); console.error(err.message); ``` outputs: first of 2 errors: failed to resolve DNS name "abc.example.com" See the convenience function `VError.errorFromList`, which is sometimes simpler to use than this constructor. ## Public methods ### `errors()` Returns an array of the errors used to construct this MultiError. # Contributing See separate [contribution guidelines](CONTRIBUTING.md). [![Build Status](https://img.shields.io/travis/css-modules/icss-replace-symbols/master.svg?style=flat-square)]() # ICSS — Replace Symbols Governs the way tokens are searched & replaced during the linking stage of ICSS loading. This is broken into its own module in case the behaviour needs to be replicated in other PostCSS plugins (i.e. [CSS Modules Constants](https://github.com/css-modules/postcss-modules-constants)) ## API ```js import replaceSymbols from "icss-replace-symbols" replaceSymbols(css, translations) ``` Where: - `css` is the PostCSS tree you're working with - `translations` is an JS object of `symbol: "replacement"` pairs, where all occurrences of `symbol` are replaced with `replacement`. ## Behaviour A symbol is a string of alphanumeric, `-` or `_` characters. A replacement can be any string. They are replaced in the following places: - In the value of a declaration, i.e. `color: my_symbol;` or `box-shadow: 0 0 blur spread shadow-color` - In a media expression i.e. `@media small {}` or `@media screen and not-large {}` ## License ISC --- Glen Maddern, 2015. # thunky Delay the evaluation of a paramless async function and cache the result (see [thunk](http://en.wikipedia.org/wiki/Thunk_%28functional_programming%29)). ``` npm install thunky ``` [![build status](http://img.shields.io/travis/mafintosh/thunky.svg?style=flat)](http://travis-ci.org/mafintosh/thunky) ## Example Let's make a simple function that returns a random number 1 second after it is called for the first time ``` js var thunky = require('thunky') var test = thunky(function (callback) { // the inner function should only accept a callback console.log('waiting 1s and returning random number') setTimeout(function () { callback(Math.random()) }, 1000) }) test(function (num) { // inner function is called the first time we call test console.log(num) // prints random number }) test(function (num) { // subsequent calls waits for the first call to finish and return the same value console.log(num) // prints the same random number as above }) ``` ## Lazy evaluation Thunky makes it easy to implement a lazy evaluation pattern. ``` js var getDb = thunky(function (callback) { db.open(myConnectionString, callback) }) var queryDb = function (query, callback) { getDb(function (err, db) { if (err) return callback(err) db.query(query, callback) }) } queryDb('some query', function (err, result) { ... } ) queryDb('some other query', function (err, result) { ... } ) ``` The first time `getDb` is called it will try do open a connection to the database. Any subsequent calls will just wait for the first call to complete and then call your callback. A nice property of this pattern is that it *easily* allows us to pass any error caused by `getDb` to the `queryDb` callback. ## Error → No caching If the thunk callback is called with an `Error` object as the first argument it will not cache the result ``` js var fails = thunky(function (callback) { console.log('returning an error') callback(new Error('bad stuff')) }) fails(function (err) { // inner function is called console.log(err) }); fails(function (err) { // inner function is called again as it returned an error before console.log(err) }) ``` ## License MIT # stream-http [![Build Status](https://travis-ci.org/jhiesey/stream-http.svg?branch=master)](https://travis-ci.org/jhiesey/stream-http) [![Sauce Test Status](https://saucelabs.com/browser-matrix/stream-http.svg)](https://saucelabs.com/u/stream-http) This module is an implementation of Node's native `http` module for the browser. It tries to match Node's API and behavior as closely as possible, but some features aren't available, since browsers don't give nearly as much control over requests. This is heavily inspired by, and intended to replace, [http-browserify](https://github.com/substack/http-browserify). ## What does it do? In accordance with its name, `stream-http` tries to provide data to its caller before the request has completed whenever possible. Backpressure, allowing the browser to only pull data from the server as fast as it is consumed, is supported in: * Chrome >= 58 (using `fetch` and `WritableStream`) The following browsers support true streaming, where only a small amount of the request has to be held in memory at once: * Chrome >= 43 (using the `fetch` API) * Firefox >= 9 (using `moz-chunked-arraybuffer` responseType with xhr) The following browsers support pseudo-streaming, where the data is available before the request finishes, but the entire response must be held in memory: * Chrome * Safari >= 5, and maybe older * IE >= 10 * Most other Webkit-based browsers, including the default Android browser All browsers newer than IE8 support binary responses. All of the above browsers that support true streaming or pseudo-streaming support that for binary data as well except for IE10. Old (presto-based) Opera also does not support binary streaming either. ### IE8 note: As of version 2.0.0, IE8 support requires the user to supply polyfills for `Object.keys`, `Array.prototype.forEach`, and `Array.prototype.indexOf`. Example implementations are provided in [ie8-polyfill.js](ie8-polyfill.js); alternately, you may want to consider using [es5-shim](https://github.com/es-shims/es5-shim). All browsers with full ES5 support shouldn't require any polyfills. ## How do you use it? The intent is to have the same API as the client part of the [Node HTTP module](https://nodejs.org/api/http.html). The interfaces are the same wherever practical, although limitations in browsers make an exact clone of the Node API impossible. This module implements `http.request`, `http.get`, and most of `http.ClientRequest` and `http.IncomingMessage` in addition to `http.METHODS` and `http.STATUS_CODES`. See the Node docs for how these work. ### Extra features compared to Node * The `message.url` property provides access to the final URL after all redirects. This is useful since the browser follows all redirects silently, unlike Node. It is available in Chrome 37 and newer, Firefox 32 and newer, and Safari 9 and newer. * The `options.withCredentials` boolean flag, used to indicate if the browser should send cookies or authentication information with a CORS request. Default false. This module has to make some tradeoffs to support binary data and/or streaming. Generally, the module can make a fairly good decision about which underlying browser features to use, but sometimes it helps to get a little input from the developer. * The `options.mode` field passed into `http.request` or `http.get` can take on one of the following values: * 'default' (or any falsy value, including `undefined`): Try to provide partial data before the request completes, but not at the cost of correctness for binary data or correctness of the 'content-type' response header. This mode will also avoid slower code paths whenever possible, which is particularly useful when making large requests in a browser like Safari that has a weaker JavaScript engine. * 'allow-wrong-content-type': Provides partial data in more cases than 'default', but at the expense of causing the 'content-type' response header to be incorrectly reported (as 'text/plain; charset=x-user-defined') in some browsers, notably Safari and Chrome 42 and older. Preserves binary data whenever possible. In some cases the implementation may also be a bit slow. This was the default in versions of this module before 1.5. * 'prefer-stream': Provide data before the request completes even if binary data (anything that isn't a single-byte ASCII or UTF8 character) will be corrupted. Of course, this option is only safe for text data. May also cause the 'content-type' response header to be incorrectly reported (as 'text/plain; charset=x-user-defined'). * 'disable-fetch': Force the use of plain XHR regardless of the browser declaring a fetch capability. Preserves the correctness of binary data and the 'content-type' response header. * 'prefer-fast': Deprecated; now a synonym for 'default', which has the same performance characteristics as this mode did in versions before 1.5. * `options.requestTimeout` allows setting a timeout in millisecionds for XHR and fetch (if supported by the browser). This is a limit on how long the entire process takes from beginning to end. Note that this is not the same as the node `setTimeout` functions, which apply to pauses in data transfer over the underlying socket, or the node `timeout` option, which applies to opening the connection. ### Features missing compared to Node * `http.Agent` is only a stub * The 'socket', 'connect', 'upgrade', and 'continue' events on `http.ClientRequest`. * Any operations, including `request.setTimeout`, that operate directly on the underlying socket. * Any options that are disallowed for security reasons. This includes setting or getting certain headers. * `message.httpVersion` * `message.rawHeaders` is modified by the browser, and may not quite match what is sent by the server. * `message.trailers` and `message.rawTrailers` will remain empty. * Redirects are followed silently by the browser, so it isn't possible to access the 301/302 redirect pages. * The `timeout` event/option and `setTimeout` functions, which operate on the underlying socket, are not available. However, see `options.requestTimeout` above. ## Example ``` js http.get('/bundle.js', function (res) { var div = document.getElementById('result'); div.innerHTML += 'GET /beep<br>'; res.on('data', function (buf) { div.innerHTML += buf; }); res.on('end', function () { div.innerHTML += '<br>__END__'; }); }) ``` ## Running tests There are two sets of tests: the tests that run in Node (found in `test/node`) and the tests that run in the browser (found in `test/browser`). Normally the browser tests run on [Sauce Labs](http://saucelabs.com/). Running `npm test` will run both sets of tests, but in order for the Sauce Labs tests to run you will need to sign up for an account (free for open source projects) and put the credentials in a [`.zuulrc` file](https://github.com/defunctzombie/zuul/wiki/zuulrc). To run just the Node tests, run `npm run test-node`. To run the browser tests locally, run `npm run test-browser-local` and point your browser to `http://localhost:8080/__zuul` ## License MIT. Copyright (C) John Hiesey and other contributors. # shallow-clone [![NPM version](https://img.shields.io/npm/v/shallow-clone.svg?style=flat)](https://www.npmjs.com/package/shallow-clone) [![NPM monthly downloads](https://img.shields.io/npm/dm/shallow-clone.svg?style=flat)](https://npmjs.org/package/shallow-clone) [![NPM total downloads](https://img.shields.io/npm/dt/shallow-clone.svg?style=flat)](https://npmjs.org/package/shallow-clone) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/shallow-clone.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/shallow-clone) > Make a shallow clone of an object, array or primitive. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save shallow-clone ``` ## Usage ```js var clone = require('shallow-clone'); ``` ## shallow clones arrays The array itself is cloned, but not the elements of the array. So any objects in the array will still not be cloned (e.g. they will be the same object as in the orginal array). ```js var arr = [{ 'a': 0 }, { 'b': 1 }] var foo = clone(arr); // foo => [{ 'a': 0 }, { 'b': 1 }] // array is cloned assert.equal(actual === expected, false); // array elements are not assert.deepEqual(actual[0], expected[0]); // true ``` ## returns primitives as-is ```js clone(0) //=> 0 clone('foo') //=> 'foo' ``` ## shallow clone a regex ```js clone(/foo/g) //=> /foo/g ``` ## shallow clone an object ```js clone({a: 1, b: 2, c: 3 }) //=> {a: 1, b: 2, c: 3 } ``` ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [clone-deep](https://www.npmjs.com/package/clone-deep): Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives. | [homepage](https://github.com/jonschlinkert/clone-deep "Recursively (deep) clone JavaScript native types, like Object, Array, RegExp, Date as well as primitives.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://github.com/jonschlinkert/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object "Mixin the own and inherited properties of other objects onto the first object. Pass an empty object as the first arg to shallow clone.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 2 | [doowb](https://github.com/doowb) | | 2 | [jonschlinkert](https://github.com/jonschlinkert) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 16, 2017._ # postcss-selector-parser [![Build Status](https://travis-ci.org/postcss/postcss-selector-parser.svg?branch=master)](https://travis-ci.org/postcss/postcss-selector-parser) > Selector parser with built in methods for working with selector strings. ## Install With [npm](https://npmjs.com/package/postcss-selector-parser) do: ``` npm install postcss-selector-parser ``` ## Quick Start ```js const parser = require('postcss-selector-parser'); const transform = selectors => { selectors.walk(selector => { // do something with the selector console.log(String(selector)) }); }; const transformed = parser(transform).processSync('h1, h2, h3'); ``` To normalize selector whitespace: ```js const parser = require('postcss-selector-parser'); const normalized = parser().processSync('h1, h2, h3', {lossless: false}); // -> h1,h2,h3 ``` Async support is provided through `parser.process` and will resolve a Promise with the resulting selector string. ## API Please see [API.md](API.md). ## Credits * Huge thanks to Andrey Sitnik (@ai) for work on PostCSS which helped accelerate this module's development. ## License MIT # caniuse-lite > A smaller version of caniuse-db, with only the essentials! ## Why? The full data behind [Can I use][1] is incredibly useful for any front end developer, and on the website all of the details from the database are displayed to the user. However in automated tools, [many of these fields go unused][2]; it's not a problem for server side consumption but client side, the less JavaScript that we send to the end user the better. caniuse-lite then, is a smaller dataset that keeps essential parts of the data in a compact format. It does this in multiple ways, such as converting `null` array entries into empty strings, representing support data as an integer rather than a string, and using base62 references instead of longer human-readable keys. This packed data is then reassembled (via functions exposed by this module) into a larger format which is mostly compatible with caniuse-db, and so it can be used as an almost drop-in replacement for caniuse-db for contexts where size on disk is important; for example, usage in web browsers. The API differences are very small and are detailed in the section below. ## API ```js import * as lite from 'caniuse-lite'; ``` ### `lite.agents` caniuse-db provides a full `data.json` file which contains all of the features data. Instead of this large file, caniuse-lite provides this data subset instead, which has the `browser`, `prefix`, `prefix_exceptions`, `usage_global` and `versions` keys from the original. In addition, the subset contains the `release_date` key with release dates (as timestamps) for each version: ```json { "release_date": { "6": 998870400, "7": 1161129600, "8": 1237420800, "9": 1300060800, "10": 1346716800, "11": 1381968000, "5.5": 962323200 } } ``` ### `lite.feature(js)` The `feature` method takes a file from `data/features` and converts it into something that more closely represents the `caniuse-db` format. Note that only the `title`, `stats` and `status` keys are kept from the original data. ### `lite.features` The `features` index is provided as a way to query all of the features that are listed in the `caniuse-db` dataset. Note that you will need to use the `feature` method on values from this index to get a human-readable format. ### `lite.region(js)` The `region` method takes a file from `data/regions` and converts it into something that more closely represents the `caniuse-db` format. Note that *only* the usage data is exposed here (the `data` key in the original files). ## Contributors Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --> <!-- prettier-ignore --> | [<img src="https://avatars.githubusercontent.com/u/1282980?v=3" width="100px;"/><br /><sub><b>Ben Briggs</b></sub>](http://beneb.info)<br />[💻](https://github.com/ben-eb/caniuse-lite/commits?author=ben-eb "Code") [📖](https://github.com/ben-eb/caniuse-lite/commits?author=ben-eb "Documentation") [👀](#review-ben-eb "Reviewed Pull Requests") [⚠️](https://github.com/ben-eb/caniuse-lite/commits?author=ben-eb "Tests") | [<img src="https://avatars.githubusercontent.com/u/1737375?v=3" width="100px;"/><br /><sub><b>Andy Jansson</b></sub>](https://github.com/andyjansson)<br />[💻](https://github.com/ben-eb/caniuse-lite/commits?author=andyjansson "Code") | [<img src="https://avatars1.githubusercontent.com/u/19343?v=4" width="100px;"/><br /><sub><b>Andrey Sitnik</b></sub>](http://twitter.com/sitnikcode)<br />[💻](https://github.com/ben-eb/caniuse-lite/commits?author=ai "Code") | [<img src="https://avatars2.githubusercontent.com/u/947326?v=4" width="100px;"/><br /><sub><b>Igor Deryabin</b></sub>](http://rodweb.ru)<br />[💻](https://github.com/ben-eb/caniuse-lite/commits?author=rodweb "Code") | | :---: | :---: | :---: | :---: | <!-- ALL-CONTRIBUTORS-LIST:END --> This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind welcome! <img src="https://opensource.nyc3.digitaloceanspaces.com/attribution/assets/SVG/DO_Logo_icon_blue.svg" alt="Digital Ocean logo" width="40" align="left"> Big thanks to [DigitalOcean](https://www.digitalocean.com/?utm_source=opensource&utm_campaign=caniuse-lite) for supporting this project by providing their great infrastructure for us. ## License The data in this repo is available for use under a CC BY 4.0 license (http://creativecommons.org/licenses/by/4.0/). For attribution just mention somewhere that the source is caniuse.com. If you have any questions about using the data for your project please contact me here: http://a.deveria.com/contact [1]: http://caniuse.com/ [2]: https://github.com/Fyrd/caniuse/issues/1827 semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install --save semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero digit in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # union-value [![NPM version](https://img.shields.io/npm/v/union-value.svg?style=flat)](https://www.npmjs.com/package/union-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/union-value.svg?style=flat)](https://npmjs.org/package/union-value) [![NPM total downloads](https://img.shields.io/npm/dt/union-value.svg?style=flat)](https://npmjs.org/package/union-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/union-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/union-value) > Set an array of unique values as the property of an object. Supports setting deeply nested properties using using object-paths/dot notation. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save union-value ``` ## Usage ```js var union = require('union-value'); var obj = {}; union(obj, 'a.b.c', ['one', 'two']); union(obj, 'a.b.c', ['three']); console.log(obj); //=> {a: {b: {c: [ 'one', 'two', 'three' ] }}} ``` ## About ### Related projects * [assign-value](https://www.npmjs.com/package/assign-value): Assign a value or extend a deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/assign-value) | [homepage](https://github.com/jonschlinkert/assign-value "Assign a value or extend a deeply nested property of an object using object path notation.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value "Returns true if a value exists, false if empty. Works with deeply nested values using object paths.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value "Delete nested properties from an object using dot notation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 25, 2017._ # require-main-filename [![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) [![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) [![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) `require.main.filename` is great for figuring out the entry point for the current application. This can be combined with a module like [pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load top-level configuration. Unfortunately, `require.main.filename` sometimes fails when an application is executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). `require-main-filename` is a shim that addresses this problem. ## Usage ```js var main = require('require-main-filename')() // use main as an alternative to require.main.filename. ``` ## License ISC # process ```require('process');``` just like any other module. Works in node.js and browsers via the browser.js shim provided with the module. ## package manager notes If you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json. See https://gist.github.com/4339901 for details. The [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files. # serve-static [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Linux Build][travis-image]][travis-url] [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url] ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install serve-static ``` ## API <!-- eslint-disable no-unused-vars --> ```js var serveStatic = require('serve-static') ``` ### serveStatic(root, options) Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining `req.url` with the provided root directory. When a file is not found, instead of sending a 404 response, this module will instead call `next()` to move on to the next middleware, allowing for stacking and fall-backs. #### Options ##### acceptRanges Enable or disable accepting ranged requests, defaults to true. Disabling this will not send `Accept-Ranges` and ignore the contents of the `Range` request header. ##### cacheControl Enable or disable setting `Cache-Control` response header, defaults to true. Disabling this will ignore the `immutable` and `maxAge` options. ##### dotfiles Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If `root` is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny"). - `'allow'` No special treatment for dotfiles. - `'deny'` Deny a request for a dotfile and 403/`next()`. - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. The default value is similar to `'ignore'`, with the exception that this default will not ignore the files within a directory that begins with a dot. ##### etag Enable or disable etag generation, defaults to true. ##### extensions Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. The first that exists will be served. Example: `['html', 'htm']`. The default value is `false`. ##### fallthrough Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply `next()` to your next middleware when this value is `true`. When this value is `false`, these errors (even 404s), will invoke `next(err)`. Typically `true` is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files. The value `false` can be used if this middleware is mounted at a path that is designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods. The default value is `true`. ##### immutable Enable or disable the `immutable` directive in the `Cache-Control` response header, defaults to `false`. If set to `true`, the `maxAge` option should also be specified to enable caching. The `immutable` directive will prevent supported clients from making conditional requests during the life of the `maxAge` option to check if the file has changed. ##### index By default this module will send "index.html" files in response to a request on a directory. To disable this set `false` or to supply a new index pass a string or an array in preferred order. ##### lastModified Enable or disable `Last-Modified` header, defaults to true. Uses the file system's last modified value. ##### maxAge Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) module. ##### redirect Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. ##### setHeaders Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called as `fn(res, path, stat)`, where the arguments are: - `res` the response object - `path` the file path that is being sent - `stat` the stat object of the file that is being sent ## Examples ### Serve files with vanilla node.js http server ```js var finalhandler = require('finalhandler') var http = require('http') var serveStatic = require('serve-static') // Serve up public/ftp folder var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) // Create server var server = http.createServer(function onRequest (req, res) { serve(req, res, finalhandler(req, res)) }) // Listen server.listen(3000) ``` ### Serve all files as downloads ```js var contentDisposition = require('content-disposition') var finalhandler = require('finalhandler') var http = require('http') var serveStatic = require('serve-static') // Serve up public/ftp folder var serve = serveStatic('public/ftp', { 'index': false, 'setHeaders': setHeaders }) // Set header to force download function setHeaders (res, path) { res.setHeader('Content-Disposition', contentDisposition(path)) } // Create server var server = http.createServer(function onRequest (req, res) { serve(req, res, finalhandler(req, res)) }) // Listen server.listen(3000) ``` ### Serving using express #### Simple This is a simple example of using Express. ```js var express = require('express') var serveStatic = require('serve-static') var app = express() app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})) app.listen(3000) ``` #### Multiple roots This example shows a simple way to search through multiple directories. Files are look for in `public-optimized/` first, then `public/` second as a fallback. ```js var express = require('express') var path = require('path') var serveStatic = require('serve-static') var app = express() app.use(serveStatic(path.join(__dirname, 'public-optimized'))) app.use(serveStatic(path.join(__dirname, 'public'))) app.listen(3000) ``` #### Different settings for paths This example shows how to set a different max age depending on the served file type. In this example, HTML files are not cached, while everything else is for 1 day. ```js var express = require('express') var path = require('path') var serveStatic = require('serve-static') var app = express() app.use(serveStatic(path.join(__dirname, 'public'), { maxAge: '1d', setHeaders: setCustomCacheControl })) app.listen(3000) function setCustomCacheControl (res, path) { if (serveStatic.mime.lookup(path) === 'text/html') { // Custom Cache-Control for HTML files res.setHeader('Cache-Control', 'public, max-age=0') } } ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/serve-static.svg [npm-url]: https://npmjs.org/package/serve-static [travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux [travis-url]: https://travis-ci.org/expressjs/serve-static [appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-static/master.svg?label=windows [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static [coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-static/master.svg [coveralls-url]: https://coveralls.io/r/expressjs/serve-static [downloads-image]: https://img.shields.io/npm/dm/serve-static.svg [downloads-url]: https://npmjs.org/package/serve-static # is-number [![NPM version](https://img.shields.io/npm/v/is-number.svg?style=flat)](https://www.npmjs.com/package/is-number) [![NPM downloads](https://img.shields.io/npm/dm/is-number.svg?style=flat)](https://npmjs.org/package/is-number) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-number.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-number) > Returns true if the value is a number. comprehensive tests. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-number ``` ## Usage To understand some of the rationale behind the decisions made in this library (and to learn about some oddities of number evaluation in JavaScript), [see this gist](https://gist.github.com/jonschlinkert/e30c70c713da325d0e81). ```js var isNumber = require('is-number'); ``` ### true See the [tests](./test.js) for more examples. ```js isNumber(5e3) //=> 'true' isNumber(0xff) //=> 'true' isNumber(-1.1) //=> 'true' isNumber(0) //=> 'true' isNumber(1) //=> 'true' isNumber(1.1) //=> 'true' isNumber(10) //=> 'true' isNumber(10.10) //=> 'true' isNumber(100) //=> 'true' isNumber('-1.1') //=> 'true' isNumber('0') //=> 'true' isNumber('012') //=> 'true' isNumber('0xff') //=> 'true' isNumber('1') //=> 'true' isNumber('1.1') //=> 'true' isNumber('10') //=> 'true' isNumber('10.10') //=> 'true' isNumber('100') //=> 'true' isNumber('5e3') //=> 'true' isNumber(parseInt('012')) //=> 'true' isNumber(parseFloat('012')) //=> 'true' ``` ### False See the [tests](./test.js) for more examples. ```js isNumber('foo') //=> 'false' isNumber([1]) //=> 'false' isNumber([]) //=> 'false' isNumber(function () {}) //=> 'false' isNumber(Infinity) //=> 'false' isNumber(NaN) //=> 'false' isNumber(new Array('abc')) //=> 'false' isNumber(new Array(2)) //=> 'false' isNumber(new Buffer('abc')) //=> 'false' isNumber(null) //=> 'false' isNumber(undefined) //=> 'false' isNumber({abc: 'abc'}) //=> 'false' ``` ## About ### Related projects * [even](https://www.npmjs.com/package/even): Get the even numbered items from an array. | [homepage](https://github.com/jonschlinkert/even "Get the even numbered items from an array.") * [is-even](https://www.npmjs.com/package/is-even): Return true if the given number is even. | [homepage](https://github.com/jonschlinkert/is-even "Return true if the given number is even.") * [is-odd](https://www.npmjs.com/package/is-odd): Returns true if the given number is odd. | [homepage](https://github.com/jonschlinkert/is-odd "Returns true if the given number is odd.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") * [odd](https://www.npmjs.com/package/odd): Get the odd numbered items from an array. | [homepage](https://github.com/jonschlinkert/odd "Get the odd numbered items from an array.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-number/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.30, on September 10, 2016._ Serialize JavaScript ==================== Serialize JavaScript to a _superset_ of JSON that includes regular expressions, dates and functions. [![npm Version][npm-badge]][npm] [![Dependency Status][david-badge]][david] [![Build Status][travis-badge]][travis] ## Overview The code in this package began its life as an internal module to [express-state][]. To expand its usefulness, it now lives as `serialize-javascript` — an independent package on npm. You're probably wondering: **What about `JSON.stringify()`!?** We've found that sometimes we need to serialize JavaScript **functions**, **regexps** or **dates**. A great example is a web app that uses client-side URL routing where the route definitions are regexps that need to be shared from the server to the client. But this module is also great for communicating between node processes. The string returned from this package's single export function is literal JavaScript which can be saved to a `.js` file, or be embedded into an HTML document by making the content of a `<script>` element. > **HTML characters and JavaScript line terminators are escaped automatically.** ## Installation Install using npm: ```shell $ npm install serialize-javascript ``` ## Usage ```js var serialize = require('serialize-javascript'); serialize({ str : 'string', num : 0, obj : {foo: 'foo'}, arr : [1, 2, 3], bool : true, nil : null, undef: undefined, date: new Date("Thu, 28 Apr 2016 22:02:17 GMT"), fn: function echo(arg) { return arg; }, re: /([^\s]+)/g }); ``` The above will produce the following string output: ```js '{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,date:new Date("2016-04-28T22:02:17.156Z"),"fn":function echo(arg) { return arg; },"re":/([^\\s]+)/g}' ``` Note: to produced a beautified string, you can pass an optional second argument to `serialize()` to define the number of spaces to be used for the indentation. ### Automatic Escaping of HTML Characters A primary feature of this package is to serialize code to a string of literal JavaScript which can be embedded in an HTML document by adding it as the contents of the `<script>` element. In order to make this safe, HTML characters and JavaScript line terminators are escaped automatically. ```js serialize({ haxorXSS: '</script>' }); ``` The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate: ```js '{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}' ``` > You can pass an optional `unsafe` argument to `serialize()` for straight serialization. ### Options The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`: #### `options.space` This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable. ```js serialize(obj, {space: 2}); ``` #### `options.isJSON` This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up. **Note:** That when using this option, the output will still be escaped to protect against XSS. ```js serialize(obj, {isJSON: true}); ``` #### `options.unsafe` This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own. ```js serialize(obj, {unsafe: true}); ``` ## Deserializing For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself: ```js function deserialize(serializedJavascript){ return eval('(' + serializedJavascript + ')'); } ``` **Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body. ## License This software is free to use under the Yahoo! Inc. BSD license. See the [LICENSE file][LICENSE] for license text and copyright information. [npm]: https://www.npmjs.org/package/serialize-javascript [npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square [david]: https://david-dm.org/yahoo/serialize-javascript [david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square [travis]: https://travis-ci.org/yahoo/serialize-javascript [travis-badge]: https://img.shields.io/travis/yahoo/serialize-javascript.svg?style=flat-square [express-state]: https://github.com/yahoo/express-state [JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify [LICENSE]: https://github.com/yahoo/serialize-javascript/blob/master/LICENSE aproba ====== A ridiculously light-weight function argument validator ``` var validate = require("aproba") function myfunc(a, b, c) { // `a` must be a string, `b` a number, `c` a function validate('SNF', arguments) // [a,b,c] is also valid } myfunc('test', 23, function () {}) // ok myfunc(123, 23, function () {}) // type error myfunc('test', 23) // missing arg error myfunc('test', 23, function () {}, true) // too many args error ``` Valid types are: | type | description | :--: | :---------- | * | matches any type | A | `Array.isArray` OR an `arguments` object | S | typeof == string | N | typeof == number | F | typeof == function | O | typeof == object and not type A and not type E | B | typeof == boolean | E | `instanceof Error` OR `null` **(special: see below)** | Z | == `null` Validation failures throw one of three exception types, distinguished by a `code` property of `EMISSINGARG`, `EINVALIDTYPE` or `ETOOMANYARGS`. If you pass in an invalid type then it will throw with a code of `EUNKNOWNTYPE`. If an **error** argument is found and is not null then the remaining arguments are optional. That is, if you say `ESO` then that's like using a non-magical `E` in: `E|ESO|ZSO`. ### But I have optional arguments?! You can provide more than one signature by separating them with pipes `|`. If any signature matches the arguments then they'll be considered valid. So for example, say you wanted to write a signature for `fs.createWriteStream`. The docs for it describe it thusly: ``` fs.createWriteStream(path[, options]) ``` This would be a signature of `SO|S`. That is, a string and and object, or just a string. Now, if you read the full `fs` docs, you'll see that actually path can ALSO be a buffer. And options can be a string, that is: ``` path <String> | <Buffer> options <String> | <Object> ``` To reproduce this you have to fully enumerate all of the possible combinations and that implies a signature of `SO|SS|OO|OS|S|O`. The awkwardness is a feature: It reminds you of the complexity you're adding to your API when you do this sort of thing. ### Browser support This has no dependencies and should work in browsers, though you'll have noisier stack traces. ### Why this exists I wanted a very simple argument validator. It needed to do two things: 1. Be more concise and easier to use than assertions 2. Not encourage an infinite bikeshed of DSLs This is why types are specified by a single character and there's no such thing as an optional argument. This is not intended to validate user data. This is specifically about asserting the interface of your functions. If you need greater validation, I encourage you to write them by hand or look elsewhere. # core-js-pure [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/zloirock/core-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![version](https://img.shields.io/npm/v/core-js-pure.svg)](https://www.npmjs.com/package/core-js-pure) [![npm downloads](https://img.shields.io/npm/dm/core-js-pure.svg)](http://npm-stat.com/charts.html?package=core-js-pure&author=&from=2019-03-18) [![Build Status](https://travis-ci.org/zloirock/core-js.svg)](https://travis-ci.org/zloirock/core-js) [![devDependency status](https://david-dm.org/zloirock/core-js/dev-status.svg)](https://david-dm.org/zloirock/core-js?type=dev) ## As advertising: the author is looking for a good job -) ## [core-js@3, babel and a look into the future](https://github.com/zloirock/core-js/tree/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md) ## Open Collective Sponsors [**Become a sponsor**](https://opencollective.com/core-js#sponsor) and get your logo with a link to your site on our README on GitHub and NPM. <a href="https://opencollective.com/core-js/sponsor/0/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/0/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/1/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/1/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/2/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/2/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/3/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/3/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/4/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/4/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/5/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/5/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/6/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/6/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/7/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/7/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/8/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/8/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/9/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/9/avatar.svg"></a> ## Patreon Sponsors [**Become a sponsor**](https://www.patreon.com/zloirock) and get your logo with a link to your site on our README on GitHub and NPM. --- Modular standard library for JavaScript. Includes polyfills for [ECMAScript up to 2019](https://github.com/zloirock/core-js#ecmascript): [promises](https://github.com/zloirock/core-js#ecmascript-promise), [symbols](https://github.com/zloirock/core-js#ecmascript-symbol), [collections](https://github.com/zloirock/core-js#ecmascript-collections), iterators, [typed arrays](https://github.com/zloirock/core-js#ecmascript-typed-arrays), many other features, [ECMAScript proposals](https://github.com/zloirock/core-js#ecmascript-proposals), [some cross-platform WHATWG / W3C features and proposals](#web-standards) like [`URL`](https://github.com/zloirock/core-js#url-and-urlsearchparams). You can load only required features or use it without global namespace pollution. [*Example*](http://goo.gl/a2xexl): ```js import 'core-js'; // <- at the top of your entry point Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] [1, [2, 3], [4, [5]]].flat(2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` *You can load only required features*: ```js import 'core-js/features/array/from'; // <- at the top of your entry point import 'core-js/features/array/flat'; // <- at the top of your entry point import 'core-js/features/set'; // <- at the top of your entry point import 'core-js/features/promise'; // <- at the top of your entry point Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] [1, [2, 3], [4, [5]]].flat(2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` *Or use it without global namespace pollution*: ```js import from from 'core-js-pure/features/array/from'; import flat from 'core-js-pure/features/array/flat'; import Set from 'core-js-pure/features/set'; import Promise from 'core-js-pure/features/promise'; from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] flat([1, [2, 3], [4, [5]]], 2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` **It's a version without global namespace pollution (the third example), for more info see [`core-js` documentation](https://github.com/zloirock/core-js/blob/master/README.md)**. # psl (Public Suffix List) [![NPM](https://nodei.co/npm/psl.png?downloads=true&downloadRank=true)](https://nodei.co/npm/psl/) [![Greenkeeper badge](https://badges.greenkeeper.io/wrangr/psl.svg)](https://greenkeeper.io/) [![Build Status](https://travis-ci.org/wrangr/psl.svg?branch=master)](https://travis-ci.org/wrangr/psl) [![devDependency Status](https://david-dm.org/wrangr/psl/dev-status.png)](https://david-dm.org/wrangr/psl#info=devDependencies) `psl` is a `JavaScript` domain name parser based on the [Public Suffix List](https://publicsuffix.org/). This implementation is tested against the [test data hosted by Mozilla](http://mxr.mozilla.org/mozilla-central/source/netwerk/test/unit/data/test_psl.txt?raw=1) and kindly provided by [Comodo](https://www.comodo.com/). ## What is the Public Suffix List? The Public Suffix List is a cross-vendor initiative to provide an accurate list of domain name suffixes. The Public Suffix List is an initiative of the Mozilla Project, but is maintained as a community resource. It is available for use in any software, but was originally created to meet the needs of browser manufacturers. A "public suffix" is one under which Internet users can directly register names. Some examples of public suffixes are ".com", ".co.uk" and "pvt.k12.wy.us". The Public Suffix List is a list of all known public suffixes. Source: http://publicsuffix.org ## Installation ### Node.js ```sh npm install --save psl ``` ### Browser Download [psl.min.js](https://raw.githubusercontent.com/wrangr/psl/master/dist/psl.min.js) and include it in a script tag. ```html <script src="psl.min.js"></script> ``` This script is browserified and wrapped in a [umd](https://github.com/umdjs/umd) wrapper so you should be able to use it standalone or together with a module loader. ## API ### `psl.parse(domain)` Parse domain based on Public Suffix List. Returns an `Object` with the following properties: * `tld`: Top level domain (this is the _public suffix_). * `sld`: Second level domain (the first private part of the domain name). * `domain`: The domain name is the `sld` + `tld`. * `subdomain`: Optional parts left of the domain. #### Example: ```js var psl = require('psl'); // Parse domain without subdomain var parsed = psl.parse('google.com'); console.log(parsed.tld); // 'com' console.log(parsed.sld); // 'google' console.log(parsed.domain); // 'google.com' console.log(parsed.subdomain); // null // Parse domain with subdomain var parsed = psl.parse('www.google.com'); console.log(parsed.tld); // 'com' console.log(parsed.sld); // 'google' console.log(parsed.domain); // 'google.com' console.log(parsed.subdomain); // 'www' // Parse domain with nested subdomains var parsed = psl.parse('a.b.c.d.foo.com'); console.log(parsed.tld); // 'com' console.log(parsed.sld); // 'foo' console.log(parsed.domain); // 'foo.com' console.log(parsed.subdomain); // 'a.b.c.d' ``` ### `psl.get(domain)` Get domain name, `sld` + `tld`. Returns `null` if not valid. #### Example: ```js var psl = require('psl'); // null input. psl.get(null); // null // Mixed case. psl.get('COM'); // null psl.get('example.COM'); // 'example.com' psl.get('WwW.example.COM'); // 'example.com' // Unlisted TLD. psl.get('example'); // null psl.get('example.example'); // 'example.example' psl.get('b.example.example'); // 'example.example' psl.get('a.b.example.example'); // 'example.example' // TLD with only 1 rule. psl.get('biz'); // null psl.get('domain.biz'); // 'domain.biz' psl.get('b.domain.biz'); // 'domain.biz' psl.get('a.b.domain.biz'); // 'domain.biz' // TLD with some 2-level rules. psl.get('uk.com'); // null); psl.get('example.uk.com'); // 'example.uk.com'); psl.get('b.example.uk.com'); // 'example.uk.com'); // More complex TLD. psl.get('c.kobe.jp'); // null psl.get('b.c.kobe.jp'); // 'b.c.kobe.jp' psl.get('a.b.c.kobe.jp'); // 'b.c.kobe.jp' psl.get('city.kobe.jp'); // 'city.kobe.jp' psl.get('www.city.kobe.jp'); // 'city.kobe.jp' // IDN labels. psl.get('食狮.com.cn'); // '食狮.com.cn' psl.get('食狮.公司.cn'); // '食狮.公司.cn' psl.get('www.食狮.公司.cn'); // '食狮.公司.cn' // Same as above, but punycoded. psl.get('xn--85x722f.com.cn'); // 'xn--85x722f.com.cn' psl.get('xn--85x722f.xn--55qx5d.cn'); // 'xn--85x722f.xn--55qx5d.cn' psl.get('www.xn--85x722f.xn--55qx5d.cn'); // 'xn--85x722f.xn--55qx5d.cn' ``` ### `psl.isValid(domain)` Check whether a domain has a valid Public Suffix. Returns a `Boolean` indicating whether the domain has a valid Public Suffix. #### Example ```js var psl = require('psl'); psl.isValid('google.com'); // true psl.isValid('www.google.com'); // true psl.isValid('x.yz'); // false ``` ## Testing and Building Test are written using [`mocha`](https://mochajs.org/) and can be run in two different environments: `node` and `phantomjs`. ```sh # This will run `eslint`, `mocha` and `karma`. npm test # Individual test environments # Run tests in node only. ./node_modules/.bin/mocha test # Run tests in phantomjs only. ./node_modules/.bin/karma start ./karma.conf.js --single-run # Build data (parse raw list) and create dist files npm run build ``` Feel free to fork if you see possible improvements! ## Acknowledgements * Mozilla Foundation's [Public Suffix List](https://publicsuffix.org/) * Thanks to Rob Stradling of [Comodo](https://www.comodo.com/) for providing test data. * Inspired by [weppos/publicsuffix-ruby](https://github.com/weppos/publicsuffix-ruby) ## License The MIT License (MIT) Copyright (c) 2017 Lupo Montero <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][npm-url] #### The buffer module from [node.js](https://nodejs.org/), for the browser. [![saucelabs][saucelabs-image]][saucelabs-url] [travis-image]: https://img.shields.io/travis/feross/buffer/master.svg [travis-url]: https://travis-ci.org/feross/buffer [npm-image]: https://img.shields.io/npm/v/buffer.svg [npm-url]: https://npmjs.org/package/buffer [downloads-image]: https://img.shields.io/npm/dm/buffer.svg [saucelabs-image]: https://saucelabs.com/browser-matrix/buffer.svg [saucelabs-url]: https://saucelabs.com/u/buffer With [browserify](http://browserify.org), simply `require('buffer')` or use the `Buffer` global and you will get this module. The goal is to provide an API that is 100% identical to [node's Buffer API](https://nodejs.org/api/buffer.html). Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. ## features - Manipulate binary data like a boss, in all browsers -- even IE6! - Super fast. Backed by Typed Arrays (`Uint8Array`/`ArrayBuffer`, not `Object`) - Extremely small bundle size (**5.04KB minified + gzipped**, 35.5KB with comments) - Excellent browser support (IE 6+, Chrome 4+, Firefox 3+, Safari 5.1+, Opera 11+, iOS, etc.) - Preserves Node API exactly, with one minor difference (see below) - Square-bracket `buf[4]` notation works, even in old browsers like IE6! - Does not modify any browser prototypes or put anything on `window` - Comprehensive test suite (including all buffer tests from node.js core) ## install To use this module directly (without browserify), install it: ```bash npm install buffer ``` This module was previously called **native-buffer-browserify**, but please use **buffer** from now on. A standalone bundle is available [here](https://wzrd.in/standalone/buffer), for non-browserify users. ## usage The module's API is identical to node's `Buffer` API. Read the [official docs](https://nodejs.org/api/buffer.html) for the full list of properties, instance methods, and class methods that are supported. As mentioned above, `require('buffer')` or use the `Buffer` global with [browserify](http://browserify.org) and this module will automatically be included in your bundle. Almost any npm module will work in the browser, even if it assumes that the node `Buffer` API will be available. To depend on this module explicitly (without browserify), require it like this: ```js var Buffer = require('buffer/').Buffer // note: the trailing slash is important! ``` To require this module explicitly, use `require('buffer/')` which tells the node.js module lookup algorithm (also used by browserify) to use the **npm module** named `buffer` instead of the **node.js core** module named `buffer`! ## how does it work? The Buffer constructor returns instances of `Uint8Array` that have their prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of `Uint8Array`, so the returned instances will have all the node `Buffer` methods and the `Uint8Array` methods. Square bracket notation works as expected -- it returns a single octet. The `Uint8Array` prototype remains unmodified. ## one minor difference #### In old browsers, `buf.slice()` does not modify parent buffer's memory If you only support modern browsers (specifically, those with typed array support), then this issue does not affect you. If you support super old browsers, then read on. In node, the `slice()` method returns a new `Buffer` that shares underlying memory with the original Buffer. When you modify one buffer, you modify the other. [Read more.](https://nodejs.org/api/buffer.html#buffer_buf_slice_start_end) In browsers with typed array support, this `Buffer` implementation supports this behavior. In browsers without typed arrays, an alternate buffer implementation is used that is based on `Object` which has no mechanism to point separate `Buffer`s to the same underlying slab of memory. You can see which browser versions lack typed array support [here](https://github.com/feross/buffer/blob/master/index.js#L22-L48). ## tracking the latest node api This module tracks the Buffer API in the latest (unstable) version of node.js. The Buffer API is considered **stable** in the [node stability index](https://nodejs.org/docs/latest/api/documentation.html#documentation_stability_index), so it is unlikely that there will ever be breaking changes. Nonetheless, when/if the Buffer API changes in node, this module's API will change accordingly. ## related packages - [`buffer-equals`](https://www.npmjs.com/package/buffer-equals) - Node.js 0.12 buffer.equals() ponyfill - [`buffer-reverse`](https://www.npmjs.com/package/buffer-reverse) - A lite module for reverse-operations on buffers - [`buffer-xor`](https://www.npmjs.com/package/buffer-xor) - A simple module for bitwise-xor on buffers - [`is-buffer`](https://www.npmjs.com/package/is-buffer) - Determine if an object is a Buffer without including the whole `Buffer` package - [`typedarray-to-buffer`](https://www.npmjs.com/package/typedarray-to-buffer) - Convert a typed array to a Buffer without a copy ## performance See perf tests in `/perf`. `BrowserBuffer` is the browser `buffer` module (this repo). `Uint8Array` is included as a sanity check (since `BrowserBuffer` uses `Uint8Array` under the hood, `Uint8Array` will always be at least a bit faster). Finally, `NodeBuffer` is the node.js buffer module, which is included to compare against. NOTE: Performance has improved since these benchmarks were taken. PR welcoem to update the README. ### Chrome 38 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 11,457,464 ops/sec | ±0.86% | 66 | ✓ | | Uint8Array#bracket-notation | 10,824,332 ops/sec | ±0.74% | 65 | | | | | | | | BrowserBuffer#concat | 450,532 ops/sec | ±0.76% | 68 | | | Uint8Array#concat | 1,368,911 ops/sec | ±1.50% | 62 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 903,001 ops/sec | ±0.96% | 67 | | | Uint8Array#copy(16000) | 1,422,441 ops/sec | ±1.04% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 11,431,358 ops/sec | ±0.46% | 69 | | | Uint8Array#copy(16) | 13,944,163 ops/sec | ±1.12% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 106,329 ops/sec | ±6.70% | 44 | | | Uint8Array#new(16000) | 131,001 ops/sec | ±2.85% | 31 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,554,491 ops/sec | ±1.60% | 65 | | | Uint8Array#new(16) | 6,623,930 ops/sec | ±1.66% | 65 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 112,830 ops/sec | ±0.51% | 69 | ✓ | | DataView#getFloat64 | 93,500 ops/sec | ±0.57% | 68 | | | | | | | | BrowserBuffer#readFloatBE | 146,678 ops/sec | ±0.95% | 68 | ✓ | | DataView#getFloat32 | 99,311 ops/sec | ±0.41% | 67 | | | | | | | | BrowserBuffer#readUInt32LE | 843,214 ops/sec | ±0.70% | 69 | ✓ | | DataView#getUint32 | 103,024 ops/sec | ±0.64% | 67 | | | | | | | | BrowserBuffer#slice | 1,013,941 ops/sec | ±0.75% | 67 | | | Uint8Array#subarray | 1,903,928 ops/sec | ±0.53% | 67 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 61,387 ops/sec | ±0.90% | 67 | | | DataView#setFloat32 | 141,249 ops/sec | ±0.40% | 66 | ✓ | ### Firefox 33 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 20,800,421 ops/sec | ±1.84% | 60 | | | Uint8Array#bracket-notation | 20,826,235 ops/sec | ±2.02% | 61 | ✓ | | | | | | | BrowserBuffer#concat | 153,076 ops/sec | ±2.32% | 61 | | | Uint8Array#concat | 1,255,674 ops/sec | ±8.65% | 52 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,105,312 ops/sec | ±1.16% | 63 | | | Uint8Array#copy(16000) | 1,615,911 ops/sec | ±0.55% | 66 | ✓ | | | | | | | BrowserBuffer#copy(16) | 16,357,599 ops/sec | ±0.73% | 68 | | | Uint8Array#copy(16) | 31,436,281 ops/sec | ±1.05% | 68 | ✓ | | | | | | | BrowserBuffer#new(16000) | 52,995 ops/sec | ±6.01% | 35 | | | Uint8Array#new(16000) | 87,686 ops/sec | ±5.68% | 45 | ✓ | | | | | | | BrowserBuffer#new(16) | 252,031 ops/sec | ±1.61% | 66 | | | Uint8Array#new(16) | 8,477,026 ops/sec | ±0.49% | 68 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 99,871 ops/sec | ±0.41% | 69 | | | DataView#getFloat64 | 285,663 ops/sec | ±0.70% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 115,540 ops/sec | ±0.42% | 69 | | | DataView#getFloat32 | 288,722 ops/sec | ±0.82% | 68 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 633,926 ops/sec | ±1.08% | 67 | ✓ | | DataView#getUint32 | 294,808 ops/sec | ±0.79% | 64 | | | | | | | | BrowserBuffer#slice | 349,425 ops/sec | ±0.46% | 69 | | | Uint8Array#subarray | 5,965,819 ops/sec | ±0.60% | 65 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 59,980 ops/sec | ±0.41% | 67 | | | DataView#setFloat32 | 317,634 ops/sec | ±0.63% | 68 | ✓ | ### Safari 8 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,279,729 ops/sec | ±2.25% | 56 | ✓ | | Uint8Array#bracket-notation | 10,030,767 ops/sec | ±2.23% | 59 | | | | | | | | BrowserBuffer#concat | 144,138 ops/sec | ±1.38% | 65 | | | Uint8Array#concat | 4,950,764 ops/sec | ±1.70% | 63 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 1,058,548 ops/sec | ±1.51% | 64 | | | Uint8Array#copy(16000) | 1,409,666 ops/sec | ±1.17% | 65 | ✓ | | | | | | | BrowserBuffer#copy(16) | 6,282,529 ops/sec | ±1.88% | 58 | | | Uint8Array#copy(16) | 11,907,128 ops/sec | ±2.87% | 58 | ✓ | | | | | | | BrowserBuffer#new(16000) | 101,663 ops/sec | ±3.89% | 57 | | | Uint8Array#new(16000) | 22,050,818 ops/sec | ±6.51% | 46 | ✓ | | | | | | | BrowserBuffer#new(16) | 176,072 ops/sec | ±2.13% | 64 | | | Uint8Array#new(16) | 24,385,731 ops/sec | ±5.01% | 51 | ✓ | | | | | | | BrowserBuffer#readDoubleBE | 41,341 ops/sec | ±1.06% | 67 | | | DataView#getFloat64 | 322,280 ops/sec | ±0.84% | 68 | ✓ | | | | | | | BrowserBuffer#readFloatBE | 46,141 ops/sec | ±1.06% | 65 | | | DataView#getFloat32 | 337,025 ops/sec | ±0.43% | 69 | ✓ | | | | | | | BrowserBuffer#readUInt32LE | 151,551 ops/sec | ±1.02% | 66 | | | DataView#getUint32 | 308,278 ops/sec | ±0.94% | 67 | ✓ | | | | | | | BrowserBuffer#slice | 197,365 ops/sec | ±0.95% | 66 | | | Uint8Array#subarray | 9,558,024 ops/sec | ±3.08% | 58 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 17,518 ops/sec | ±1.03% | 63 | | | DataView#setFloat32 | 319,751 ops/sec | ±0.48% | 68 | ✓ | ### Node 0.11.14 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,489,828 ops/sec | ±3.25% | 90 | | | Uint8Array#bracket-notation | 10,534,884 ops/sec | ±0.81% | 92 | ✓ | | NodeBuffer#bracket-notation | 10,389,910 ops/sec | ±0.97% | 87 | | | | | | | | BrowserBuffer#concat | 487,830 ops/sec | ±2.58% | 88 | | | Uint8Array#concat | 1,814,327 ops/sec | ±1.28% | 88 | ✓ | | NodeBuffer#concat | 1,636,523 ops/sec | ±1.88% | 73 | | | | | | | | BrowserBuffer#copy(16000) | 1,073,665 ops/sec | ±0.77% | 90 | | | Uint8Array#copy(16000) | 1,348,517 ops/sec | ±0.84% | 89 | ✓ | | NodeBuffer#copy(16000) | 1,289,533 ops/sec | ±0.82% | 93 | | | | | | | | BrowserBuffer#copy(16) | 12,782,706 ops/sec | ±0.74% | 85 | | | Uint8Array#copy(16) | 14,180,427 ops/sec | ±0.93% | 92 | ✓ | | NodeBuffer#copy(16) | 11,083,134 ops/sec | ±1.06% | 89 | | | | | | | | BrowserBuffer#new(16000) | 141,678 ops/sec | ±3.30% | 67 | | | Uint8Array#new(16000) | 161,491 ops/sec | ±2.96% | 60 | | | NodeBuffer#new(16000) | 292,699 ops/sec | ±3.20% | 55 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,655,466 ops/sec | ±2.41% | 82 | | | Uint8Array#new(16) | 14,399,926 ops/sec | ±0.91% | 94 | ✓ | | NodeBuffer#new(16) | 3,894,696 ops/sec | ±0.88% | 92 | | | | | | | | BrowserBuffer#readDoubleBE | 109,582 ops/sec | ±0.75% | 93 | ✓ | | DataView#getFloat64 | 91,235 ops/sec | ±0.81% | 90 | | | NodeBuffer#readDoubleBE | 88,593 ops/sec | ±0.96% | 81 | | | | | | | | BrowserBuffer#readFloatBE | 139,854 ops/sec | ±1.03% | 85 | ✓ | | DataView#getFloat32 | 98,744 ops/sec | ±0.80% | 89 | | | NodeBuffer#readFloatBE | 92,769 ops/sec | ±0.94% | 93 | | | | | | | | BrowserBuffer#readUInt32LE | 710,861 ops/sec | ±0.82% | 92 | | | DataView#getUint32 | 117,893 ops/sec | ±0.84% | 91 | | | NodeBuffer#readUInt32LE | 851,412 ops/sec | ±0.72% | 93 | ✓ | | | | | | | BrowserBuffer#slice | 1,673,877 ops/sec | ±0.73% | 94 | | | Uint8Array#subarray | 6,919,243 ops/sec | ±0.67% | 90 | ✓ | | NodeBuffer#slice | 4,617,604 ops/sec | ±0.79% | 93 | | | | | | | | BrowserBuffer#writeFloatBE | 66,011 ops/sec | ±0.75% | 93 | | | DataView#setFloat32 | 127,760 ops/sec | ±0.72% | 93 | ✓ | | NodeBuffer#writeFloatBE | 103,352 ops/sec | ±0.83% | 93 | | ### iojs 1.8.1 | Method | Operations | Accuracy | Sampled | Fastest | |:-------|:-----------|:---------|:--------|:-------:| | BrowserBuffer#bracket-notation | 10,990,488 ops/sec | ±1.11% | 91 | | | Uint8Array#bracket-notation | 11,268,757 ops/sec | ±0.65% | 97 | | | NodeBuffer#bracket-notation | 11,353,260 ops/sec | ±0.83% | 94 | ✓ | | | | | | | BrowserBuffer#concat | 378,954 ops/sec | ±0.74% | 94 | | | Uint8Array#concat | 1,358,288 ops/sec | ±0.97% | 87 | | | NodeBuffer#concat | 1,934,050 ops/sec | ±1.11% | 78 | ✓ | | | | | | | BrowserBuffer#copy(16000) | 894,538 ops/sec | ±0.56% | 84 | | | Uint8Array#copy(16000) | 1,442,656 ops/sec | ±0.71% | 96 | | | NodeBuffer#copy(16000) | 1,457,898 ops/sec | ±0.53% | 92 | ✓ | | | | | | | BrowserBuffer#copy(16) | 12,870,457 ops/sec | ±0.67% | 95 | | | Uint8Array#copy(16) | 16,643,989 ops/sec | ±0.61% | 93 | ✓ | | NodeBuffer#copy(16) | 14,885,848 ops/sec | ±0.74% | 94 | | | | | | | | BrowserBuffer#new(16000) | 109,264 ops/sec | ±4.21% | 63 | | | Uint8Array#new(16000) | 138,916 ops/sec | ±1.87% | 61 | | | NodeBuffer#new(16000) | 281,449 ops/sec | ±3.58% | 51 | ✓ | | | | | | | BrowserBuffer#new(16) | 1,362,935 ops/sec | ±0.56% | 99 | | | Uint8Array#new(16) | 6,193,090 ops/sec | ±0.64% | 95 | ✓ | | NodeBuffer#new(16) | 4,745,425 ops/sec | ±1.56% | 90 | | | | | | | | BrowserBuffer#readDoubleBE | 118,127 ops/sec | ±0.59% | 93 | ✓ | | DataView#getFloat64 | 107,332 ops/sec | ±0.65% | 91 | | | NodeBuffer#readDoubleBE | 116,274 ops/sec | ±0.94% | 95 | | | | | | | | BrowserBuffer#readFloatBE | 150,326 ops/sec | ±0.58% | 95 | ✓ | | DataView#getFloat32 | 110,541 ops/sec | ±0.57% | 98 | | | NodeBuffer#readFloatBE | 121,599 ops/sec | ±0.60% | 87 | | | | | | | | BrowserBuffer#readUInt32LE | 814,147 ops/sec | ±0.62% | 93 | | | DataView#getUint32 | 137,592 ops/sec | ±0.64% | 90 | | | NodeBuffer#readUInt32LE | 931,650 ops/sec | ±0.71% | 96 | ✓ | | | | | | | BrowserBuffer#slice | 878,590 ops/sec | ±0.68% | 93 | | | Uint8Array#subarray | 2,843,308 ops/sec | ±1.02% | 90 | | | NodeBuffer#slice | 4,998,316 ops/sec | ±0.68% | 90 | ✓ | | | | | | | BrowserBuffer#writeFloatBE | 65,927 ops/sec | ±0.74% | 93 | | | DataView#setFloat32 | 139,823 ops/sec | ±0.97% | 89 | ✓ | | NodeBuffer#writeFloatBE | 135,763 ops/sec | ±0.65% | 96 | | | | | | | ## Testing the project First, install the project: npm install Then, to run tests in Node.js, run: npm run test-node To test locally in a browser, you can run: npm run test-browser-local This will print out a URL that you can then open in a browser to run the tests, using [Zuul](https://github.com/defunctzombie/zuul). To run automated browser tests using Saucelabs, ensure that your `SAUCE_USERNAME` and `SAUCE_ACCESS_KEY` environment variables are set, then run: npm test This is what's run in Travis, to check against various browsers. The list of browsers is kept in the `.zuul.yml` file. ## JavaScript Standard Style This module uses [JavaScript Standard Style](https://github.com/feross/standard). [![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) To test that the code conforms to the style, `npm install` and run: ./node_modules/.bin/standard ## credit This was originally forked from [buffer-browserify](https://github.com/toots/buffer-browserify). ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org), and other contributors. Originally forked from an MIT-licensed module by Romain Beauxis. # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # is-descriptor [![NPM version](https://img.shields.io/npm/v/is-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-descriptor) > Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-descriptor ``` ## Usage ```js var isDescriptor = require('is-descriptor'); isDescriptor({value: 'foo'}) //=> true isDescriptor({get: function(){}, set: function(){}}) //=> true isDescriptor({get: 'foo', set: function(){}}) //=> false ``` You may also check for a descriptor by passing an object as the first argument and property name (`string`) as the second argument. ```js var obj = {}; obj.foo = 'abc'; Object.defineProperty(obj, 'bar', { value: 'xyz' }); isDescriptor(obj, 'foo'); //=> true isDescriptor(obj, 'bar'); //=> true ``` ## Examples ### value type `false` when not an object ```js isDescriptor('a'); //=> false isDescriptor(null); //=> false isDescriptor([]); //=> false ``` ### data descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({value: 'foo'}); //=> true isDescriptor({value: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', get: noop}); //=> false isDescriptor({get: noop, value: noop}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({value: 'foo', enumerable: 'foo'}); //=> false isDescriptor({value: 'foo', configurable: 'foo'}); //=> false isDescriptor({value: 'foo', writable: 'foo'}); //=> false ``` ### accessor descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({get: noop, set: noop}); //=> true isDescriptor({get: noop}); //=> true isDescriptor({set: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({get: noop, set: noop, bar: 'baz'}); //=> false isDescriptor({get: noop, writable: true}); //=> false isDescriptor({get: noop, value: true}); //=> false ``` `false` when an accessor is not a function ```js isDescriptor({get: noop, set: 'baz'}); //=> false isDescriptor({get: 'foo', set: noop}); //=> false isDescriptor({get: 'foo', bar: 'baz'}); //=> false isDescriptor({get: 'foo', set: 'baz'}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({get: noop, set: noop, enumerable: 'foo'}); //=> false isDescriptor({set: noop, configurable: 'foo'}); //=> false isDescriptor({get: noop, configurable: 'foo'}); //=> false ``` ## About ### Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 24 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ This folder contains implementations of polyfills. It's not recommended to include in your projects directly if you don't completely understand what are you doing. # ignore-walk [![Build Status](https://travis-ci.org/isaacs/ignore-walk.svg?branch=master)](https://travis-ci.org/isaacs/ignore-walk) Nested/recursive `.gitignore`/`.npmignore` parsing and filtering. Walk a directory creating a list of entries, parsing any `.ignore` files met along the way to exclude files. ## USAGE ```javascript const walk = require('ignore-walk') // All options are optional, defaults provided. // this function returns a promise, but you can also pass a cb // if you like that approach better. walk({ path: '...', // root dir to start in. defaults to process.cwd() ignoreFiles: [ '.gitignore' ], // list of filenames. defaults to ['.ignore'] includeEmpty: true|false, // true to include empty dirs, default false follow: true|false // true to follow symlink dirs, default false }, callback) // to walk synchronously, do it this way: const result = walk.sync({ path: '/wow/such/filepath' }) ``` If you want to get at the underlying classes, they're at `walk.Walker` and `walk.WalkerSync`. ## OPTIONS * `path` The path to start in. Defaults to `process.cwd()` * `ignoreFiles` Filenames to treat as ignore files. The default is `['.ignore']`. (This is where you'd put `.gitignore` or `.npmignore` or whatever.) If multiple ignore files are in a directory, then rules from each are applied in the order that the files are listed. * `includeEmpty` Set to `true` to include empty directories, assuming they are not excluded by any of the ignore rules. If not set, then this follows the standard `git` behavior of not including directories that are empty. Note: this will cause an empty directory to be included if it would contain an included entry, even if it would have otherwise been excluded itself. For example, given the rules `*` (ignore everything) and `!/a/b/c` (re-include the entry at `/a/b/c`), the directory `/a/b` will be included if it is empty. * `follow` Set to `true` to treat symbolically linked directories as directories, recursing into them. There is no handling for nested symlinks, so `ELOOP` errors can occur in some cases when using this option. Defaults to `false`. # pseudomap A thing that is a lot like ES6 `Map`, but without iterators, for use in environments where `for..of` syntax and `Map` are not available. If you need iterators, or just in general a more faithful polyfill to ES6 Maps, check out [es6-map](http://npm.im/es6-map). If you are in an environment where `Map` is supported, then that will be returned instead, unless `process.env.TEST_PSEUDOMAP` is set. You can use any value as keys, and any value as data. Setting again with the identical key will overwrite the previous value. Internally, data is stored on an `Object.create(null)` style object. The key is coerced to a string to generate the key on the internal data-bag object. The original key used is stored along with the data. In the event of a stringified-key collision, a new key is generated by appending an increasing number to the stringified-key until finding either the intended key or an empty spot. Note that because object traversal order of plain objects is not guaranteed to be identical to insertion order, the insertion order guarantee of `Map.prototype.forEach` is not guaranteed in this implementation. However, in all versions of Node.js and V8 where this module works, `forEach` does traverse data in insertion order. ## API Most of the [Map API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), with the following exceptions: 1. A `Map` object is not an iterator. 2. `values`, `keys`, and `entries` methods are not implemented, because they return iterators. 3. The argument to the constructor can be an Array of `[key, value]` pairs, or a `Map` or `PseudoMap` object. But, since iterators aren't used, passing any plain-old iterator won't initialize the map properly. ## USAGE Use just like a regular ES6 Map. ```javascript var PseudoMap = require('pseudomap') // optionally provide a pseudomap, or an array of [key,value] pairs // as the argument to initialize the map with var myMap = new PseudoMap() myMap.set(1, 'number 1') myMap.set('1', 'string 1') var akey = {} var bkey = {} myMap.set(akey, { some: 'data' }) myMap.set(bkey, { some: 'other data' }) ``` This folder contains entry points for [stable ECMAScript features](https://github.com/zloirock/core-js/tree/v3#ecmascript) with dependencies. #define-properties <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] [![browser support][testling-svg]][testling-url] Define multiple non-enumerable properties at once. Uses `Object.defineProperty` when available; falls back to standard assignment in older engines. Existing properties are not overridden. Accepts a map of property names to a predicate that, when true, force-overrides. ## Example ```js var define = require('define-properties'); var assert = require('assert'); var obj = define({ a: 1, b: 2 }, { a: 10, b: 20, c: 30 }); assert(obj.a === 1); assert(obj.b === 2); assert(obj.c === 30); if (define.supportsDescriptors) { assert.deepEqual(Object.keys(obj), ['a', 'b']); assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'c'), { configurable: true, enumerable: false, value: 30, writable: false }); } ``` Then, with predicates: ```js var define = require('define-properties'); var assert = require('assert'); var obj = define({ a: 1, b: 2, c: 3 }, { a: 10, b: 20, c: 30 }, { a: function () { return false; }, b: function () { return true; } }); assert(obj.a === 1); assert(obj.b === 20); assert(obj.c === 3); if (define.supportsDescriptors) { assert.deepEqual(Object.keys(obj), ['a', 'c']); assert.deepEqual(Object.getOwnPropertyDescriptor(obj, 'b'), { configurable: true, enumerable: false, value: 20, writable: false }); } ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/define-properties [npm-version-svg]: http://versionbadg.es/ljharb/define-properties.svg [travis-svg]: https://travis-ci.org/ljharb/define-properties.svg [travis-url]: https://travis-ci.org/ljharb/define-properties [deps-svg]: https://david-dm.org/ljharb/define-properties.svg [deps-url]: https://david-dm.org/ljharb/define-properties [dev-deps-svg]: https://david-dm.org/ljharb/define-properties/dev-status.svg [dev-deps-url]: https://david-dm.org/ljharb/define-properties#info=devDependencies [testling-svg]: https://ci.testling.com/ljharb/define-properties.png [testling-url]: https://ci.testling.com/ljharb/define-properties [npm-badge-png]: https://nodei.co/npm/define-properties.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/define-properties.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/define-properties.svg [downloads-url]: http://npm-stat.com/charts.html?package=define-properties semver(1) -- The semantic versioner for npm =========================================== ## Install ```bash npm install --save semver ```` ## Usage As a node module: ```js const semver = require('semver') semver.valid('1.2.3') // '1.2.3' semver.valid('a.b.c') // null semver.clean(' =v1.2.3 ') // '1.2.3' semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true semver.gt('1.2.3', '9.8.7') // false semver.lt('1.2.3', '9.8.7') // true semver.minVersion('>=1.0.0') // '1.0.0' semver.valid(semver.coerce('v2')) // '2.0.0' semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7' ``` As a command-line utility: ``` $ semver -h A JavaScript implementation of the https://semver.org/ specification Copyright Isaac Z. Schlueter Usage: semver [options] <version> [<version> [...]] Prints valid versions sorted by SemVer precedence Options: -r --range <range> Print versions that match the specified range. -i --increment [<level>] Increment a version by the specified level. Level can be one of: major, minor, patch, premajor, preminor, prepatch, or prerelease. Default level is 'patch'. Only one version may be specified. --preid <identifier> Identifier to be used to prefix premajor, preminor, prepatch or prerelease version increments. -l --loose Interpret versions and ranges loosely -p --include-prerelease Always include prerelease versions in range matching -c --coerce Coerce a string into SemVer if possible (does not imply --loose) Program exits successfully if any valid version satisfies all supplied ranges, and prints all satisfying versions. If no satisfying versions are found, then exits failure. Versions are printed in ascending order, so supplying multiple versions to the utility will just sort them. ``` ## Versions A "version" is described by the `v2.0.0` specification found at <https://semver.org/>. A leading `"="` or `"v"` character is stripped off and ignored. ## Ranges A `version range` is a set of `comparators` which specify versions that satisfy the range. A `comparator` is composed of an `operator` and a `version`. The set of primitive `operators` is: * `<` Less than * `<=` Less than or equal to * `>` Greater than * `>=` Greater than or equal to * `=` Equal. If no operator is specified, then equality is assumed, so this operator is optional, but MAY be included. For example, the comparator `>=1.2.7` would match the versions `1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6` or `1.1.0`. Comparators can be joined by whitespace to form a `comparator set`, which is satisfied by the **intersection** of all of the comparators it includes. A range is composed of one or more comparator sets, joined by `||`. A version matches a range if and only if every comparator in at least one of the `||`-separated comparator sets is satisfied by the version. For example, the range `>=1.2.7 <1.3.0` would match the versions `1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`, or `1.1.0`. The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`, `1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`. ### Prerelease Tags If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then it will only be allowed to satisfy comparator sets if at least one comparator with the same `[major, minor, patch]` tuple also has a prerelease tag. For example, the range `>1.2.3-alpha.3` would be allowed to match the version `1.2.3-alpha.7`, but it would *not* be satisfied by `3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater than" `1.2.3-alpha.3` according to the SemVer sort rules. The version range only accepts prerelease tags on the `1.2.3` version. The version `3.4.5` *would* satisfy the range, because it does not have a prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`. The purpose for this behavior is twofold. First, prerelease versions frequently are updated very quickly, and contain many breaking changes that are (by the author's design) not yet fit for public consumption. Therefore, by default, they are excluded from range matching semantics. Second, a user who has opted into using a prerelease version has clearly indicated the intent to use *that specific* set of alpha/beta/rc versions. By including a prerelease tag in the range, the user is indicating that they are aware of the risk. However, it is still not appropriate to assume that they have opted into taking a similar risk on the *next* set of prerelease versions. Note that this behavior can be suppressed (treating all prerelease versions as if they were normal versions, for the purpose of range matching) by setting the `includePrerelease` flag on the options object to any [functions](https://github.com/npm/node-semver#functions) that do range matching. #### Prerelease Identifiers The method `.inc` takes an additional `identifier` string argument that will append the value of the string as a prerelease identifier: ```javascript semver.inc('1.2.3', 'prerelease', 'beta') // '1.2.4-beta.0' ``` command-line example: ```bash $ semver 1.2.3 -i prerelease --preid beta 1.2.4-beta.0 ``` Which then can be used to increment further: ```bash $ semver 1.2.4-beta.0 -i prerelease 1.2.4-beta.1 ``` ### Advanced Range Syntax Advanced range syntax desugars to primitive comparators in deterministic ways. Advanced ranges may be combined in the same way as primitive comparators using white space or `||`. #### Hyphen Ranges `X.Y.Z - A.B.C` Specifies an inclusive set. * `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` If a partial version is provided as the first version in the inclusive range, then the missing pieces are replaced with zeroes. * `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4` If a partial version is provided as the second version in the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but nothing that would be greater than the provided tuple parts. * `1.2.3 - 2.3` := `>=1.2.3 <2.4.0` * `1.2.3 - 2` := `>=1.2.3 <3.0.0` #### X-Ranges `1.2.x` `1.X` `1.2.*` `*` Any of `X`, `x`, or `*` may be used to "stand in" for one of the numeric values in the `[major, minor, patch]` tuple. * `*` := `>=0.0.0` (Any version satisfies) * `1.x` := `>=1.0.0 <2.0.0` (Matching major version) * `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions) A partial version range is treated as an X-Range, so the special character is in fact optional. * `""` (empty string) := `*` := `>=0.0.0` * `1` := `1.x.x` := `>=1.0.0 <2.0.0` * `1.2` := `1.2.x` := `>=1.2.0 <1.3.0` #### Tilde Ranges `~1.2.3` `~1.2` `~1` Allows patch-level changes if a minor version is specified on the comparator. Allows minor-level changes if not. * `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0` * `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`) * `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`) * `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0` * `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`) * `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`) * `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. #### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4` Allows changes that do not modify the left-most non-zero digit in the `[major, minor, patch]` tuple. In other words, this allows patch and minor updates for versions `1.0.0` and above, patch updates for versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`. Many authors treat a `0.x` version as if the `x` were the major "breaking-change" indicator. Caret ranges are ideal when an author may make breaking changes between `0.2.4` and `0.3.0` releases, which is a common practice. However, it presumes that there will *not* be breaking changes between `0.2.4` and `0.2.5`. It allows for changes that are presumed to be additive (but non-breaking), according to commonly observed practices. * `^1.2.3` := `>=1.2.3 <2.0.0` * `^0.2.3` := `>=0.2.3 <0.3.0` * `^0.0.3` := `>=0.0.3 <0.0.4` * `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in the `1.2.3` version will be allowed, if they are greater than or equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but `1.2.4-beta.2` would not, because it is a prerelease of a different `[major, minor, patch]` tuple. * `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the `0.0.3` version *only* will be allowed, if they are greater than or equal to `beta`. So, `0.0.3-pr.2` would be allowed. When parsing caret ranges, a missing `patch` value desugars to the number `0`, but will allow flexibility within that value, even if the major and minor versions are both `0`. * `^1.2.x` := `>=1.2.0 <2.0.0` * `^0.0.x` := `>=0.0.0 <0.1.0` * `^0.0` := `>=0.0.0 <0.1.0` A missing `minor` and `patch` values will desugar to zero, but also allow flexibility within those values, even if the major version is zero. * `^1.x` := `>=1.0.0 <2.0.0` * `^0.x` := `>=0.0.0 <1.0.0` ### Range Grammar Putting all this together, here is a Backus-Naur grammar for ranges, for the benefit of parser authors: ```bnf range-set ::= range ( logical-or range ) * logical-or ::= ( ' ' ) * '||' ( ' ' ) * range ::= hyphen | simple ( ' ' simple ) * | '' hyphen ::= partial ' - ' partial simple ::= primitive | partial | tilde | caret primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )? xr ::= 'x' | 'X' | '*' | nr nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) * tilde ::= '~' partial caret ::= '^' partial qualifier ::= ( '-' pre )? ( '+' build )? pre ::= parts build ::= parts parts ::= part ( '.' part ) * part ::= nr | [-0-9A-Za-z]+ ``` ## Functions All methods and classes take a final `options` object argument. All options in this object are `false` by default. The options supported are: - `loose` Be more forgiving about not-quite-valid semver strings. (Any resulting output will always be 100% strict compliant, of course.) For backwards compatibility reasons, if the `options` argument is a boolean value instead of an object, it is interpreted to be the `loose` param. - `includePrerelease` Set to suppress the [default behavior](https://github.com/npm/node-semver#prerelease-tags) of excluding prerelease tagged versions from ranges unless they are explicitly opted into. Strict-mode Comparators and Ranges will be strict about the SemVer strings that they parse. * `valid(v)`: Return the parsed version, or null if it's not valid. * `inc(v, release)`: Return the version incremented by the release type (`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`), or null if it's not valid * `premajor` in one call will bump the version up to the next major version and down to a prerelease of that major version. `preminor`, and `prepatch` work the same way. * If called from a non-prerelease version, the `prerelease` will work the same as `prepatch`. It increments the patch version, then makes a prerelease. If the input version is already a prerelease it simply increments it. * `prerelease(v)`: Returns an array of prerelease components, or null if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]` * `major(v)`: Return the major version number. * `minor(v)`: Return the minor version number. * `patch(v)`: Return the patch version number. * `intersects(r1, r2, loose)`: Return true if the two supplied ranges or comparators intersect. * `parse(v)`: Attempt to parse a string as a semantic version, returning either a `SemVer` object or `null`. ### Comparison * `gt(v1, v2)`: `v1 > v2` * `gte(v1, v2)`: `v1 >= v2` * `lt(v1, v2)`: `v1 < v2` * `lte(v1, v2)`: `v1 <= v2` * `eq(v1, v2)`: `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. * `neq(v1, v2)`: `v1 != v2` The opposite of `eq`. * `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call the corresponding function above. `"==="` and `"!=="` do simple string comparison, but are included for completeness. Throws if an invalid comparison string is provided. * `compare(v1, v2)`: Return `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()`. * `rcompare(v1, v2)`: The reverse of compare. Sorts an array of versions in descending order when passed to `Array.sort()`. * `diff(v1, v2)`: 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. ### Comparators * `intersects(comparator)`: Return true if the comparators intersect ### Ranges * `validRange(range)`: Return the valid range or null if it's not valid * `satisfies(version, range)`: Return true if the version satisfies the range. * `maxSatisfying(versions, range)`: Return the highest version in the list that satisfies the range, or `null` if none of them do. * `minSatisfying(versions, range)`: Return the lowest version in the list that satisfies the range, or `null` if none of them do. * `minVersion(range)`: Return the lowest version that can possibly match the given range. * `gtr(version, range)`: Return `true` if version is greater than all the versions possible in the range. * `ltr(version, range)`: Return `true` if version is less than all the versions possible in the range. * `outside(version, range, hilo)`: Return 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`.) * `intersects(range)`: Return true if any of the ranges comparators intersect Note that, since ranges may be non-contiguous, a version might not be greater than a range, less than a range, *or* satisfy a range! For example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` until `2.0.0`, so the version `1.2.10` would not be greater than the range (because `2.0.1` satisfies, which is higher), nor less than the range (since `1.2.8` satisfies, which is lower), and it also does not satisfy the range. If you want to know if a version satisfies or does not satisfy a range, use the `satisfies(version, range)` function. ### Coercion * `coerce(version)`: Coerces a string to semver if possible This aims to provide a very forgiving translation of a non-semver string to semver. It looks for the first digit in a string, and consumes all remaining characters which satisfy at least a partial semver (e.g., `1`, `1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes `3.4.0`). Only text which lacks digits will fail coercion (`version one` is not valid). The maximum length for any semver component considered for coercion is 16 characters; longer components will be ignored (`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value components are invalid (`9999999999999999.4.7.4` is likely invalid). # micromatch [![NPM version](https://img.shields.io/npm/v/micromatch.svg?style=flat)](https://www.npmjs.com/package/micromatch) [![NPM monthly downloads](https://img.shields.io/npm/dm/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![NPM total downloads](https://img.shields.io/npm/dt/micromatch.svg?style=flat)](https://npmjs.org/package/micromatch) [![Linux Build Status](https://img.shields.io/travis/micromatch/micromatch.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/micromatch) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/micromatch.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/micromatch) > Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Table of Contents <details> <summary><strong>Details</strong></summary> - [Install](#install) - [Quickstart](#quickstart) - [Why use micromatch?](#why-use-micromatch) * [Matching features](#matching-features) - [Switching to micromatch](#switching-to-micromatch) * [From minimatch](#from-minimatch) * [From multimatch](#from-multimatch) - [API](#api) - [Options](#options) * [options.basename](#optionsbasename) * [options.bash](#optionsbash) * [options.cache](#optionscache) * [options.dot](#optionsdot) * [options.failglob](#optionsfailglob) * [options.ignore](#optionsignore) * [options.matchBase](#optionsmatchbase) * [options.nobrace](#optionsnobrace) * [options.nocase](#optionsnocase) * [options.nodupes](#optionsnodupes) * [options.noext](#optionsnoext) * [options.nonegate](#optionsnonegate) * [options.noglobstar](#optionsnoglobstar) * [options.nonull](#optionsnonull) * [options.nullglob](#optionsnullglob) * [options.snapdragon](#optionssnapdragon) * [options.sourcemap](#optionssourcemap) * [options.unescape](#optionsunescape) * [options.unixify](#optionsunixify) - [Extended globbing](#extended-globbing) * [extglobs](#extglobs) * [braces](#braces) * [regex character classes](#regex-character-classes) * [regex groups](#regex-groups) * [POSIX bracket expressions](#posix-bracket-expressions) - [Notes](#notes) * [Bash 4.3 parity](#bash-43-parity) * [Backslashes](#backslashes) - [Contributing](#contributing) - [Benchmarks](#benchmarks) * [Running benchmarks](#running-benchmarks) * [Latest results](#latest-results) - [About](#about) </details> ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save micromatch ``` ## Quickstart ```js var mm = require('micromatch'); mm(list, patterns[, options]); ``` The [main export](#micromatch) takes a list of strings and one or more glob patterns: ```js console.log(mm(['foo', 'bar', 'qux'], ['f*', 'b*'])); //=> ['foo', 'bar'] ``` Use [.isMatch()](#ismatch) to get true/false: ```js console.log(mm.isMatch('foo', 'f*')); //=> true ``` [Switching](#switching-to-micromatch) from minimatch and multimatch is easy! ## Why use micromatch? > micromatch is a [drop-in replacement](#switching-to-micromatch) for minimatch and multimatch * Supports all of the same matching features as [minimatch](https://github.com/isaacs/minimatch) and [multimatch](https://github.com/sindresorhus/multimatch) * Micromatch uses [snapdragon](https://github.com/jonschlinkert/snapdragon) for parsing and compiling globs, which provides granular control over the entire conversion process in a way that is easy to understand, reason about, and maintain. * More consistently accurate matching [than minimatch](https://github.com/yarnpkg/yarn/pull/3339), with more than 36,000 [test assertions](./test) to prove it. * More complete support for the Bash 4.3 specification than minimatch and multimatch. In fact, micromatch passes _all of the spec tests_ from bash, including some that bash still fails. * [Faster matching](#benchmarks), from a combination of optimized glob patterns, faster algorithms, and regex caching. * [Micromatch is safer](https://github.com/micromatch/braces#braces-is-safe), and is not subject to DoS with brace patterns, like minimatch and multimatch. * More reliable windows support than minimatch and multimatch. ### Matching features * Support for multiple glob patterns (no need for wrappers like multimatch) * Wildcards (`**`, `*.js`) * Negation (`'!a/*.js'`, `'*!(b).js']`) * [extglobs](https://github.com/micromatch/extglob) (`+(x|y)`, `!(a|b)`) * [POSIX character classes](https://github.com/micromatch/expand-brackets) (`[[:alpha:][:digit:]]`) * [brace expansion](https://github.com/micromatch/braces) (`foo/{1..5}.md`, `bar/{a,b,c}.js`) * regex character classes (`foo-[1-5].js`) * regex logical "or" (`foo/(abc|xyz).js`) You can mix and match these features to create whatever patterns you need! ## Switching to micromatch There is one notable difference between micromatch and minimatch in regards to how backslashes are handled. See [the notes about backslashes](#backslashes) for more information. ### From minimatch Use [mm.isMatch()](#ismatch) instead of `minimatch()`: ```js mm.isMatch('foo', 'b*'); //=> false ``` Use [mm.match()](#match) instead of `minimatch.match()`: ```js mm.match(['foo', 'bar'], 'b*'); //=> 'bar' ``` ### From multimatch Same signature: ```js mm(['foo', 'bar', 'baz'], ['f*', '*z']); //=> ['foo', 'baz'] ``` ## API ### [micromatch](index.js#L41) The main function takes a list of strings and one or more glob patterns to use for matching. **Params** * `list` **{Array}**: A list of strings to match * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of matches **Example** ```js var mm = require('micromatch'); mm(list, patterns[, options]); console.log(mm(['a.js', 'a.txt'], ['*.js'])); //=> [ 'a.js' ] ``` ### [.match](index.js#L93) Similar to the main function, but `pattern` must be a string. **Params** * `list` **{Array}**: Array of strings to match * `pattern` **{String}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of matches **Example** ```js var mm = require('micromatch'); mm.match(list, pattern[, options]); console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); //=> ['a.a', 'a.aa'] ``` ### [.isMatch](index.js#L154) Returns true if the specified `string` matches the given glob `pattern`. **Params** * `string` **{String}**: String to match * `pattern` **{String}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if the string matches the glob pattern. **Example** ```js var mm = require('micromatch'); mm.isMatch(string, pattern[, options]); console.log(mm.isMatch('a.a', '*.a')); //=> true console.log(mm.isMatch('a.b', '*.a')); //=> false ``` ### [.some](index.js#L192) Returns true if some of the strings in the given `list` match any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. Returns as soon as the first match is found. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var mm = require('micromatch'); mm.some(list, patterns[, options]); console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // true console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.every](index.js#L228) Returns true if every string in the given `list` matches any of the given glob `patterns`. **Params** * `list` **{String|Array}**: The string or array of strings to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var mm = require('micromatch'); mm.every(list, patterns[, options]); console.log(mm.every('foo.js', ['foo.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); // true console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); // false console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); // false ``` ### [.any](index.js#L260) Returns true if **any** of the given glob `patterns` match the specified `string`. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var mm = require('micromatch'); mm.any(string, patterns[, options]); console.log(mm.any('a.a', ['b.*', '*.a'])); //=> true console.log(mm.any('a.a', 'b.*')); //=> false ``` ### [.all](index.js#L308) Returns true if **all** of the given `patterns` match the specified string. **Params** * `str` **{String|Array}**: The string to test. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if any patterns match `str` **Example** ```js var mm = require('micromatch'); mm.all(string, patterns[, options]); console.log(mm.all('foo.js', ['foo.js'])); // true console.log(mm.all('foo.js', ['*.js', '!foo.js'])); // false console.log(mm.all('foo.js', ['*.js', 'foo.js'])); // true console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); // true ``` ### [.not](index.js#L340) Returns a list of strings that _**do not match any**_ of the given `patterns`. **Params** * `list` **{Array}**: Array of strings to match. * `patterns` **{String|Array}**: One or more glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Array}**: Returns an array of strings that **do not match** the given patterns. **Example** ```js var mm = require('micromatch'); mm.not(list, patterns[, options]); console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); //=> ['b.b', 'c.c'] ``` ### [.contains](index.js#L376) Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `patterns` **{String|Array}**: Glob pattern to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns true if the patter matches any part of `str`. **Example** ```js var mm = require('micromatch'); mm.contains(string, pattern[, options]); console.log(mm.contains('aa/bb/cc', '*b')); //=> true console.log(mm.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matchKeys](index.js#L432) 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. **Params** * `object` **{Object}**: The object with keys to filter. * `patterns` **{String|Array}**: One or more glob patterns to use for matching. * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Object}**: Returns an object with only keys that match the given patterns. **Example** ```js var mm = require('micromatch'); mm.matchKeys(object, patterns[, options]); var obj = { aa: 'a', ab: 'b', ac: 'c' }; console.log(mm.matchKeys(obj, '*b')); //=> { ab: 'b' } ``` ### [.matcher](index.js#L461) 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. **Params** * `pattern` **{String}**: Glob pattern * `options` **{Object}**: See available [options](#options) for changing how matches are performed. * `returns` **{Function}**: Returns a matcher function. **Example** ```js var mm = require('micromatch'); mm.matcher(pattern[, options]); var isMatch = mm.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.capture](index.js#L536) Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. **Params** * `pattern` **{String}**: Glob pattern to use for matching. * `string` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns an array of captures if the string matches the glob pattern, otherwise `null`. **Example** ```js var mm = require('micromatch'); mm.capture(pattern, string[, options]); console.log(mm.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(mm.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L571) Create a regular expression from the given glob `pattern`. **Params** * `pattern` **{String}**: A glob pattern to convert to regex. * `options` **{Object}**: See available [options](#options) for changing how matches are performed. * `returns` **{RegExp}**: Returns a regex created from the given pattern. **Example** ```js var mm = require('micromatch'); mm.makeRe(pattern[, options]); console.log(mm.makeRe('*.js')); //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ ``` ### [.braces](index.js#L618) Expand the given brace `pattern`. **Params** * `pattern` **{String}**: String with brace pattern to expand. * `options` **{Object}**: Any [options](#options) to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * `returns` **{Array}** **Example** ```js var mm = require('micromatch'); console.log(mm.braces('foo/{a,b}/bar')); //=> ['foo/(a|b)/bar'] console.log(mm.braces('foo/{a,b}/bar', {expand: true})); //=> ['foo/(a|b)/bar'] ``` ### [.create](index.js#L685) 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. **Params** * `pattern` **{String}**: Glob pattern to parse and compile. * `options` **{Object}**: Any [options](#options) to change how parsing and compiling is performed. * `returns` **{Object}**: Returns an object with the parsed AST, compiled string and optional source map. **Example** ```js var mm = require('micromatch'); mm.create(pattern[, options]); console.log(mm.create('abc/*.js')); // [{ options: { source: 'string', sourcemap: true }, // state: {}, // compilers: // { ... }, // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js', // ast: // { type: 'root', // errors: [], // nodes: // [ ... ], // dot: false, // input: 'abc/*.js' }, // parsingErrors: [], // map: // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/*.js' ] }, // position: { line: 1, column: 28 }, // content: {}, // files: {}, // idx: 6 }] ``` ### [.parse](index.js#L732) Parse the given `str` with the given `options`. **Params** * `str` **{String}** * `options` **{Object}** * `returns` **{Object}**: Returns an AST **Example** ```js var mm = require('micromatch'); mm.parse(pattern[, options]); var ast = mm.parse('a/{b,c}/d'); console.log(ast); // { type: 'root', // errors: [], // input: 'a/{b,c}/d', // nodes: // [ { type: 'bos', val: '' }, // { type: 'text', val: 'a/' }, // { type: 'brace', // nodes: // [ { type: 'brace.open', val: '{' }, // { type: 'text', val: 'b,c' }, // { type: 'brace.close', val: '}' } ] }, // { type: 'text', val: '/d' }, // { type: 'eos', val: '' } ] } ``` ### [.compile](index.js#L780) Compile the given `ast` or string with the given `options`. **Params** * `ast` **{Object|String}** * `options` **{Object}** * `returns` **{Object}**: Returns an object that has an `output` property with the compiled string. **Example** ```js var mm = require('micromatch'); mm.compile(ast[, options]); var ast = mm.parse('a/{b,c}/d'); console.log(mm.compile(ast)); // { options: { source: 'string' }, // state: {}, // compilers: // { eos: [Function], // noop: [Function], // bos: [Function], // brace: [Function], // 'brace.open': [Function], // text: [Function], // 'brace.close': [Function] }, // output: [ 'a/(b|c)/d' ], // ast: // { ... }, // parsingErrors: [] } ``` ### [.clearCache](index.js#L801) Clear the regex cache. **Example** ```js mm.clearCache(); ``` ## Options * [basename](#optionsbasename) * [bash](#optionsbash) * [cache](#optionscache) * [dot](#optionsdot) * [failglob](#optionsfailglob) * [ignore](#optionsignore) * [matchBase](#optionsmatchBase) * [nobrace](#optionsnobrace) * [nocase](#optionsnocase) * [nodupes](#optionsnodupes) * [noext](#optionsnoext) * [noglobstar](#optionsnoglobstar) * [nonull](#optionsnonull) * [nullglob](#optionsnullglob) * [snapdragon](#optionssnapdragon) * [sourcemap](#optionssourcemap) * [unescape](#optionsunescape) * [unixify](#optionsunixify) ### options.basename 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`. **Type**: `Boolean` **Default**: `false` **Example** ```js mm(['a/b.js', 'a/c.md'], '*.js'); //=> [] mm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true}); //=> ['a/b.js'] ``` ### options.bash 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. **Type**: `Boolean` **Default**: `true` **Example** ```js var files = ['abc', 'ajz']; console.log(mm(files, '[a-c]*')); //=> ['abc', 'ajz'] console.log(mm(files, '[a-c]*', {bash: false})); ``` ### options.cache Disable regex and function memoization. **Type**: `Boolean` **Default**: `undefined` ### options.dot Match dotfiles. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `dot`. **Type**: `Boolean` **Default**: `false` ### options.failglob Similar to the `--failglob` behavior in Bash, throws an error when no matches are found. **Type**: `Boolean` **Default**: `undefined` ### options.ignore String or array of glob patterns to match files to ignore. **Type**: `String|Array` **Default**: `undefined` ### options.matchBase Alias for [options.basename](#options-basename). ### options.nobrace Disable expansion of brace patterns. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `nobrace`. **Type**: `Boolean` **Default**: `undefined` See [braces](https://github.com/micromatch/braces) for more information about extended brace expansion. ### options.nocase Use a case-insensitive regex for matching files. Same behavior as [minimatch](https://github.com/isaacs/minimatch). **Type**: `Boolean` **Default**: `undefined` ### options.nodupes Remove duplicate elements from the result array. **Type**: `Boolean` **Default**: `undefined` **Example** Example of using the `unescape` and `nodupes` options together: ```js mm.match(['a/b/c', 'a/b/c'], 'a/b/c'); //=> ['a/b/c', 'a/b/c'] mm.match(['a/b/c', 'a/b/c'], 'a/b/c', {nodupes: true}); //=> ['abc'] ``` ### options.noext Disable extglob support, so that extglobs are regarded as literal characters. **Type**: `Boolean` **Default**: `undefined` **Examples** ```js mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)'); //=> ['a/b', 'a/!(z)'] mm(['a/z', 'a/b', 'a/!(z)'], 'a/!(z)', {noext: true}); //=> ['a/!(z)'] (matches only as literal characters) ``` ### options.nonegate Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. **Type**: `Boolean` **Default**: `undefined` ### options.noglobstar Disable matching with globstars (`**`). **Type**: `Boolean` **Default**: `undefined` ```js mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**'); //=> ['a/b', 'a/b/c', 'a/b/c/d'] mm(['a/b', 'a/b/c', 'a/b/c/d'], 'a/**', {noglobstar: true}); //=> ['a/b'] ``` ### options.nonull Alias for [options.nullglob](#options-nullglob). ### options.nullglob 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`. **Type**: `Boolean` **Default**: `undefined` ### options.snapdragon Pass your own instance of [snapdragon](https://github.com/jonschlinkert/snapdragon), to customize parsers or compilers. **Type**: `Object` **Default**: `undefined` ### options.sourcemap 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)_ **Examples** ``` js var mm = require('micromatch'); var pattern = '*(*(of*(a)x)z)'; var res = mm.create('abc/*.js', {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,iBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/*.js' ] } var ast = mm.parse('abc/**/*.js'); var res = mm.compile(ast, {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,GAAG,EAAC,2BAAE,EAAC,iBAAC,EAAC,EAAE', // sourcesContent: [ 'abc/**/*.js' ] } var ast = mm.parse(pattern); var res = mm.compile(ast, {sourcemap: true}); console.log(res.map); // { version: 3, // sources: [ 'string' ], // names: [], // mappings: 'AAAA,CAAE,CAAE,EAAE,CAAE,CAAC,EAAC,CAAC,EAAC,CAAC,EAAC', // sourcesContent: [ '*(*(of*(a)x)z)' ] } ``` ### options.unescape Remove backslashes from returned matches. **Type**: `Boolean` **Default**: `undefined` **Example** In this example we want to match a literal `*`: ```js mm.match(['abc', 'a\\*c'], 'a\\*c'); //=> ['a\\*c'] mm.match(['abc', 'a\\*c'], 'a\\*c', {unescape: true}); //=> ['a*c'] ``` ### options.unixify Convert path separators on returned files to posix/unix-style forward slashes. **Type**: `Boolean` **Default**: `true` on windows, `false` everywhere else **Example** ```js mm.match(['a\\b\\c'], 'a/**'); //=> ['a/b/c'] mm.match(['a\\b\\c'], {unixify: false}); //=> ['a\\b\\c'] ``` ## Extended globbing Micromatch also supports extended globbing features. ### extglobs Extended globbing, as described by the bash man page: | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern)` | `(pattern)?` | Matches zero or one occurrence of the given patterns | | `*(pattern)` | `(pattern)*` | Matches zero or more occurrences of the given patterns | | `+(pattern)` | `(pattern)+` | Matches one or more occurrences of the given patterns | | `@(pattern)` | `(pattern)` <sup>*</sup> | Matches one of the given patterns | | `!(pattern)` | N/A (equivalent regex is much more complicated) | Matches anything except one of the given patterns | <sup><strong>*</strong></sup> Note that `@` isn't a RegEx character. Powered by [extglob](https://github.com/micromatch/extglob). Visit that library for the full range of options or to report extglob related issues. ### braces Brace patterns can be used to match specific ranges or sets of characters. For example, the pattern `*/{1..3}/*` would match any of following strings: ``` foo/1/bar foo/2/bar foo/3/bar baz/1/qux baz/2/qux baz/3/qux ``` Visit [braces](https://github.com/micromatch/braces) to see the full range of features and options related to brace expansion, or to create brace matching or expansion related issues. ### regex character classes Given the list: `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `[ac].js`: matches both `a` and `c`, returning `['a.js', 'c.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `[b-d].js`: matches from `b` to `d`, returning `['b.js', 'c.js', 'd.js']` * `a/[A-Z].js`: matches and uppercase letter, returning `['a/E.md']` Learn about [regex character classes](http://www.regular-expressions.info/charclass.html). ### regex groups Given `['a.js', 'b.js', 'c.js', 'd.js', 'E.js']`: * `(a|c).js`: would match either `a` or `c`, returning `['a.js', 'c.js']` * `(b|d).js`: would match either `b` or `d`, returning `['b.js', 'd.js']` * `(b|[A-Z]).js`: would match either `b` or an uppercase letter, returning `['b.js', 'E.js']` As with regex, parens can be nested, so patterns like `((a|b)|c)/b` will work. Although brace expansion might be friendlier to use, depending on preference. ### POSIX bracket expressions POSIX brackets are intended to be more user-friendly than regex character classes. This of course is in the eye of the beholder. **Example** ```js mm.isMatch('a1', '[[:alpha:][:digit:]]'); //=> true mm.isMatch('a1', '[[:alpha:][:alpha:]]'); //=> false ``` See [expand-brackets](https://github.com/jonschlinkert/expand-brackets) for more information about bracket expressions. *** ## Notes ### Bash 4.3 parity Whenever possible matching behavior is based on behavior Bash 4.3, which is mostly consistent with minimatch. However, it's suprising how many edge cases and rabbit holes there are with glob matching, and since there is no real glob specification, and micromatch is more accurate than both Bash and minimatch, there are cases where best-guesses were made for behavior. In a few cases where Bash had no answers, we used wildmatch (used by git) as a fallback. ### Backslashes There is an important, notable difference between minimatch and micromatch _in regards to how backslashes are handled_ in glob patterns. * Micromatch exclusively and explicitly reserves backslashes for escaping characters in a glob pattern, even on windows. This is consistent with bash behavior. * Minimatch converts all backslashes to forward slashes, which means you can't use backslashes to escape any characters in your glob patterns. We made this decision for micromatch for a couple of reasons: * consistency with bash conventions. * glob patterns are not filepaths. They are a type of [regular language](https://en.wikipedia.org/wiki/Regular_language) that is converted to a JavaScript regular expression. Thus, when forward slashes are defined in a glob pattern, the resulting regular expression will match windows or POSIX path separators just fine. **A note about joining paths to globs** Note that when you pass something like `path.join('foo', '*')` to micromatch, you are creating a filepath and expecting it to still work as a glob pattern. This causes problems on windows, since the `path.sep` is `\\`. In other words, since `\\` is reserved as an escape character in globs, on windows `path.join('foo', '*')` would result in `foo\\*`, which tells micromatch to match `*` as a literal character. This is the same behavior as bash. ## Contributing All contributions are welcome! Please read [the contributing guide](.github/contributing.md) to get started. **Bug reports** Please create an issue if you encounter a bug or matching behavior that doesn't seem correct. If you find a matching-related issue, please: * [research existing issues first](../../issues) (open and closed) * visit the [GNU Bash documentation](https://www.gnu.org/software/bash/manual/) to see how Bash deals with the pattern * visit the [minimatch](https://github.com/isaacs/minimatch) documentation to cross-check expected behavior in node.js * if all else fails, since there is no real specification for globs we will probably need to discuss expected behavior and decide how to resolve it. which means any detail you can provide to help with this discussion would be greatly appreciated. **Platform issues** It's important to us that micromatch work consistently on all platforms. If you encounter any platform-specific matching or path related issues, please let us know (pull requests are also greatly appreciated). ## Benchmarks ### Running benchmarks Install dev dependencies: ```bash npm i -d && npm run benchmark ``` ### Latest results As of February 18, 2018 (longer bars are better): ```sh # braces-globstar-large-list (485691 bytes) micromatch ██████████████████████████████████████████████████ (517 ops/sec ±0.49%) minimatch █ (18.92 ops/sec ±0.54%) multimatch █ (18.94 ops/sec ±0.62%) micromatch is faster by an avg. of 2,733% # braces-multiple (3362 bytes) micromatch ██████████████████████████████████████████████████ (33,625 ops/sec ±0.45%) minimatch (2.92 ops/sec ±3.26%) multimatch (2.90 ops/sec ±2.76%) micromatch is faster by an avg. of 1,156,935% # braces-range (727 bytes) micromatch █████████████████████████████████████████████████ (155,220 ops/sec ±0.56%) minimatch ██████ (20,186 ops/sec ±1.27%) multimatch ██████ (19,809 ops/sec ±0.60%) micromatch is faster by an avg. of 776% # braces-set (2858 bytes) micromatch █████████████████████████████████████████████████ (24,354 ops/sec ±0.92%) minimatch █████ (2,566 ops/sec ±0.56%) multimatch ████ (2,431 ops/sec ±1.25%) micromatch is faster by an avg. of 975% # globstar-large-list (485686 bytes) micromatch █████████████████████████████████████████████████ (504 ops/sec ±0.45%) minimatch ███ (33.36 ops/sec ±1.08%) multimatch ███ (33.19 ops/sec ±1.35%) micromatch is faster by an avg. of 1,514% # globstar-long-list (90647 bytes) micromatch ██████████████████████████████████████████████████ (2,694 ops/sec ±1.08%) minimatch ████████████████ (870 ops/sec ±1.09%) multimatch ████████████████ (862 ops/sec ±0.84%) micromatch is faster by an avg. of 311% # globstar-short-list (182 bytes) micromatch ██████████████████████████████████████████████████ (328,921 ops/sec ±1.06%) minimatch █████████ (64,808 ops/sec ±1.42%) multimatch ████████ (57,991 ops/sec ±2.11%) micromatch is faster by an avg. of 536% # no-glob (701 bytes) micromatch █████████████████████████████████████████████████ (415,935 ops/sec ±0.36%) minimatch ███████████ (92,730 ops/sec ±1.44%) multimatch █████████ (81,958 ops/sec ±2.13%) micromatch is faster by an avg. of 476% # star-basename-long (12339 bytes) micromatch █████████████████████████████████████████████████ (7,963 ops/sec ±0.36%) minimatch ███████████████████████████████ (5,072 ops/sec ±0.83%) multimatch ███████████████████████████████ (5,028 ops/sec ±0.40%) micromatch is faster by an avg. of 158% # star-basename-short (349 bytes) micromatch ██████████████████████████████████████████████████ (269,552 ops/sec ±0.70%) minimatch ██████████████████████ (122,457 ops/sec ±1.39%) multimatch ████████████████████ (110,788 ops/sec ±1.99%) micromatch is faster by an avg. of 231% # star-folder-long (19207 bytes) micromatch █████████████████████████████████████████████████ (3,806 ops/sec ±0.38%) minimatch ████████████████████████████ (2,204 ops/sec ±0.32%) multimatch ██████████████████████████ (2,020 ops/sec ±1.07%) micromatch is faster by an avg. of 180% # star-folder-short (551 bytes) micromatch ██████████████████████████████████████████████████ (249,077 ops/sec ±0.40%) minimatch ███████████ (59,431 ops/sec ±1.67%) multimatch ███████████ (55,569 ops/sec ±1.43%) micromatch is faster by an avg. of 433% ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob… [more](https://github.com/micromatch/extglob) | [homepage](https://github.com/micromatch/extglob "Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns.") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [nanomatch](https://www.npmjs.com/package/nanomatch): Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash… [more](https://github.com/micromatch/nanomatch) | [homepage](https://github.com/micromatch/nanomatch "Fast, minimal glob matcher for node.js. Similar to micromatch, minimatch and multimatch, but complete Bash 4.3 wildcard support only (no support for exglobs, posix brackets or braces)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 457 | [jonschlinkert](https://github.com/jonschlinkert) | | 12 | [es128](https://github.com/es128) | | 8 | [doowb](https://github.com/doowb) | | 3 | [paulmillr](https://github.com/paulmillr) | | 2 | [TrySound](https://github.com/TrySound) | | 2 | [MartinKolarik](https://github.com/MartinKolarik) | | 2 | [charlike-old](https://github.com/charlike-old) | | 1 | [amilajack](https://github.com/amilajack) | | 1 | [mrmlnc](https://github.com/mrmlnc) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [DianeLooney](https://github.com/DianeLooney) | | 1 | [UltCombo](https://github.com/UltCombo) | | 1 | [tomByrer](https://github.com/tomByrer) | | 1 | [fidian](https://github.com/fidian) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 18, 2018._ # is-plain-object [![NPM version](https://img.shields.io/npm/v/is-plain-object.svg?style=flat)](https://www.npmjs.com/package/is-plain-object) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-plain-object.svg?style=flat)](https://npmjs.org/package/is-plain-object) [![NPM total downloads](https://img.shields.io/npm/dt/is-plain-object.svg?style=flat)](https://npmjs.org/package/is-plain-object) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-plain-object.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-plain-object) > Returns true if an object was created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-plain-object ``` Use [isobject](https://github.com/jonschlinkert/isobject) if you only want to check if the value is an object and not an array or null. ## Usage ```js var isPlainObject = require('is-plain-object'); ``` **true** when created by the `Object` constructor. ```js isPlainObject(Object.create({})); //=> true isPlainObject(Object.create(Object.prototype)); //=> true isPlainObject({foo: 'bar'}); //=> true isPlainObject({}); //=> true ``` **false** when not created by the `Object` constructor. ```js isPlainObject(1); //=> false isPlainObject(['foo', 'bar']); //=> false isPlainObject([]); //=> false isPlainObject(new Foo); //=> false isPlainObject(null); //=> false isPlainObject(Object.create(null)); //=> false ``` ## About ### Related projects * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 17 | [jonschlinkert](https://github.com/jonschlinkert) | | 6 | [stevenvachon](https://github.com/stevenvachon) | | 3 | [onokumus](https://github.com/onokumus) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 11, 2017._ # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` aws4 ---- [![Build Status](https://secure.travis-ci.org/mhart/aws4.png?branch=master)](http://travis-ci.org/mhart/aws4) A small utility to sign vanilla node.js http(s) request options using Amazon's [AWS Signature Version 4](http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html). Can also be used [in the browser](./browser). This signature is supported by nearly all Amazon services, including [S3](http://docs.aws.amazon.com/AmazonS3/latest/API/), [EC2](http://docs.aws.amazon.com/AWSEC2/latest/APIReference/), [DynamoDB](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html), [Kinesis](http://docs.aws.amazon.com/kinesis/latest/APIReference/), [Lambda](http://docs.aws.amazon.com/lambda/latest/dg/API_Reference.html), [SQS](http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/), [SNS](http://docs.aws.amazon.com/sns/latest/api/), [IAM](http://docs.aws.amazon.com/IAM/latest/APIReference/), [STS](http://docs.aws.amazon.com/STS/latest/APIReference/), [RDS](http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/), [CloudWatch](http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/), [CloudWatch Logs](http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/), [CodeDeploy](http://docs.aws.amazon.com/codedeploy/latest/APIReference/), [CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/), [CloudTrail](http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/), [ElastiCache](http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/), [EMR](http://docs.aws.amazon.com/ElasticMapReduce/latest/API/), [Glacier](http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-api.html), [CloudSearch](http://docs.aws.amazon.com/cloudsearch/latest/developerguide/APIReq.html), [Elastic Load Balancing](http://docs.aws.amazon.com/ElasticLoadBalancing/latest/APIReference/), [Elastic Transcoder](http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/api-reference.html), [CloudFormation](http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/), [Elastic Beanstalk](http://docs.aws.amazon.com/elasticbeanstalk/latest/api/), [Storage Gateway](http://docs.aws.amazon.com/storagegateway/latest/userguide/AWSStorageGatewayAPI.html), [Data Pipeline](http://docs.aws.amazon.com/datapipeline/latest/APIReference/), [Direct Connect](http://docs.aws.amazon.com/directconnect/latest/APIReference/), [Redshift](http://docs.aws.amazon.com/redshift/latest/APIReference/), [OpsWorks](http://docs.aws.amazon.com/opsworks/latest/APIReference/), [SES](http://docs.aws.amazon.com/ses/latest/APIReference/), [SWF](http://docs.aws.amazon.com/amazonswf/latest/apireference/), [AutoScaling](http://docs.aws.amazon.com/AutoScaling/latest/APIReference/), [Mobile Analytics](http://docs.aws.amazon.com/mobileanalytics/latest/ug/server-reference.html), [Cognito Identity](http://docs.aws.amazon.com/cognitoidentity/latest/APIReference/), [Cognito Sync](http://docs.aws.amazon.com/cognitosync/latest/APIReference/), [Container Service](http://docs.aws.amazon.com/AmazonECS/latest/APIReference/), [AppStream](http://docs.aws.amazon.com/appstream/latest/developerguide/appstream-api-rest.html), [Key Management Service](http://docs.aws.amazon.com/kms/latest/APIReference/), [Config](http://docs.aws.amazon.com/config/latest/APIReference/), [CloudHSM](http://docs.aws.amazon.com/cloudhsm/latest/dg/api-ref.html), [Route53](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rest.html) and [Route53 Domains](http://docs.aws.amazon.com/Route53/latest/APIReference/requests-rpc.html). Indeed, the only AWS services that *don't* support v4 as of 2014-12-30 are [Import/Export](http://docs.aws.amazon.com/AWSImportExport/latest/DG/api-reference.html) and [SimpleDB](http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/SDB_API.html) (they only support [AWS Signature Version 2](https://github.com/mhart/aws2)). It also provides defaults for a number of core AWS headers and request parameters, making it very easy to query AWS services, or build out a fully-featured AWS library. Example ------- ```javascript var http = require('http'), https = require('https'), aws4 = require('aws4') // given an options object you could pass to http.request var opts = {host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues'} // alternatively (as aws4 can infer the host): opts = {service: 'sqs', region: 'us-east-1', path: '/?Action=ListQueues'} // alternatively (as us-east-1 is default): opts = {service: 'sqs', path: '/?Action=ListQueues'} aws4.sign(opts) // assumes AWS credentials are available in process.env console.log(opts) /* { host: 'sqs.us-east-1.amazonaws.com', path: '/?Action=ListQueues', headers: { Host: 'sqs.us-east-1.amazonaws.com', 'X-Amz-Date': '20121226T061030Z', Authorization: 'AWS4-HMAC-SHA256 Credential=ABCDEF/20121226/us-east-1/sqs/aws4_request, ...' } } */ // we can now use this to query AWS using the standard node.js http API http.request(opts, function(res) { res.pipe(process.stdout) }).end() /* <?xml version="1.0"?> <ListQueuesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"> ... */ ``` More options ------------ ```javascript // you can also pass AWS credentials in explicitly (otherwise taken from process.env) aws4.sign(opts, {accessKeyId: '', secretAccessKey: ''}) // can also add the signature to query strings aws4.sign({service: 's3', path: '/my-bucket?X-Amz-Expires=12345', signQuery: true}) // create a utility function to pipe to stdout (with https this time) function request(o) { https.request(o, function(res) { res.pipe(process.stdout) }).end(o.body || '') } // aws4 can infer the HTTP method if a body is passed in // method will be POST and Content-Type: 'application/x-www-form-urlencoded; charset=utf-8' request(aws4.sign({service: 'iam', body: 'Action=ListGroups&Version=2010-05-08'})) /* <ListGroupsResponse xmlns="https://iam.amazonaws.com/doc/2010-05-08/"> ... */ // can specify any custom option or header as per usual request(aws4.sign({ service: 'dynamodb', region: 'ap-southeast-2', method: 'POST', path: '/', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'X-Amz-Target': 'DynamoDB_20120810.ListTables' }, body: '{}' })) /* {"TableNames":[]} ... */ // works with all other services that support Signature Version 4 request(aws4.sign({service: 's3', path: '/', signQuery: true})) /* <ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> ... */ request(aws4.sign({service: 'ec2', path: '/?Action=DescribeRegions&Version=2014-06-15'})) /* <DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2014-06-15/"> ... */ request(aws4.sign({service: 'sns', path: '/?Action=ListTopics&Version=2010-03-31'})) /* <ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"> ... */ request(aws4.sign({service: 'sts', path: '/?Action=GetSessionToken&Version=2011-06-15'})) /* <GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> ... */ request(aws4.sign({service: 'cloudsearch', path: '/?Action=ListDomainNames&Version=2013-01-01'})) /* <ListDomainNamesResponse xmlns="http://cloudsearch.amazonaws.com/doc/2013-01-01/"> ... */ request(aws4.sign({service: 'ses', path: '/?Action=ListIdentities&Version=2010-12-01'})) /* <ListIdentitiesResponse xmlns="http://ses.amazonaws.com/doc/2010-12-01/"> ... */ request(aws4.sign({service: 'autoscaling', path: '/?Action=DescribeAutoScalingInstances&Version=2011-01-01'})) /* <DescribeAutoScalingInstancesResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/"> ... */ request(aws4.sign({service: 'elasticloadbalancing', path: '/?Action=DescribeLoadBalancers&Version=2012-06-01'})) /* <DescribeLoadBalancersResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2012-06-01/"> ... */ request(aws4.sign({service: 'cloudformation', path: '/?Action=ListStacks&Version=2010-05-15'})) /* <ListStacksResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/"> ... */ request(aws4.sign({service: 'elasticbeanstalk', path: '/?Action=ListAvailableSolutionStacks&Version=2010-12-01'})) /* <ListAvailableSolutionStacksResponse xmlns="http://elasticbeanstalk.amazonaws.com/docs/2010-12-01/"> ... */ request(aws4.sign({service: 'rds', path: '/?Action=DescribeDBInstances&Version=2012-09-17'})) /* <DescribeDBInstancesResponse xmlns="http://rds.amazonaws.com/doc/2012-09-17/"> ... */ request(aws4.sign({service: 'monitoring', path: '/?Action=ListMetrics&Version=2010-08-01'})) /* <ListMetricsResponse xmlns="http://monitoring.amazonaws.com/doc/2010-08-01/"> ... */ request(aws4.sign({service: 'redshift', path: '/?Action=DescribeClusters&Version=2012-12-01'})) /* <DescribeClustersResponse xmlns="http://redshift.amazonaws.com/doc/2012-12-01/"> ... */ request(aws4.sign({service: 'cloudfront', path: '/2014-05-31/distribution'})) /* <DistributionList xmlns="http://cloudfront.amazonaws.com/doc/2014-05-31/"> ... */ request(aws4.sign({service: 'elasticache', path: '/?Action=DescribeCacheClusters&Version=2014-07-15'})) /* <DescribeCacheClustersResponse xmlns="http://elasticache.amazonaws.com/doc/2014-07-15/"> ... */ request(aws4.sign({service: 'elasticmapreduce', path: '/?Action=DescribeJobFlows&Version=2009-03-31'})) /* <DescribeJobFlowsResponse xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-03-31"> ... */ request(aws4.sign({service: 'route53', path: '/2013-04-01/hostedzone'})) /* <ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"> ... */ request(aws4.sign({service: 'appstream', path: '/applications'})) /* {"_links":{"curie":[{"href":"http://docs.aws.amazon.com/appstream/latest/... ... */ request(aws4.sign({service: 'cognito-sync', path: '/identitypools'})) /* {"Count":0,"IdentityPoolUsages":[],"MaxResults":16,"NextToken":null} ... */ request(aws4.sign({service: 'elastictranscoder', path: '/2012-09-25/pipelines'})) /* {"NextPageToken":null,"Pipelines":[]} ... */ request(aws4.sign({service: 'lambda', path: '/2014-11-13/functions/'})) /* {"Functions":[],"NextMarker":null} ... */ request(aws4.sign({service: 'ecs', path: '/?Action=ListClusters&Version=2014-11-13'})) /* <ListClustersResponse xmlns="http://ecs.amazonaws.com/doc/2014-11-13/"> ... */ request(aws4.sign({service: 'glacier', path: '/-/vaults', headers: {'X-Amz-Glacier-Version': '2012-06-01'}})) /* {"Marker":null,"VaultList":[]} ... */ request(aws4.sign({service: 'storagegateway', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'StorageGateway_20120630.ListGateways' }})) /* {"Gateways":[]} ... */ request(aws4.sign({service: 'datapipeline', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'DataPipeline.ListPipelines' }})) /* {"hasMoreResults":false,"pipelineIdList":[]} ... */ request(aws4.sign({service: 'opsworks', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'OpsWorks_20130218.DescribeStacks' }})) /* {"Stacks":[]} ... */ request(aws4.sign({service: 'route53domains', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'Route53Domains_v20140515.ListDomains' }})) /* {"Domains":[]} ... */ request(aws4.sign({service: 'kinesis', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'Kinesis_20131202.ListStreams' }})) /* {"HasMoreStreams":false,"StreamNames":[]} ... */ request(aws4.sign({service: 'cloudtrail', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'CloudTrail_20131101.DescribeTrails' }})) /* {"trailList":[]} ... */ request(aws4.sign({service: 'logs', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'Logs_20140328.DescribeLogGroups' }})) /* {"logGroups":[]} ... */ request(aws4.sign({service: 'codedeploy', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'CodeDeploy_20141006.ListApplications' }})) /* {"applications":[]} ... */ request(aws4.sign({service: 'directconnect', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'OvertureService.DescribeConnections' }})) /* {"connections":[]} ... */ request(aws4.sign({service: 'kms', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'TrentService.ListKeys' }})) /* {"Keys":[],"Truncated":false} ... */ request(aws4.sign({service: 'config', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'StarlingDoveService.DescribeDeliveryChannels' }})) /* {"DeliveryChannels":[]} ... */ request(aws4.sign({service: 'cloudhsm', body: '{}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'CloudHsmFrontendService.ListAvailableZones' }})) /* {"AZList":["us-east-1a","us-east-1b","us-east-1c"]} ... */ request(aws4.sign({ service: 'swf', body: '{"registrationStatus":"REGISTERED"}', headers: { 'Content-Type': 'application/x-amz-json-1.0', 'X-Amz-Target': 'SimpleWorkflowService.ListDomains' } })) /* {"domainInfos":[]} ... */ request(aws4.sign({ service: 'cognito-identity', body: '{"MaxResults": 1}', headers: { 'Content-Type': 'application/x-amz-json-1.1', 'X-Amz-Target': 'AWSCognitoIdentityService.ListIdentityPools' } })) /* {"IdentityPools":[]} ... */ request(aws4.sign({ service: 'mobileanalytics', path: '/2014-06-05/events', body: JSON.stringify({events:[{ eventType: 'a', timestamp: new Date().toISOString(), session: {}, }]}), headers: { 'Content-Type': 'application/json', 'X-Amz-Client-Context': JSON.stringify({ client: {client_id: 'a', app_title: 'a'}, custom: {}, env: {platform: 'a'}, services: {}, }), } })) /* (HTTP 202, empty response) */ // Generate CodeCommit Git access password var signer = new aws4.RequestSigner({ service: 'codecommit', host: 'git-codecommit.us-east-1.amazonaws.com', method: 'GIT', path: '/v1/repos/MyAwesomeRepo', }) var password = signer.getDateTime() + 'Z' + signer.signature() ``` API --- ### aws4.sign(requestOptions, [credentials]) This calculates and populates the `Authorization` header of `requestOptions`, and any other necessary AWS headers and/or request options. Returns `requestOptions` as a convenience for chaining. `requestOptions` is an object holding the same options that the node.js [http.request](http://nodejs.org/docs/latest/api/http.html#http_http_request_options_callback) function takes. The following properties of `requestOptions` are used in the signing or populated if they don't already exist: - `hostname` or `host` (will be determined from `service` and `region` if not given) - `method` (will use `'GET'` if not given or `'POST'` if there is a `body`) - `path` (will use `'/'` if not given) - `body` (will use `''` if not given) - `service` (will be calculated from `hostname` or `host` if not given) - `region` (will be calculated from `hostname` or `host` or use `'us-east-1'` if not given) - `headers['Host']` (will use `hostname` or `host` or be calculated if not given) - `headers['Content-Type']` (will use `'application/x-www-form-urlencoded; charset=utf-8'` if not given and there is a `body`) - `headers['Date']` (used to calculate the signature date if given, otherwise `new Date` is used) Your AWS credentials (which can be found in your [AWS console](https://portal.aws.amazon.com/gp/aws/securityCredentials)) can be specified in one of two ways: - As the second argument, like this: ```javascript aws4.sign(requestOptions, { secretAccessKey: "<your-secret-access-key>", accessKeyId: "<your-access-key-id>", sessionToken: "<your-session-token>" }) ``` - From `process.env`, such as this: ``` export AWS_SECRET_ACCESS_KEY="<your-secret-access-key>" export AWS_ACCESS_KEY_ID="<your-access-key-id>" export AWS_SESSION_TOKEN="<your-session-token>" ``` (will also use `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` if available) The `sessionToken` property and `AWS_SESSION_TOKEN` environment variable are optional for signing with [IAM STS temporary credentials](http://docs.aws.amazon.com/STS/latest/UsingSTS/using-temp-creds.html). Installation ------------ With [npm](http://npmjs.org/) do: ``` npm install aws4 ``` Can also be used [in the browser](./browser). Thanks ------ Thanks to [@jed](https://github.com/jed) for his [dynamo-client](https://github.com/jed/dynamo-client) lib where I first committed and subsequently extracted this code. Also thanks to the [official node.js AWS SDK](https://github.com/aws/aws-sdk-js) for giving me a start on implementing the v4 signature. # CSS Modules: Extract Imports [![Build Status](https://travis-ci.org/css-modules/postcss-modules-extract-imports.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-extract-imports) Transforms: ```css :local(.continueButton) { composes: button from "library/button.css"; color: green; } ``` into: ```css :import("library/button.css") { button: __tmp_487387465fczSDGHSABb; } :local(.continueButton) { composes: __tmp_487387465fczSDGHSABb; color: green; } ``` ## Specification - Only a certain whitelist of properties are inspected. Currently, that whitelist is `['composes']` alone. - An extend-import has the following format: ``` composes: className [... className] from "path/to/file.css"; ``` ## Options - `failOnWrongOrder` `bool` generates exception for unpredictable imports order. ```css .aa { composes: b from './b.css'; composes: c from './c.css'; } .bb { /* "b.css" should be before "c.css" in this case */ composes: c from './c.css'; composes: b from './b.css'; } ``` ## Building ``` npm install npm test ``` [![Build Status](https://travis-ci.org/css-modules/postcss-modules-extract-imports.svg?branch=master)](https://travis-ci.org/css-modules/postcss-modules-extract-imports) * Lines: [![Coverage Status](https://coveralls.io/repos/css-modules/postcss-modules-extract-imports/badge.svg?branch=master)](https://coveralls.io/r/css-modules/postcss-modules-extract-imports?branch=master) * Statements: [![codecov.io](http://codecov.io/github/css-modules/postcss-modules-extract-imports/coverage.svg?branch=master)](http://codecov.io/github/css-modules/postcss-modules-extract-imports?branch=master) ## Development - `npm watch` will watch `src` for changes and rebuild - `npm autotest` will watch `src` and `test` for changes and retest ## License ISC ## With thanks - Mark Dalgleish - Tobias Koppers - Guy Bedford --- Glen Maddern, 2015. # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')({ width: 80 }) ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.row`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. # encodeurl [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Encode a URL to a percent-encoded form, excluding already-encoded sequences ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install encodeurl ``` ## API ```js var encodeUrl = require('encodeurl') ``` ### encodeUrl(url) Encode a URL to a percent-encoded form, excluding already-encoded sequences. This function will take an already-encoded URL and encode all the non-URL code points (as UTF-8 byte sequences). This function will not encode the "%" character unless it is not part of a valid sequence (`%20` will be left as-is, but `%foo` will be encoded as `%25foo`). This encode is meant to be "safe" and does not throw errors. It will try as hard as it can to properly encode the given URL, including replacing any raw, unpaired surrogate pairs with the Unicode replacement character prior to encoding. This function is _similar_ to the intrinsic function `encodeURI`, except it will not encode the `%` character if that is part of a valid sequence, will not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired surrogate pairs with the Unicode replacement character (instead of throwing). ## Examples ### Encode a URL containing user-controled data ```js var encodeUrl = require('encodeurl') var escapeHtml = require('escape-html') http.createServer(function onRequest (req, res) { // get encoded form of inbound url var url = encodeUrl(req.url) // create html message var body = '<p>Location ' + escapeHtml(url) + ' not found</p>' // send a 404 res.statusCode = 404 res.setHeader('Content-Type', 'text/html; charset=UTF-8') res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) res.end(body, 'utf-8') }) ``` ### Encode a URL for use in a header field ```js var encodeUrl = require('encodeurl') var escapeHtml = require('escape-html') var url = require('url') http.createServer(function onRequest (req, res) { // parse inbound url var href = url.parse(req) // set new host for redirect href.host = 'localhost' href.protocol = 'https:' href.slashes = true // create location header var location = encodeUrl(url.format(href)) // create html message var body = '<p>Redirecting to new site: ' + escapeHtml(location) + '</p>' // send a 301 res.statusCode = 301 res.setHeader('Content-Type', 'text/html; charset=UTF-8') res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) res.setHeader('Location', location) res.end(body, 'utf-8') }) ``` ## Testing ```sh $ npm test $ npm run lint ``` ## References - [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] - [WHATWG URL Living Standard][whatwg-url] [rfc-3986]: https://tools.ietf.org/html/rfc3986 [whatwg-url]: https://url.spec.whatwg.org/ ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/encodeurl.svg [npm-url]: https://npmjs.org/package/encodeurl [node-version-image]: https://img.shields.io/node/v/encodeurl.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg [travis-url]: https://travis-ci.org/pillarjs/encodeurl [coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg [coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master [downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg [downloads-url]: https://npmjs.org/package/encodeurl # process ```require('process');``` just like any other module. Works in node.js and browsers via the browser.js shim provided with the module. ## browser implementation The goal of this module is not to be a full-fledged alternative to the builtin process module. This module mostly exists to provide the nextTick functionality and little more. We keep this module lean because it will often be included by default by tools like browserify when it detects a module has used the `process` global. It also exposes a "browser" member (i.e. `process.browser`) which is `true` in this implementation but `undefined` in node. This can be used in isomorphic code that adjusts it's behavior depending on which environment it's running in. If you are looking to provide other process methods, I suggest you monkey patch them onto the process global in your app. A list of user created patches is below. * [hrtime](https://github.com/kumavis/browser-process-hrtime) * [stdout](https://github.com/kumavis/browser-stdout) ## package manager notes If you are writing a bundler to package modules for client side use, make sure you use the ```browser``` field hint in package.json. See https://gist.github.com/4339901 for details. The [browserify](https://github.com/substack/node-browserify) module will properly handle this field when bundling your files. # emojis-list [![Dependency status](http://img.shields.io/david/Kikobeats/emojis-list.svg?style=flat-square)](https://david-dm.org/Kikobeats/emojis-list) [![Dev Dependencies Status](http://img.shields.io/david/dev/Kikobeats/emojis-list.svg?style=flat-square)](https://david-dm.org/Kikobeats/emojis-list#info=devDependencies) [![NPM Status](http://img.shields.io/npm/dm/emojis-list.svg?style=flat-square)](https://www.npmjs.org/package/emojis-list) [![Donate](https://img.shields.io/badge/donate-paypal-blue.svg?style=flat-square)](https://paypal.me/kikobeats) > Complete list of standard Unicode Hex Character Code that represent emojis. **NOTE**: The lists is related with the Unicode Hex Character Code. The representation of the emoji depend of the system. Will be possible that the system don't have all the representations. ## Install ```bash npm install emojis-list --save ``` If you want to use in the browser (powered by [Browserify](http://browserify.org/)): ```bash bower install emojis-list --save ``` and later link in your HTML: ```html <script src="bower_components/emojis-list/dist/emojis-list.js"></script> ``` ## Usage ``` var emojis = require('emojis-list'); console.log(emojis[0]); // => 🀄 ``` ## Related * [emojis-unicode](https://github.com/Kikobeats/emojis-unicode) – Complete list of standard Unicode codes that represent emojis. * [emojis-keywords](https://github.com/Kikobeats/emojis-keywords) – Complete list of am emoji shortcuts. * [is-emoji-keyword](https://github.com/Kikobeats/is-emoji-keyword) – Check if a word is a emoji shortcut. * [is-standard-emoji](https://github.com/kikobeats/is-standard-emoji) – Simply way to check if a emoji is a standard emoji. * [trim-emoji](https://github.com/Kikobeats/trim-emoji) – Deletes ':' from the begin and the end of an emoji shortcut. ## License MIT © [Kiko Beats](http://www.kikobeats.com) # lodash.mergewith v4.6.1 The [Lodash](https://lodash.com/) method `_.mergeWith` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.mergewith ``` In Node.js: ```js var mergeWith = require('lodash.mergewith'); ``` See the [documentation](https://lodash.com/docs#mergeWith) or [package source](https://github.com/lodash/lodash/blob/4.6.1-npm-packages/lodash.mergewith) for more details. # loader-utils ## Methods ### `getOptions` Recommended way to retrieve the options of a loader invocation: ```javascript // inside your loader const options = loaderUtils.getOptions(this); ``` 1. If `this.query` is a string: - Tries to parse the query string and returns a new object - Throws if it's not a valid query string 2. If `this.query` is object-like, it just returns `this.query` 3. In any other case, it just returns `null` **Please note:** The returned `options` object is *read-only*. It may be re-used across multiple invocations. If you pass it on to another library, make sure to make a *deep copy* of it: ```javascript const options = Object.assign( {}, defaultOptions, loaderUtils.getOptions(this) // it is safe to pass null to Object.assign() ); // don't forget nested objects or arrays options.obj = Object.assign({}, options.obj); options.arr = options.arr.slice(); someLibrary(options); ``` [clone](https://www.npmjs.com/package/clone) is a good library to make a deep copy of the options. #### Options as query strings If the loader options have been passed as loader query string (`loader?some&params`), the string is parsed by using [`parseQuery`](#parsequery). ### `parseQuery` Parses a passed string (e.g. `loaderContext.resourceQuery`) as a query string, and returns an object. ``` javascript const params = loaderUtils.parseQuery(this.resourceQuery); // resource: `file?param1=foo` if (params.param1 === "foo") { // do something } ``` The string is parsed like this: ``` text -> Error ? -> {} ?flag -> { flag: true } ?+flag -> { flag: true } ?-flag -> { flag: false } ?xyz=test -> { xyz: "test" } ?xyz=1 -> { xyz: "1" } // numbers are NOT parsed ?xyz[]=a -> { xyz: ["a"] } ?flag1&flag2 -> { flag1: true, flag2: true } ?+flag1,-flag2 -> { flag1: true, flag2: false } ?xyz[]=a,xyz[]=b -> { xyz: ["a", "b"] } ?a%2C%26b=c%2C%26d -> { "a,&b": "c,&d" } ?{data:{a:1},isJSON5:true} -> { data: { a: 1 }, isJSON5: true } ``` ### `stringifyRequest` Turns a request into a string that can be used inside `require()` or `import` while avoiding absolute paths. Use it instead of `JSON.stringify(...)` if you're generating code inside a loader. **Why is this necessary?** Since webpack calculates the hash before module paths are translated into module ids, we must avoid absolute paths to ensure consistent hashes across different compilations. This function: - resolves absolute requests into relative requests if the request and the module are on the same hard drive - replaces `\` with `/` if the request and the module are on the same hard drive - won't change the path at all if the request and the module are on different hard drives - applies `JSON.stringify` to the result ```javascript loaderUtils.stringifyRequest(this, "./test.js"); // "\"./test.js\"" loaderUtils.stringifyRequest(this, ".\\test.js"); // "\"./test.js\"" loaderUtils.stringifyRequest(this, "test"); // "\"test\"" loaderUtils.stringifyRequest(this, "test/lib/index.js"); // "\"test/lib/index.js\"" loaderUtils.stringifyRequest(this, "otherLoader?andConfig!test?someConfig"); // "\"otherLoader?andConfig!test?someConfig\"" loaderUtils.stringifyRequest(this, require.resolve("test")); // "\"../node_modules/some-loader/lib/test.js\"" loaderUtils.stringifyRequest(this, "C:\\module\\test.js"); // "\"../../test.js\"" (on Windows, in case the module and the request are on the same drive) loaderUtils.stringifyRequest(this, "C:\\module\\test.js"); // "\"C:\\module\\test.js\"" (on Windows, in case the module and the request are on different drives) loaderUtils.stringifyRequest(this, "\\\\network-drive\\test.js"); // "\"\\\\network-drive\\\\test.js\"" (on Windows, in case the module and the request are on different drives) ``` ### `urlToRequest` Converts some resource URL to a webpack module request. > i Before call `urlToRequest` you need call `isUrlRequest` to ensure it is requestable url ```javascript const url = "path/to/module.js"; if (loaderUtils.isUrlRequest(url)) { // Logic for requestable url const request = loaderUtils.urlToRequest(url); } else { // Logic for not requestable url } ``` Simple example: ```javascript const url = "path/to/module.js"; const request = loaderUtils.urlToRequest(url); // "./path/to/module.js" ``` #### Module URLs Any URL containing a `~` will be interpreted as a module request. Anything after the `~` will be considered the request path. ```javascript const url = "~path/to/module.js"; const request = loaderUtils.urlToRequest(url); // "path/to/module.js" ``` #### Root-relative URLs URLs that are root-relative (start with `/`) can be resolved relative to some arbitrary path by using the `root` parameter: ```javascript const url = "/path/to/module.js"; const root = "./root"; const request = loaderUtils.urlToRequest(url, root); // "./root/path/to/module.js" ``` To convert a root-relative URL into a module URL, specify a `root` value that starts with `~`: ```javascript const url = "/path/to/module.js"; const root = "~"; const request = loaderUtils.urlToRequest(url, root); // "path/to/module.js" ``` ### `interpolateName` Interpolates a filename template using multiple placeholders and/or a regular expression. The template and regular expression are set as query params called `name` and `regExp` on the current loader's context. ```javascript const interpolatedName = loaderUtils.interpolateName(loaderContext, name, options); ``` The following tokens are replaced in the `name` parameter: * `[ext]` the extension of the resource * `[name]` the basename of the resource * `[path]` the path of the resource relative to the `context` query parameter or option. * `[folder]` the folder of the resource is in. * `[emoji]` a random emoji representation of `options.content` * `[emoji:<length>]` same as above, but with a customizable number of emojis * `[contenthash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md5 hash) * `[<hashType>:contenthash:<digestType>:<length>]` optionally one can configure * other `hashType`s, i. e. `sha1`, `md5`, `sha256`, `sha512` * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64` * and `length` the length in chars * `[hash]` the hash of `options.content` (Buffer) (by default it's the hex digest of the md5 hash) * `[<hashType>:hash:<digestType>:<length>]` optionally one can configure * other `hashType`s, i. e. `sha1`, `md5`, `sha256`, `sha512` * other `digestType`s, i. e. `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64` * and `length` the length in chars * `[N]` the N-th match obtained from matching the current file name against `options.regExp` In loader context `[hash]` and `[contenthash]` are the same, but we recommend using `[contenthash]` for avoid misleading. Examples ``` javascript // loaderContext.resourcePath = "/app/js/javascript.js" loaderUtils.interpolateName(loaderContext, "js/[hash].script.[ext]", { content: ... }); // => js/9473fdd0d880a43c21b7778d34872157.script.js // loaderContext.resourcePath = "/app/js/javascript.js" loaderUtils.interpolateName(loaderContext, "js/[contenthash].script.[ext]", { content: ... }); // => js/9473fdd0d880a43c21b7778d34872157.script.js // loaderContext.resourcePath = "/app/page.html" loaderUtils.interpolateName(loaderContext, "html-[hash:6].html", { content: ... }); // => html-9473fd.html // loaderContext.resourcePath = "/app/flash.txt" loaderUtils.interpolateName(loaderContext, "[hash]", { content: ... }); // => c31e9820c001c9c4a86bce33ce43b679 // loaderContext.resourcePath = "/app/img/image.gif" loaderUtils.interpolateName(loaderContext, "[emoji]", { content: ... }); // => 👍 // loaderContext.resourcePath = "/app/img/image.gif" loaderUtils.interpolateName(loaderContext, "[emoji:4]", { content: ... }); // => 🙍🏢📤🐝 // loaderContext.resourcePath = "/app/img/image.png" loaderUtils.interpolateName(loaderContext, "[sha512:hash:base64:7].[ext]", { content: ... }); // => 2BKDTjl.png // use sha512 hash instead of md5 and with only 7 chars of base64 // loaderContext.resourcePath = "/app/img/myself.png" // loaderContext.query.name = loaderUtils.interpolateName(loaderContext, "picture.png"); // => picture.png // loaderContext.resourcePath = "/app/dir/file.png" loaderUtils.interpolateName(loaderContext, "[path][name].[ext]?[hash]", { content: ... }); // => /app/dir/file.png?9473fdd0d880a43c21b7778d34872157 // loaderContext.resourcePath = "/app/js/page-home.js" loaderUtils.interpolateName(loaderContext, "script-[1].[ext]", { regExp: "page-(.*)\\.js", content: ... }); // => script-home.js ``` ### `getHashDigest` ``` javascript const digestString = loaderUtils.getHashDigest(buffer, hashType, digestType, maxLength); ``` * `buffer` the content that should be hashed * `hashType` one of `sha1`, `md5`, `sha256`, `sha512` or any other node.js supported hash type * `digestType` one of `hex`, `base26`, `base32`, `base36`, `base49`, `base52`, `base58`, `base62`, `base64` * `maxLength` the maximum length in chars ## License MIT (http://www.opensource.org/licenses/mit-license.php) # ajv-keywords Custom JSON-Schema keywords for [Ajv](https://github.com/epoberezkin/ajv) validator [![Build Status](https://travis-ci.org/epoberezkin/ajv-keywords.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv-keywords) [![npm](https://img.shields.io/npm/v/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords) [![npm downloads](https://img.shields.io/npm/dm/ajv-keywords.svg)](https://www.npmjs.com/package/ajv-keywords) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/ajv-keywords/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/ajv-keywords?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv-keywords.svg)](https://greenkeeper.io/) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) ## Contents - [Install](#install) - [Usage](#usage) - [Keywords](#keywords) - [Types](#types) - [typeof](#typeof) - [instanceof](#instanceof) - [Keywords for numbers](#keywords-for-numbers) - [range and exclusiveRange](#range-and-exclusiverange) - [Keywords for strings](#keywords-for-strings) - [regexp](#regexp) - [formatMaximum / formatMinimum and formatExclusiveMaximum / formatExclusiveMinimum](#formatmaximum--formatminimum-and-formatexclusivemaximum--formatexclusiveminimum) - [transform](#transform)<sup>\*</sup> - [Keywords for arrays](#keywords-for-arrays) - [uniqueItemProperties](#uniqueitemproperties) - [Keywords for objects](#keywords-for-objects) - [allRequired](allrequired) - [anyRequired](anyrequired) - [patternRequired](#patternrequired) - [prohibited](#prohibited) - [deepProperties](#deepproperties) - [deepRequired](#deeprequired) - [Compound keywords](#compound-keywords) - [switch](#switch) (deprecated) - [select/selectCases/selectDefault](#selectselectcasesselectdefault) (BETA) - [Keywords for all types](#keywords-for-all-types) - [dynamicDefaults](#dynamicdefaults)<sup>\*</sup> - [License](#license) <sup>\*</sup> - keywords that modify data ## Install ``` npm install ajv-keywords ``` ## Usage To add all available keywords: ```javascript var Ajv = require('ajv'); var ajv = new Ajv; require('ajv-keywords')(ajv); ajv.validate({ instanceof: 'RegExp' }, /.*/); // true ajv.validate({ instanceof: 'RegExp' }, '.*'); // false ``` To add a single keyword: ```javascript require('ajv-keywords')(ajv, 'instanceof'); ``` To add multiple keywords: ```javascript require('ajv-keywords')(ajv, ['typeof', 'instanceof']); ``` To add a single keyword in browser (to avoid adding unused code): ```javascript require('ajv-keywords/keywords/instanceof')(ajv); ``` ## Keywords ### Types #### `typeof` Based on JavaScript `typeof` operation. The value of the keyword should be a string (`"undefined"`, `"string"`, `"number"`, `"object"`, `"function"`, `"boolean"` or `"symbol"`) or array of strings. To pass validation the result of `typeof` operation on the value should be equal to the string (or one of the strings in the array). ``` ajv.validate({ typeof: 'undefined' }, undefined); // true ajv.validate({ typeof: 'undefined' }, null); // false ajv.validate({ typeof: ['undefined', 'object'] }, null); // true ``` #### `instanceof` Based on JavaScript `instanceof` operation. The value of the keyword should be a string (`"Object"`, `"Array"`, `"Function"`, `"Number"`, `"String"`, `"Date"`, `"RegExp"`, `"Promise"` or `"Buffer"`) or array of strings. To pass validation the result of `data instanceof ...` operation on the value should be true: ``` ajv.validate({ instanceof: 'Array' }, []); // true ajv.validate({ instanceof: 'Array' }, {}); // false ajv.validate({ instanceof: ['Array', 'Function'] }, function(){}); // true ``` You can add your own constructor function to be recognised by this keyword: ```javascript function MyClass() {} var instanceofDefinition = require('ajv-keywords').get('instanceof').definition; // or require('ajv-keywords/keywords/instanceof').definition; instanceofDefinition.CONSTRUCTORS.MyClass = MyClass; ajv.validate({ instanceof: 'MyClass' }, new MyClass); // true ``` ### Keywords for numbers #### `range` and `exclusiveRange` Syntax sugar for the combination of minimum and maximum keywords, also fails schema compilation if there are no numbers in the range. The value of this keyword must be the array consisting of two numbers, the second must be greater or equal than the first one. If the validated value is not a number the validation passes, otherwise to pass validation the value should be greater (or equal) than the first number and smaller (or equal) than the second number in the array. If `exclusiveRange` keyword is present in the same schema and its value is true, the validated value must not be equal to the range boundaries. ```javascript var schema = { range: [1, 3] }; ajv.validate(schema, 1); // true ajv.validate(schema, 2); // true ajv.validate(schema, 3); // true ajv.validate(schema, 0.99); // false ajv.validate(schema, 3.01); // false var schema = { range: [1, 3], exclusiveRange: true }; ajv.validate(schema, 1.01); // true ajv.validate(schema, 2); // true ajv.validate(schema, 2.99); // true ajv.validate(schema, 1); // false ajv.validate(schema, 3); // false ``` ### Keywords for strings #### `regexp` This keyword allows to use regular expressions with flags in schemas (the standard `pattern` keyword does not support flags). This keyword applies only to strings. If the data is not a string, the validation succeeds. The value of this keyword can be either a string (the result of `regexp.toString()`) or an object with the properties `pattern` and `flags` (the same strings that should be passed to RegExp constructor). ```javascript var schema = { type: 'object', properties: { foo: { regexp: '/foo/i' }, bar: { regexp: { pattern: 'bar', flags: 'i' } } } }; var validData = { foo: 'Food', bar: 'Barmen' }; var invalidData = { foo: 'fog', bar: 'bad' }; ``` #### `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` These keywords allow to define minimum/maximum constraints when the format keyword defines ordering. These keywords apply only to strings. If the data is not a string, the validation succeeds. The value of keyword `formatMaximum` (`formatMinimum`) should be a string. This value is the maximum (minimum) allowed value for the data to be valid as determined by `format` keyword. If `format` is not present schema compilation will throw exception. When this keyword is added, it defines comparison rules for formats `"date"`, `"time"` and `"date-time"`. Custom formats also can have comparison rules. See [addFormat](https://github.com/epoberezkin/ajv#api-addformat) method. The value of keyword `formatExclusiveMaximum` (`formatExclusiveMinimum`) should be a boolean value. These keyword cannot be used without `formatMaximum` (`formatMinimum`). If this keyword value is equal to `true`, the data to be valid should not be equal to the value in `formatMaximum` (`formatMinimum`) keyword. ```javascript require('ajv-keywords')(ajv, ['formatMinimum', 'formatMaximum']); var schema = { format: 'date', formatMinimum: '2016-02-06', formatMaximum: '2016-12-27', formatExclusiveMaximum: true } var validDataList = ['2016-02-06', '2016-12-26', 1]; var invalidDataList = ['2016-02-05', '2016-12-27', 'abc']; ``` #### `transform` This keyword allows a string to be modified before validation. These keywords apply only to strings. If the data is not a string, the transform is skipped. There are limitation due to how ajv is written: - a stand alone string cannot be transformed. ie `data = 'a'; ajv.validate(schema, data);` - currently cannot work with `ajv-pack` **Supported options:** - `trim`: remove whitespace from start and end - `trimLeft`: remove whitespace from start - `trimRight`: remove whitespace from end - `toLowerCase`: case string to all lower case - `toUpperCase`: case string to all upper case - `toEnumCase`: case string to match case in schema Options are applied in the order they are listed. Note: `toEnumCase` requires that all allowed values are unique when case insensitive. **Example: multiple options** ```javascript require('ajv-keywords')(ajv, ['transform']); var schema = { type: 'array', items: { type:'string', transform:['trim','toLowerCase'] } }; var data = [' MixCase ']; ajv.validate(schema, data); console.log(data); // ['mixcase'] ``` **Example: `enumcase`** ```javascript require('ajv-keywords')(ajv, ['transform']); var schema = { type: 'array', items: { type:'string', transform:['trim','toEnumCase'], enum:['pH'] } }; var data = ['ph',' Ph','PH','pH ']; ajv.validate(schema, data); console.log(data); // ['pH','pH','pH','pH'] ``` ### Keywords for arrays #### `uniqueItemProperties` The keyword allows to check that some properties in array items are unique. This keyword applies only to arrays. If the data is not an array, the validation succeeds. The value of this keyword must be an array of strings - property names that should have unique values across all items. ```javascript var schema = { uniqueItemProperties: [ "id", "name" ] }; var validData = [ { id: 1 }, { id: 2 }, { id: 3 } ]; var invalidData1 = [ { id: 1 }, { id: 1 }, { id: 3 } ]; var invalidData2 = [ { id: 1, name: "taco" }, { id: 2, name: "taco" }, // duplicate "name" { id: 3, name: "salsa" } ]; ``` This keyword is contributed by [@blainesch](https://github.com/blainesch). ### Keywords for objects #### `allRequired` This keyword allows to require the presence of all properties used in `properties` keyword in the same schema object. This keyword applies only to objects. If the data is not an object, the validation succeeds. The value of this keyword must be boolean. If the value of the keyword is `false`, the validation succeeds. If the value of the keyword is `true`, the validation succeeds if the data contains all properties defined in `properties` keyword (in the same schema object). If the `properties` keyword is not present in the same schema object, schema compilation will throw exception. ```javascript var schema = { properties: { foo: {type: 'number'}, bar: {type: 'number'} } allRequired: true }; var validData = { foo: 1, bar: 2 }; var alsoValidData = { foo: 1, bar: 2, baz: 3 }; var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ]; ``` #### `anyRequired` This keyword allows to require the presence of any (at least one) property from the list. This keyword applies only to objects. If the data is not an object, the validation succeeds. The value of this keyword must be an array of strings, each string being a property name. For data object to be valid at least one of the properties in this array should be present in the object. ```javascript var schema = { anyRequired: ['foo', 'bar'] }; var validData = { foo: 1 }; var alsoValidData = { foo: 1, bar: 2 }; var invalidDataList = [ {}, { baz: 3 } ]; ``` __Please note__: By combining `anyRequired` with `maxProperties: 1` you can achieve that exactly one property from the list is required to be present for the data object to pass validation. #### `patternRequired` This keyword allows to require the presence of properties that match some pattern(s). This keyword applies only to objects. If the data is not an object, the validation succeeds. The value of this keyword should be an array of strings, each string being a regular expression. For data object to be valid each regular expression in this array should match at least one property name in the data object. If the array contains multiple regular expressions, more than one expression can match the same property name. ```javascript var schema = { patternRequired: [ 'f.*o', 'b.*r' ] }; var validData = { foo: 1, bar: 2 }; var alsoValidData = { foobar: 3 }; var invalidDataList = [ {}, { foo: 1 }, { bar: 2 } ]; ``` #### `prohibited` This keyword allows to prohibit that any of the properties in the list is present in the object. This keyword applies only to objects. If the data is not an object, the validation succeeds. The value of this keyword should be an array of strings, each string being a property name. For data object to be valid none of the properties in this array should be present in the object. ``` var schema = { prohibited: ['foo', 'bar']}; var validData = { baz: 1 }; var alsoValidData = {}; var invalidDataList = [ { foo: 1 }, { bar: 2 }, { foo: 1, bar: 2} ]; ``` __Please note__: `{prohibited: ['foo', 'bar']}` is equivalent to `{not: {anyRequired: ['foo', 'bar']}}` (i.e. it has the same validation result for any data). #### `deepProperties` This keyword allows to validate deep properties (identified by JSON pointers). This keyword applies only to objects. If the data is not an object, the validation succeeds. The value should be an object, where keys are JSON pointers to the data, starting from the current position in data, and the values are JSON schemas. For data object to be valid the value of each JSON pointer should be valid according to the corresponding schema. ```javascript var schema = { type: 'object', deepProperties: { "/users/1/role": { "enum": ["admin"] } } }; var validData = { users: [ {}, { id: 123, role: 'admin' } ] }; var alsoValidData = { users: { "1": { id: 123, role: 'admin' } } }; var invalidData = { users: [ {}, { id: 123, role: 'user' } ] }; var alsoInvalidData = { users: { "1": { id: 123, role: 'user' } } }; ``` #### `deepRequired` This keyword allows to check that some deep properties (identified by JSON pointers) are available. This keyword applies only to objects. If the data is not an object, the validation succeeds. The value should be an array of JSON pointers to the data, starting from the current position in data. For data object to be valid each JSON pointer should be some existing part of the data. ```javascript var schema = { type: 'object', deepRequired: ["/users/1/role"] }; var validData = { users: [ {}, { id: 123, role: 'admin' } ] }; var invalidData = { users: [ {}, { id: 123 } ] }; ``` See [json-schema-org/json-schema-spec#203](https://github.com/json-schema-org/json-schema-spec/issues/203#issue-197211916) for an example of the equivalent schema without `deepRequired` keyword. ### Compound keywords #### `switch` (deprecated) __Please note__: this keyword is provided to preserve backward compatibility with previous versions of Ajv. It is strongly recommended to use `if`/`then`/`else` keywords instead, as they have been added to the draft-07 of JSON Schema specification. This keyword allows to perform advanced conditional validation. The value of the keyword is the array of if/then clauses. Each clause is the object with the following properties: - `if` (optional) - the value is JSON-schema - `then` (required) - the value is JSON-schema or boolean - `continue` (optional) - the value is boolean The validation process is dynamic; all clauses are executed sequentially in the following way: 1. `if`: 1. `if` property is JSON-schema according to which the data is: 1. valid => go to step 2. 2. invalid => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS. 2. `if` property is absent => go to step 2. 2. `then`: 1. `then` property is `true` or it is JSON-schema according to which the data is valid => go to step 3. 2. `then` property is `false` or it is JSON-schema according to which the data is invalid => the validation of `switch` FAILS. 3. `continue`: 1. `continue` property is `true` => go to the NEXT clause, if this was the last clause the validation of `switch` SUCCEEDS. 2. `continue` property is `false` or absent => validation of `switch` SUCCEEDS. ```javascript require('ajv-keywords')(ajv, 'switch'); var schema = { type: 'array', items: { type: 'integer', 'switch': [ { if: { not: { minimum: 1 } }, then: false }, { if: { maximum: 10 }, then: true }, { if: { maximum: 100 }, then: { multipleOf: 10 } }, { if: { maximum: 1000 }, then: { multipleOf: 100 } }, { then: false } ] } }; var validItems = [1, 5, 10, 20, 50, 100, 200, 500, 1000]; var invalidItems = [1, 0, 2000, 11, 57, 123, 'foo']; ``` The above schema is equivalent to (for example): ```javascript { type: 'array', items: { type: 'integer', if: { minimum: 1, maximum: 10 }, then: true, else: { if: { maximum: 100 }, then: { multipleOf: 10 }, else: { if: { maximum: 1000 }, then: { multipleOf: 100 }, else: false } } } } ``` #### `select`/`selectCases`/`selectDefault` These keywords allow to choose the schema to validate the data based on the value of some property in the validated data. These keywords must be present in the same schema object (`selectDefault` is optional). The value of `select` keyword should be a [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference) that points to any primitive JSON type (string, number, boolean or null) in the data that is validated. You can also use a constant of primitive type as the value of this keyword (e.g., for debugging purposes). The value of `selectCases` keyword must be an object where each property name is a possible string representation of the value of `select` keyword and each property value is a corresponding schema (from draft-06 it can be boolean) that must be used to validate the data. The value of `selectDefault` keyword is a schema (from draft-06 it can be boolean) that must be used to validate the data in case `selectCases` has no key equal to the stringified value of `select` keyword. The validation succeeds in one of the following cases: - the validation of data using selected schema succeeds, - none of the schemas is selected for validation, - the value of select is undefined (no property in the data that the data reference points to). If `select` value (in data) is not a primitive type the validation fails. __Please note__: these keywords require Ajv `$data` option to support [$data reference](https://github.com/epoberezkin/ajv/tree/5.0.2-beta.0#data-reference). ```javascript require('ajv-keywords')(ajv, 'select'); var schema = { type: object, required: ['kind'], properties: { kind: { type: 'string' } }, select: { $data: '0/kind' }, selectCases: { foo: { required: ['foo'], properties: { kind: {}, foo: { type: 'string' } }, additionalProperties: false }, bar: { required: ['bar'], properties: { kind: {}, bar: { type: 'number' } }, additionalProperties: false } }, selectDefault: { propertyNames: { not: { enum: ['foo', 'bar'] } } } }; var validDataList = [ { kind: 'foo', foo: 'any' }, { kind: 'bar', bar: 1 }, { kind: 'anything_else', not_bar_or_foo: 'any value' } ]; var invalidDataList = [ { kind: 'foo' }, // no propery foo { kind: 'bar' }, // no propery bar { kind: 'foo', foo: 'any', another: 'any value' }, // additional property { kind: 'bar', bar: 1, another: 'any value' }, // additional property { kind: 'anything_else', foo: 'any' } // property foo not allowed { kind: 'anything_else', bar: 1 } // property bar not allowed ]; ``` __Please note__: the current implementation is BETA. It does not allow using relative URIs in $ref keywords in schemas in `selectCases` and `selectDefault` that point outside of these schemas. The workaround is to use absolute URIs (that can point to any (sub-)schema added to Ajv, including those inside the current root schema where `select` is used). See [tests](https://github.com/epoberezkin/ajv-keywords/blob/v2.0.0/spec/tests/select.json#L314). ### Keywords for all types #### `dynamicDefaults` This keyword allows to assign dynamic defaults to properties, such as timestamps, unique IDs etc. This keyword only works if `useDefaults` options is used and not inside `anyOf` keywords etc., in the same way as [default keyword treated by Ajv](https://github.com/epoberezkin/ajv#assigning-defaults). The keyword should be added on the object level. Its value should be an object with each property corresponding to a property name, in the same way as in standard `properties` keyword. The value of each property can be: - an identifier of default function (a string) - an object with properties `func` (an identifier) and `args` (an object with parameters that will be passed to this function during schema compilation - see examples). The properties used in `dynamicDefaults` should not be added to `required` keyword (or validation will fail), because unlike `default` this keyword is processed after validation. There are several predefined dynamic default functions: - `"timestamp"` - current timestamp in milliseconds - `"datetime"` - current date and time as string (ISO, valid according to `date-time` format) - `"date"` - current date as string (ISO, valid according to `date` format) - `"time"` - current time as string (ISO, valid according to `time` format) - `"random"` - pseudo-random number in [0, 1) interval - `"randomint"` - pseudo-random integer number. If string is used as a property value, the function will randomly return 0 or 1. If object `{ func: 'randomint', args: { max: N } }` is used then the default will be an integer number in [0, N) interval. - `"seq"` - sequential integer number starting from 0. If string is used as a property value, the default sequence will be used. If object `{ func: 'seq', args: { name: 'foo'} }` is used then the sequence with name `"foo"` will be used. Sequences are global, even if different ajv instances are used. ```javascript var schema = { type: 'object', dynamicDefaults: { ts: 'datetime', r: { func: 'randomint', args: { max: 100 } }, id: { func: 'seq', args: { name: 'id' } } }, properties: { ts: { type: 'string', format: 'date-time' }, r: { type: 'integer', minimum: 0, exclusiveMaximum: 100 }, id: { type: 'integer', minimum: 0 } } }; var data = {}; ajv.validate(data); // true data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 } var data1 = {}; ajv.validate(data1); // true data1; // { ts: '2016-12-01T22:07:29.832Z', r: 68, id: 1 } ajv.validate(data1); // true data1; // didn't change, as all properties were defined ``` When using the `useDefaults` option value `"empty"`, properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. Use the `allOf` [compound keyword](https://github.com/epoberezkin/ajv/blob/master/KEYWORDS.md#compound-keywords) to execute `dynamicDefaults` before validation. ```javascript var schema = { allOf: [ { dynamicDefaults: { ts: 'datetime', r: { func: 'randomint', args: { min: 5, max: 100 } }, id: { func: 'seq', args: { name: 'id' } } } }, { type: 'object', properties: { ts: { type: 'string' }, r: { type: 'number', minimum: 5, exclusiveMaximum: 100 }, id: { type: 'integer', minimum: 0 } } } ] }; var data = { ts: '', r: null }; ajv.validate(data); // true data; // { ts: '2016-12-01T22:07:28.829Z', r: 25, id: 0 } ``` You can add your own dynamic default function to be recognised by this keyword: ```javascript var uuid = require('uuid'); function uuidV4() { return uuid.v4(); } var definition = require('ajv-keywords').get('dynamicDefaults').definition; // or require('ajv-keywords/keywords/dynamicDefaults').definition; definition.DEFAULTS.uuid = uuidV4; var schema = { dynamicDefaults: { id: 'uuid' }, properties: { id: { type: 'string', format: 'uuid' } } }; var data = {}; ajv.validate(schema, data); // true data; // { id: 'a1183fbe-697b-4030-9bcc-cfeb282a9150' }; var data1 = {}; ajv.validate(schema, data1); // true data1; // { id: '5b008de7-1669-467a-a5c6-70fa244d7209' } ``` You also can define dynamic default that accepts parameters, e.g. version of uuid: ```javascript var uuid = require('uuid'); function getUuid(args) { var version = 'v' + (arvs && args.v || 4); return function() { return uuid[version](); }; } var definition = require('ajv-keywords').get('dynamicDefaults').definition; definition.DEFAULTS.uuid = getUuid; var schema = { dynamicDefaults: { id1: 'uuid', // v4 id2: { func: 'uuid', v: 4 }, // v4 id3: { func: 'uuid', v: 1 } // v1 } }; ``` ## License [MIT](https://github.com/epoberezkin/ajv-keywords/blob/master/LICENSE) # node-tar [![Build Status](https://travis-ci.org/npm/node-tar.svg?branch=master)](https://travis-ci.org/npm/node-tar) [Fast](./benchmarks) and full-featured Tar for Node.js The API is designed to mimic the behavior of `tar(1)` on unix systems. If you are familiar with how tar works, most of this will hopefully be straightforward for you. If not, then hopefully this module can teach you useful unix skills that may come in handy someday :) ## Background A "tar file" or "tarball" is an archive of file system entries (directories, files, links, etc.) The name comes from "tape archive". If you run `man tar` on almost any Unix command line, you'll learn quite a bit about what it can do, and its history. Tar has 5 main top-level commands: * `c` Create an archive * `r` Replace entries within an archive * `u` Update entries within an archive (ie, replace if they're newer) * `t` List out the contents of an archive * `x` Extract an archive to disk The other flags and options modify how this top level function works. ## High-Level API These 5 functions are the high-level API. All of them have a single-character name (for unix nerds familiar with `tar(1)`) as well as a long name (for everyone else). All the high-level functions take the following arguments, all three of which are optional and may be omitted. 1. `options` - An optional object specifying various options 2. `paths` - An array of paths to add or extract 3. `callback` - Called when the command is completed, if async. (If sync or no file specified, providing a callback throws a `TypeError`.) If the command is sync (ie, if `options.sync=true`), then the callback is not allowed, since the action will be completed immediately. If a `file` argument is specified, and the command is async, then a `Promise` is returned. In this case, if async, a callback may be provided which is called when the command is completed. If a `file` option is not specified, then a stream is returned. For `create`, this is a readable stream of the generated archive. For `list` and `extract` this is a writable stream that an archive should be written into. If a file is not specified, then a callback is not allowed, because you're already getting a stream to work with. `replace` and `update` only work on existing archives, and so require a `file` argument. Sync commands without a file argument return a stream that acts on its input immediately in the same tick. For readable streams, this means that all of the data is immediately available by calling `stream.read()`. For writable streams, it will be acted upon as soon as it is provided, but this can be at any time. ### Warnings Some things cause tar to emit a warning, but should usually not cause the entire operation to fail. There are three ways to handle warnings: 1. **Ignore them** (default) Invalid entries won't be put in the archive, and invalid entries won't be unpacked. This is usually fine, but can hide failures that you might care about. 2. **Notice them** Add an `onwarn` function to the options, or listen to the `'warn'` event on any tar stream. The function will get called as `onwarn(message, data)`. Handle as appropriate. 3. **Explode them.** Set `strict: true` in the options object, and `warn` messages will be emitted as `'error'` events instead. If there's no `error` handler, this causes the program to crash. If used with a promise-returning/callback-taking method, then it'll send the error to the promise/callback. ### Examples The API mimics the `tar(1)` command line functionality, with aliases for more human-readable option and function names. The goal is that if you know how to use `tar(1)` in Unix, then you know how to use `require('tar')` in JavaScript. To replicate `tar czf my-tarball.tgz files and folders`, you'd do: ```js tar.c( { gzip: <true|gzip options>, file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` To replicate `tar cz files and folders > my-tarball.tgz`, you'd do: ```js tar.c( // or tar.create { gzip: <true|gzip options> }, ['some', 'files', 'and', 'folders'] ).pipe(fs.createWriteStream('my-tarball.tgz')) ``` To replicate `tar xf my-tarball.tgz` you'd do: ```js tar.x( // or tar.extract( { file: 'my-tarball.tgz' } ).then(_=> { .. tarball has been dumped in cwd .. }) ``` To replicate `cat my-tarball.tgz | tar x -C some-dir --strip=1`: ```js fs.createReadStream('my-tarball.tgz').pipe( tar.x({ strip: 1, C: 'some-dir' // alias for cwd:'some-dir', also ok }) ) ``` To replicate `tar tf my-tarball.tgz`, do this: ```js tar.t({ file: 'my-tarball.tgz', onentry: entry => { .. do whatever with it .. } }) ``` To replicate `cat my-tarball.tgz | tar t` do: ```js fs.createReadStream('my-tarball.tgz') .pipe(tar.t()) .on('entry', entry => { .. do whatever with it .. }) ``` To do anything synchronous, add `sync: true` to the options. Note that sync functions don't take a callback and don't return a promise. When the function returns, it's already done. Sync methods without a file argument return a sync stream, which flushes immediately. But, of course, it still won't be done until you `.end()` it. To filter entries, add `filter: <function>` to the options. Tar-creating methods call the filter with `filter(path, stat)`. Tar-reading methods (including extraction) call the filter with `filter(path, entry)`. The filter is called in the `this`-context of the `Pack` or `Unpack` stream object. The arguments list to `tar t` and `tar x` specify a list of filenames to extract or list, so they're equivalent to a filter that tests if the file is in the list. For those who _aren't_ fans of tar's single-character command names: ``` tar.c === tar.create tar.r === tar.replace (appends to archive, file is required) tar.u === tar.update (appends if newer, file is required) tar.x === tar.extract tar.t === tar.list ``` Keep reading for all the command descriptions and options, as well as the low-level API that they are built on. ### tar.c(options, fileList, callback) [alias: tar.create] Create a tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Write the tarball archive to the specified filename. If this is specified, then the callback will be fired when the file has been written, and a promise will be returned that resolves when the file is written. If a filename is not specified, then a Readable Stream will be returned which will emit the file data. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. If this is set, and a file is not provided, then the resulting stream will already have the data ready to `read` or `emit('data')` as soon as you request it. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `mode` The mode to set on the created file archive - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. ### tar.x(options, fileList, callback) [alias: tar.extract] Extract a tarball archive. The `fileList` is an array of paths to extract from the tarball. If no paths are provided, then all the entries are extracted. If the archive is gzipped, then tar will detect this and unzip it. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. Most extraction errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then the extraction will fail completely. The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. [Alias: `C`] - `file` The archive file to extract. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Create files and directories synchronously. - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. [Alias: `keep-newer`, `keep-newer-files`] - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. [Alias: `k`, `keep-existing`] - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. [Alias: `P`] - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. [Alias: `U`] - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. [Alias: `strip-components`, `stripComponents`] - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. [Alias: `p`] - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. [Alias: `m`, `no-mtime`] - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. The following options are mostly internal, but can be modified in some advanced use cases, such as re-using caches between runs. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync extractions. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### tar.t(options, fileList, callback) [alias: tar.list] List the contents of a tarball archive. The `fileList` is an array of paths to list from the tarball. If no paths are provided, then all the entries are listed. If the archive is gzipped, then tar will detect this and unzip it. Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. However, they don't emit `'data'` or `'end'` events. (If you want to get actual readable entries, use the `tar.Parse` class instead.) The following options are supported: - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. [Alias: `C`] - `file` The archive file to list. If not specified, then a Writable stream is returned where the archive data should be written. [Alias: `f`] - `sync` Read the specified file synchronously. (This has no effect when a file option isn't specified, because entries are emitted as fast as they are parsed from the stream anyway.) - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. This is important for when both `file` and `sync` are set, because it will be called synchronously. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noResume` By default, `entry` streams are resumed immediately after the call to `onentry`. Set `noResume: true` to suppress this behavior. Note that by opting into this, the stream will never complete until the entry data is consumed. ### tar.u(options, fileList, callback) [alias: tar.update] Add files to an archive if they are newer than the entry already in the tarball archive. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ### tar.r(options, fileList, callback) [alias: tar.replace] Add files to an existing archive. Because later entries override earlier entries, this effectively replaces any existing entries. The `fileList` is an array of paths to add to the tarball. Adding a directory also adds its children recursively. An entry in `fileList` that starts with an `@` symbol is a tar archive whose entries will be added. To add a file that starts with `@`, prepend it with `./`. The following options are supported: - `file` Required. Write the tarball archive to the specified filename. [Alias: `f`] - `sync` Act synchronously. If this is set, then any provided file will be fully written after the call to `tar.c`. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for adding entries to the archive. Defaults to `process.cwd()`. [Alias: `C`] - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` [Alias: `z`] - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. [Alias: `P`] - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. [Alias: `n`] - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. [Alias: `L`, `h`] - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. [Alias: `m`, `no-mtime`] - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. ## Low-Level API ### class tar.Pack A readable tar stream. Has all the standard readable stream interface stuff. `'data'` and `'end'` events, `read()` method, `pause()` and `resume()`, etc. #### constructor(options) The following options are supported: - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `strict` Treat warnings as crash-worthy errors. Default false. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `prefix` A path portion to prefix onto the entries in the archive. - `gzip` Set to any truthy value to create a gzipped archive, or an object with settings for `zlib.Gzip()` - `filter` A function that gets called with `(path, stat)` for each entry being added. Return `true` to add the entry to the archive, or `false` to omit it. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `readdirCache` A Map object that caches calls to `readdir`. - `jobs` A number specifying how many concurrent jobs to run. Defaults to 4. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 16 MB. - `noDirRecurse` Do not recursively archive the contents of directories. - `follow` Set to true to pack the targets of symbolic links. Without this option, symbolic links are archived as such. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `mtime` Set to a `Date` object to force a specific `mtime` for everything added to the archive. Overridden by `noMtime`. #### add(path) Adds an entry to the archive. Returns the Pack stream. #### write(path) Adds an entry to the archive. Returns true if flushed. #### end() Finishes the archive. ### class tar.Pack.Sync Synchronous version of `tar.Pack`. ### class tar.Unpack A writable stream that unpacks a tar archive onto the file system. All the normal writable stream stuff is supported. `write()` and `end()` methods, `'drain'` events, etc. Note that all directories that are created will be forced to be writable, readable, and listable by their owner, to avoid cases where a directory prevents extraction of child entries by virtue of its mode. `'close'` is emitted when it's done writing stuff to the file system. Most unpack errors will cause a `warn` event to be emitted. If the `cwd` is missing, or not a directory, then an error will be emitted. #### constructor(options) - `cwd` Extract files relative to the specified directory. Defaults to `process.cwd()`. If provided, this must exist and must be a directory. - `filter` A function that gets called with `(path, entry)` for each entry being unpacked. Return `true` to unpack the entry from the archive, or `false` to skip it. - `newer` Set to true to keep the existing file on disk if it's newer than the file in the archive. - `keep` Do not overwrite existing files. In particular, if a file appears more than once in an archive, later copies will not overwrite earlier copies. - `preservePaths` Allow absolute paths, paths containing `..`, and extracting through symbolic links. By default, `/` is stripped from absolute paths, `..` paths are not extracted, and any file whose location would be modified by a symbolic link is not extracted. - `unlink` Unlink files before creating them. Without this option, tar overwrites existing files, which preserves existing hardlinks. With this option, existing hardlinks will be broken, as will any symlink that would affect the location of an extracted file. - `strip` Remove the specified number of leading path elements. Pathnames with fewer elements will be silently skipped. Note that the pathname is edited after applying the filter, but before security checks. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `umask` Filter the modes of entries like `process.umask()`. - `dmode` Default mode for directories - `fmode` Default mode for files - `dirCache` A Map object of which directories exist. - `maxMetaEntrySize` The maximum size of meta entries that is supported. Defaults to 1 MB. - `preserveOwner` If true, tar will set the `uid` and `gid` of extracted entries to the `uid` and `gid` fields in the archive. This defaults to true when run as root, and false otherwise. If false, then files and directories will be set with the owner and group of the user running the process. This is similar to `-p` in `tar(1)`, but ACLs and other system-specific data is never unpacked in this implementation, and modes are set by default already. - `win32` True if on a windows platform. Causes behavior where filenames containing `<|>?` chars are converted to windows-compatible values while being unpacked. - `uid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified user id, regardless of the `uid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `gid` option. - `gid` Set to a number to force ownership of all extracted files and folders, and all implicitly created directories, to be owned by the specified group id, regardless of the `gid` field in the archive. Cannot be used along with `preserveOwner`. Requires also setting a `uid` option. - `noMtime` Set to true to omit writing `mtime` value for extracted entries. - `transform` Provide a function that takes an `entry` object, and returns a stream, or any falsey value. If a stream is provided, then that stream's data will be written instead of the contents of the archive entry. If a falsey value is provided, then the entry is written to disk as normal. (To exclude items from extraction, use the `filter` option described above.) - `strict` Treat warnings as crash-worthy errors. Default false. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. ### class tar.Unpack.Sync Synchronous version of `tar.Unpack`. Note that using an asynchronous stream type with the `transform` option will cause undefined behavior in sync unpack streams. [MiniPass](http://npm.im/minipass)-based streams are designed for this use case. ### class tar.Parse A writable stream that parses a tar archive stream. All the standard writable stream stuff is supported. If the archive is gzipped, then tar will detect this and unzip it. Emits `'entry'` events with `tar.ReadEntry` objects, which are themselves readable streams that you can pipe wherever. Each `entry` will not emit until the one before it is flushed through, so make sure to either consume the data (with `on('data', ...)` or `.pipe(...)`) or throw it away with `.resume()` to keep the stream flowing. #### constructor(options) Returns an event emitter that emits `entry` events with `tar.ReadEntry` objects. The following options are supported: - `strict` Treat warnings as crash-worthy errors. Default false. - `filter` A function that gets called with `(path, entry)` for each entry being listed. Return `true` to emit the entry from the archive, or `false` to skip it. - `onentry` A function that gets called with `(entry)` for each entry that passes the filter. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. #### abort(message, error) Stop all parsing activities. This is called when there are zlib errors. It also emits a warning with the message and error provided. ### class tar.ReadEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being read out of a tar archive. It has the following fields: - `extended` The extended metadata object provided to the constructor. - `globalExtended` The global extended metadata object provided to the constructor. - `remain` The number of bytes remaining to be written into the stream. - `blockRemain` The number of 512-byte blocks remaining to be written into the stream. - `ignore` Whether this entry should be ignored. - `meta` True if this represents metadata about the next entry, false if it represents a filesystem object. - All the fields from the header, extended header, and global extended header are added to the ReadEntry object. So it has `path`, `type`, `size, `mode`, and so on. #### constructor(header, extended, globalExtended) Create a new ReadEntry object with the specified header, extended header, and global extended header values. ### class tar.WriteEntry extends [MiniPass](http://npm.im/minipass) A representation of an entry that is being written from the file system into a tar archive. Emits data for the Header, and for the Pax Extended Header if one is required, as well as any body data. Creating a WriteEntry for a directory does not also create WriteEntry objects for all of the directory contents. It has the following fields: - `path` The path field that will be written to the archive. By default, this is also the path from the cwd to the file system object. - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `myuid` If supported, the uid of the user running the current process. - `myuser` The `env.USER` string if set, or `''`. Set as the entry `uname` field if the file's `uid` matches `this.myuid`. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/` and filenames containing the windows-compatible forms of `<|>?:` characters are converted to actual `<|>?:` characters in the archive. - `noPax` Suppress pax extended headers. Note that this means that long paths and linkpaths will be truncated, and large or negative numeric values may be interpreted incorrectly. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. #### constructor(path, options) `path` is the path of the entry as it is written in the archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `maxReadSize` The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - `linkCache` A Map object containing the device and inode value for any file whose nlink is > 1, to identify hard links. - `statCache` A Map object that caches calls `lstat`. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `cwd` The current working directory for creating the archive. Defaults to `process.cwd()`. - `absolute` The absolute path to the entry on the filesystem. By default, this is `path.resolve(this.cwd, this.path)`, but it can be overridden explicitly. - `strict` Treat warnings as crash-worthy errors. Default false. - `win32` True if on a windows platform. Causes behavior where paths replace `\` with `/`. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. - `umask` Set to restrict the modes on the entries in the archive, somewhat like how umask works on file creation. Defaults to `process.umask()` on unix systems, or `0o22` on Windows. #### warn(message, data) If strict, emit an error with the provided message. Othewise, emit a `'warn'` event with the provided message and data. ### class tar.WriteEntry.Sync Synchronous version of tar.WriteEntry ### class tar.WriteEntry.Tar A version of tar.WriteEntry that gets its data from a tar.ReadEntry instead of from the filesystem. #### constructor(readEntry, options) `readEntry` is the entry being read out of another archive. The following options are supported: - `portable` Omit metadata that is system-specific: `ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, and `nlink`. Note that `mtime` is still included, because this is necessary other time-based operations. - `preservePaths` Allow absolute paths. By default, `/` is stripped from absolute paths. - `strict` Treat warnings as crash-worthy errors. Default false. - `onwarn` A function that will get called with `(message, data)` for any warnings encountered. - `noMtime` Set to true to omit writing `mtime` values for entries. Note that this prevents using other mtime-based features like `tar.update` or the `keepNewer` option with the resulting tar archive. ### class tar.Header A class for reading and writing header blocks. It has the following fields: - `nullBlock` True if decoding a block which is entirely composed of `0x00` null bytes. (Useful because tar files are terminated by at least 2 null blocks.) - `cksumValid` True if the checksum in the header is valid, false otherwise. - `needPax` True if the values, as encoded, will require a Pax extended header. - `path` The path of the entry. - `mode` The 4 lowest-order octal digits of the file mode. That is, read/write/execute permissions for world, group, and owner, and the setuid, setgid, and sticky bits. - `uid` Numeric user id of the file owner - `gid` Numeric group id of the file owner - `size` Size of the file in bytes - `mtime` Modified time of the file - `cksum` The checksum of the header. This is generated by adding all the bytes of the header block, treating the checksum field itself as all ascii space characters (that is, `0x20`). - `type` The human-readable name of the type of entry this represents, or the alphanumeric key if unknown. - `typeKey` The alphanumeric key for the type of entry this header represents. - `linkpath` The target of Link and SymbolicLink entries. - `uname` Human-readable user name of the file owner - `gname` Human-readable group name of the file owner - `devmaj` The major portion of the device number. Always `0` for files, directories, and links. - `devmin` The minor portion of the device number. Always `0` for files, directories, and links. - `atime` File access time. - `ctime` File change time. #### constructor(data, [offset=0]) `data` is optional. It is either a Buffer that should be interpreted as a tar Header starting at the specified offset and continuing for 512 bytes, or a data object of keys and values to set on the header object, and eventually encode as a tar Header. #### decode(block, offset) Decode the provided buffer starting at the specified offset. Buffer length must be greater than 512 bytes. #### set(data) Set the fields in the data object. #### encode(buffer, offset) Encode the header fields into the buffer at the specified offset. Returns `this.needPax` to indicate whether a Pax Extended Header is required to properly encode the specified data. ### class tar.Pax An object representing a set of key-value pairs in an Pax extended header entry. It has the following fields. Where the same name is used, they have the same semantics as the tar.Header field of the same name. - `global` True if this represents a global extended header, or false if it is for a single entry. - `atime` - `charset` - `comment` - `ctime` - `gid` - `gname` - `linkpath` - `mtime` - `path` - `size` - `uid` - `uname` - `dev` - `ino` - `nlink` #### constructor(object, global) Set the fields set in the object. `global` is a boolean that defaults to false. #### encode() Return a Buffer containing the header and body for the Pax extended header entry, or `null` if there is nothing to encode. #### encodeBody() Return a string representing the body of the pax extended header entry. #### encodeField(fieldName) Return a string representing the key/value encoding for the specified fieldName, or `''` if the field is unset. ### tar.Pax.parse(string, extended, global) Return a new Pax object created by parsing the contents of the string provided. If the `extended` object is set, then also add the fields from that object. (This is necessary because multiple metadata entries can occur in sequence.) ### tar.types A translation table for the `type` field in tar headers. #### tar.types.name.get(code) Get the human-readable name for a given alphanumeric code. #### tar.types.code.get(name) Get the alphanumeric code for a given human-readable name. # hmac-drbg [![Build Status](https://secure.travis-ci.org/indutny/hmac-drbg.svg)](http://travis-ci.org/indutny/hmac-drbg) [![NPM version](https://badge.fury.io/js/hmac-drbg.svg)](http://badge.fury.io/js/hmac-drbg) JS-only implementation of [HMAC DRBG][0]. ## Usage ```js const DRBG = require('hmac-drbg'); const hash = require('hash.js'); const d = new DRBG({ hash: hash.sha256, entropy: '0123456789abcdef', nonce: '0123456789abcdef', pers: '0123456789abcdef' /* or `null` */ }); d.generate(32, 'hex'); ``` #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2017. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: http://csrc.nist.gov/groups/ST/toolkit/documents/rng/HashBlockCipherDRBG.pdf # ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) ipaddr.js is a small (1.9K minified and gzipped) library for manipulating IP addresses in JavaScript environments. It runs on both CommonJS runtimes (e.g. [nodejs]) and in a web browser. ipaddr.js allows you to verify and parse string representation of an IP address, match it against a CIDR range or range list, determine if it falls into some reserved ranges (examples include loopback and private ranges), and convert between IPv4 and IPv4-mapped IPv6 addresses. [nodejs]: http://nodejs.org ## Installation `npm install ipaddr.js` or `bower install ipaddr.js` ## API ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, it is exported from the module: ```js var ipaddr = require('ipaddr.js'); ``` The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. ### Global methods There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and `ipaddr.process`. All of them receive a string as a single parameter. The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or IPv6 address, and `false` otherwise. It does not throw any exceptions. The `ipaddr.parse` method returns an object representing the IP address, or throws an `Error` if the passed string is not a valid representation of an IP address. The `ipaddr.process` method works just like the `ipaddr.parse` one, but it automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts before returning. It is useful when you have a Node.js instance listening on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 connections on your IPv6-only socket, but the remote address will be mangled. Use `ipaddr.process` method to automatically demangle it. ### Object representation Parsing methods return an object which descends from `ipaddr.IPv6` or `ipaddr.IPv4`. These objects share some properties, but most of them differ. #### Shared properties One can determine the type of address by calling `addr.kind()`. It will return either `"ipv6"` or `"ipv4"`. An address can be converted back to its string representation with `addr.toString()`. Note that this method: * does not return the original string used to create the object (in fact, there is no way of getting that string) * returns a compact representation (when it is applicable) A `match(range, bits)` method can be used to check if the address falls into a certain CIDR range. Note that an address can be (obviously) matched only against an address of the same type. For example: ```js var addr = ipaddr.parse("2001:db8:1234::1"); var range = ipaddr.parse("2001:db8::"); addr.match(range, 32); // => true ``` Alternatively, `match` can also be called as `match([range, bits])`. In this way, it can be used together with the `parseCIDR(string)` method, which parses an IP address together with a CIDR range. For example: ```js var addr = ipaddr.parse("2001:db8:1234::1"); addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true ``` A `range()` method returns one of predefined names for several special ranges defined by IP protocols. The exact names (and their respective CIDR ranges) can be looked up in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` (the default one) and `"reserved"`. You can match against your own range list by using `ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: ```js var rangeList = { documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], tunnelProviders: [ [ ipaddr.parse('2001:470::'), 32 ], // he.net [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 ] }; ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" ``` The addresses can be converted to their byte representation with `toByteArray()`. (Actually, JavaScript mostly does not know about byte buffers. They are emulated with arrays of numbers, each in range of 0..255.) ```js var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, <zeroes...>, 0x00, 0x68 ] ``` The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them have the same interface for both protocols, and are similar to global methods. `ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. `ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. [IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 [IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 #### IPv6 properties Sometimes you will want to convert IPv6 not to a compact string representation (with the `::` substitution); the `toNormalizedString()` method will return an address where all zeroes are explicit. For example: ```js var addr = ipaddr.parse("2001:0db8::0001"); addr.toString(); // => "2001:db8::1" addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" ``` The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped one, and `toIPv4Address()` will return an IPv4 object address. To access the underlying binary representation of the address, use `addr.parts`. ```js var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] ``` A IPv6 zone index can be accessed via `addr.zoneId`: ```js var addr = ipaddr.parse("2001:db8::%eth0"); addr.zoneId // => 'eth0' ``` #### IPv4 properties `toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. To access the underlying representation of the address, use `addr.octets`. ```js var addr = ipaddr.parse("192.168.1.1"); addr.octets // => [192, 168, 1, 1] ``` `prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or false if the netmask is not valid. ```js ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null ``` `subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. ```js ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" ``` `broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. ```js ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" ``` `networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. ```js ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" ``` #### Conversion IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, while for IPv6 it has to be an array of sixteen 8-bit values. For example: ```js var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); addr.toString(); // => "127.0.0.1" ``` or ```js var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) addr.toString(); // => "2001:db8::1" ``` Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). For example: ```js var addr = ipaddr.parse("127.0.0.1"); addr.toByteArray(); // => [0x7f, 0, 0, 1] ``` or ```js var addr = ipaddr.parse("2001:db8::1"); addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] ``` [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![test][test]][test-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] <div align="center"> <a href="http://json-schema.org"> <img width="160" height="160" src="https://raw.githubusercontent.com/webpack-contrib/schema-utils/master/docs/logo.png"> </a> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> <h1>Schema Utils</h1> </div> <h2 align="center">Install</h2> ```bash npm i schema-utils ``` <h2 align="center">Usage</h2> ### `validateOptions` **`schema.json`** ```js { "type": "object", "properties": { // Options... }, "additionalProperties": false } ``` #### Error Messages (Custom) **`schema.json`** ```js { "type": "object", "properties": { "option": { "type": [ "boolean" ] } }, // Overrides the default err.message for option "errorMessage": { "option": "should be {Boolean} (https:/github.com/org/repo#anchor)" } "additionalProperties": false } ``` ```js import schema from 'path/to/schema.json' import validateOptions from 'schema-utils' validateOptions(schema, options, 'Loader/Plugin Name') ``` <h2 align="center">Examples</h2> **schema.json** ```json { "type": "object", "properties": { "name": { "type": "string" }, "test": { "anyOf": [ { "type": "array" }, { "type": "string" }, { "instanceof": "RegExp" } ] }, "transform": { "instanceof": "Function" }, "sourceMap": { "type": "boolean" } }, "additionalProperties": false } ``` ### `Loader` ```js import { getOptions } from 'loader-utils' import validateOptions from 'schema-utils' import schema from 'path/to/schema.json' function loader (src, map) { const options = getOptions(this) || {} validateOptions(schema, options, 'Loader Name') // Code... } ``` ### `Plugin` ```js import validateOptions from 'schema-utils' import schema from 'path/to/schema.json' class Plugin { constructor (options) { validateOptions(schema, options, 'Plugin Name') this.options = options } apply (compiler) { // Code... } } ``` [npm]: https://img.shields.io/npm/v/schema-utils.svg [npm-url]: https://npmjs.com/package/schema-utils [node]: https://img.shields.io/node/v/schema-utils.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack-contrib/schema-utils.svg [deps-url]: https://david-dm.org/webpack-contrib/schema-utils [test]: http://img.shields.io/travis/webpack-contrib/schema-utils.svg [test-url]: https://travis-ci.org/webpack-contrib/schema-utils [cover]: https://codecov.io/gh/webpack-contrib/schema-utils/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/schema-utils [chat]: https://img.shields.io/badge/gitter-webpack%2Fwebpack-brightgreen.svg [chat-url]: https://gitter.im/webpack/webpack # browserify-aes [![Build Status](https://travis-ci.org/crypto-browserify/browserify-aes.svg)](https://travis-ci.org/crypto-browserify/browserify-aes) Node style aes for use in the browser. Implements: - createCipher - createCipheriv - createDecipher - createDecipheriv - getCiphers In node.js, the `crypto` implementation is used, in browsers it falls back to a pure JavaScript implementation. Much of this library has been taken from the aes implementation in [triplesec](https://github.com/keybase/triplesec), a partial derivation of [crypto-js](https://code.google.com/p/crypto-js/). `EVP_BytesToKey` is a straight up port of the same function from OpenSSL as there is literally no documenation on it beyond it using 'undocumented extensions' for longer keys. ## LICENSE [MIT](LICENSE) # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # path-parse [![Build Status](https://travis-ci.org/jbgutierrez/path-parse.svg?branch=master)](https://travis-ci.org/jbgutierrez/path-parse) > Node.js [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) [ponyfill](https://ponyfill.com). ## Install ``` $ npm install --save path-parse ``` ## Usage ```js var pathParse = require('path-parse'); pathParse('/home/user/dir/file.txt'); //=> { // root : "/", // dir : "/home/user/dir", // base : "file.txt", // ext : ".txt", // name : "file" // } ``` ## API See [`path.parse(pathString)`](https://nodejs.org/api/path.html#path_path_parse_pathstring) docs. ### pathParse(path) ### pathParse.posix(path) The Posix specific version. ### pathParse.win32(path) The Windows specific version. ## License MIT © [Javier Blanco](http://jbgutierrez.info) # is-descriptor [![NPM version](https://img.shields.io/npm/v/is-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-descriptor) > Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-descriptor ``` ## Usage ```js var isDescriptor = require('is-descriptor'); isDescriptor({value: 'foo'}) //=> true isDescriptor({get: function(){}, set: function(){}}) //=> true isDescriptor({get: 'foo', set: function(){}}) //=> false ``` You may also check for a descriptor by passing an object as the first argument and property name (`string`) as the second argument. ```js var obj = {}; obj.foo = 'abc'; Object.defineProperty(obj, 'bar', { value: 'xyz' }); isDescriptor(obj, 'foo'); //=> true isDescriptor(obj, 'bar'); //=> true ``` ## Examples ### value type `false` when not an object ```js isDescriptor('a'); //=> false isDescriptor(null); //=> false isDescriptor([]); //=> false ``` ### data descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({value: 'foo'}); //=> true isDescriptor({value: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', get: noop}); //=> false isDescriptor({get: noop, value: noop}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({value: 'foo', enumerable: 'foo'}); //=> false isDescriptor({value: 'foo', configurable: 'foo'}); //=> false isDescriptor({value: 'foo', writable: 'foo'}); //=> false ``` ### accessor descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({get: noop, set: noop}); //=> true isDescriptor({get: noop}); //=> true isDescriptor({set: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({get: noop, set: noop, bar: 'baz'}); //=> false isDescriptor({get: noop, writable: true}); //=> false isDescriptor({get: noop, value: true}); //=> false ``` `false` when an accessor is not a function ```js isDescriptor({get: noop, set: 'baz'}); //=> false isDescriptor({get: 'foo', set: noop}); //=> false isDescriptor({get: 'foo', bar: 'baz'}); //=> false isDescriptor({get: 'foo', set: 'baz'}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({get: noop, set: noop, enumerable: 'foo'}); //=> false isDescriptor({set: noop, configurable: 'foo'}); //=> false isDescriptor({get: noop, configurable: 'foo'}); //=> false ``` ## About ### Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 24 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ # core-js [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/zloirock/core-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![version](https://img.shields.io/npm/v/core-js.svg)](https://www.npmjs.com/package/core-js) [![npm downloads](https://img.shields.io/npm/dm/core-js.svg)](http://npm-stat.com/charts.html?package=core-js&author=&from=2014-11-18) [![Build Status](https://travis-ci.org/zloirock/core-js.svg)](https://travis-ci.org/zloirock/core-js) [![devDependency status](https://david-dm.org/zloirock/core-js/dev-status.svg)](https://david-dm.org/zloirock/core-js?type=dev) ## As advertising: the author is looking for a good job -) ## [core-js@3, babel and a look into the future](https://github.com/zloirock/core-js/tree/master/docs/2019-03-19-core-js-3-babel-and-a-look-into-the-future.md) ## Open Collective Sponsors [**Become a sponsor**](https://opencollective.com/core-js#sponsor) and get your logo with a link to your site on our README on GitHub and NPM. <a href="https://opencollective.com/core-js/sponsor/0/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/0/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/1/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/1/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/2/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/2/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/3/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/3/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/4/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/4/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/5/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/5/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/6/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/6/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/7/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/7/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/8/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/8/avatar.svg"></a><a href="https://opencollective.com/core-js/sponsor/9/website" target="_blank"><img src="https://opencollective.com/core-js/sponsor/9/avatar.svg"></a> ## Patreon Sponsors [**Become a sponsor**](https://www.patreon.com/zloirock) and get your logo with a link to your site on our README on GitHub and NPM. --- Modular standard library for JavaScript. Includes polyfills for [ECMAScript up to 2019](https://github.com/zloirock/core-js#ecmascript): [promises](https://github.com/zloirock/core-js#ecmascript-promise), [symbols](https://github.com/zloirock/core-js#ecmascript-symbol), [collections](https://github.com/zloirock/core-js#ecmascript-collections), iterators, [typed arrays](https://github.com/zloirock/core-js#ecmascript-typed-arrays), many other features, [ECMAScript proposals](https://github.com/zloirock/core-js#ecmascript-proposals), [some cross-platform WHATWG / W3C features and proposals](#web-standards) like [`URL`](https://github.com/zloirock/core-js#url-and-urlsearchparams). You can load only required features or use it without global namespace pollution. [*Example*](http://goo.gl/a2xexl): ```js import 'core-js'; // <- at the top of your entry point Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] [1, [2, 3], [4, [5]]].flat(2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` *You can load only required features*: ```js import 'core-js/features/array/from'; // <- at the top of your entry point import 'core-js/features/array/flat'; // <- at the top of your entry point import 'core-js/features/set'; // <- at the top of your entry point import 'core-js/features/promise'; // <- at the top of your entry point Array.from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] [1, [2, 3], [4, [5]]].flat(2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` *Or use it without global namespace pollution*: ```js import from from 'core-js-pure/features/array/from'; import flat from 'core-js-pure/features/array/flat'; import Set from 'core-js-pure/features/set'; import Promise from 'core-js-pure/features/promise'; from(new Set([1, 2, 3, 2, 1])); // => [1, 2, 3] flat([1, [2, 3], [4, [5]]], 2); // => [1, 2, 3, 4, 5] Promise.resolve(32).then(x => console.log(x)); // => 32 ``` **It's a global version (first 2 examples), for more info see [`core-js` documentation](https://github.com/zloirock/core-js/blob/master/README.md).** # hash-base [![NPM Package](https://img.shields.io/npm/v/hash-base.svg?style=flat-square)](https://www.npmjs.org/package/hash-base) [![Build Status](https://img.shields.io/travis/crypto-browserify/hash-base.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/hash-base) [![Dependency status](https://img.shields.io/david/crypto-browserify/hash-base.svg?style=flat-square)](https://david-dm.org/crypto-browserify/hash-base#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Abstract base class to inherit from if you want to create streams implementing the same API as node crypto [Hash][1] (for [Cipher][2] / [Decipher][3] check [crypto-browserify/cipher-base][4]). ## Example ```js const HashBase = require('hash-base') const inherits = require('inherits') // our hash function is XOR sum of all bytes function MyHash () { HashBase.call(this, 1) // in bytes this._sum = 0x00 } inherits(MyHash, HashBase) MyHash.prototype._update = function () { for (let i = 0; i < this._block.length; ++i) this._sum ^= this._block[i] } MyHash.prototype._digest = function () { return this._sum } const data = Buffer.from([ 0x00, 0x42, 0x01 ]) const hash = new MyHash().update(data).digest() console.log(hash) // => 67 ``` You also can check [source code](index.js) or [crypto-browserify/md5.js][5] ## LICENSE MIT [1]: https://nodejs.org/api/crypto.html#crypto_class_hash [2]: https://nodejs.org/api/crypto.html#crypto_class_cipher [3]: https://nodejs.org/api/crypto.html#crypto_class_decipher [4]: https://github.com/crypto-browserify/cipher-base [5]: https://github.com/crypto-browserify/md5.js # dom-walk iteratively walk a DOM node ## Example ``` js var walk = require("dom-walk") walk(document.body.childNodes, function (node) { console.log("node", node) }) ``` ## Installation `npm install dom-walk` ## Contributors - Raynos ## MIT Licenced base64-js ========= `base64-js` does basic base64 encoding/decoding in pure JS. [![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) [![testling badge](https://ci.testling.com/beatgammit/base64-js.png)](https://ci.testling.com/beatgammit/base64-js) Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. ## install With [npm](https://npmjs.org) do: `npm install base64-js` and `var base64js = require('base64-js')` For use in web browsers do: `<script src="base64js.min.js"></script>` ## methods `base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. * `byteLength` - Takes a base64 string and returns length of byte array * `toByteArray` - Takes a base64 string and returns a byte array * `fromByteArray` - Takes a byte array and returns a base64 string ## license MIT # node-portfinder [![Build Status](https://api.travis-ci.org/indexzero/node-portfinder.svg)](https://travis-ci.org/indexzero/node-portfinder) ## Installation ``` bash $ [sudo] npm install portfinder ``` ## Usage The `portfinder` module has a simple interface: ``` js var portfinder = require('portfinder'); portfinder.getPort(function (err, port) { // // `port` is guaranteed to be a free port // in this scope. // }); ``` Or with promise (if Promise are supported) : ``` js const portfinder = require('portfinder'); portfinder.getPortPromise() .then((port) => { // // `port` is guaranteed to be a free port // in this scope. // }) .catch((err) => { // // Could not get a free port, `err` contains the reason. // }); ``` If `portfinder.getPortPromise()` is called on a Node version without Promise (<4), it will throw an Error unless [Bluebird](http://bluebirdjs.com/docs/getting-started.html) or any Promise pollyfill is used. ### Ports search scope By default `portfinder` will start searching from `8000` and scan until maximum port number (`65535`) is reached. You can change this globally by setting: ```js portfinder.basePort = 3000; // default: 8000 portfinder.highestPort = 3333; // default: 65535 ``` or by passing optional options object on each invocation: ```js portfinder.getPort({ port: 3000, // minimum port stopPort: 3333 // maximum port }, callback); ``` ## Run Tests ``` bash $ npm test ``` #### Author: [Charlie Robbins][0] #### Maintainer: [Erik Trom][1] #### License: MIT/X11 [0]: http://nodejitsu.com [1]: https://github.com/eriktrom # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = new LRU(options) , otherCache = new LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. Setting it to a non-number or negative number will throw a `TypeError`. Setting it to 0 makes it be `Infinity`. * `maxAge` 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. Setting this to a negative value will make everything seem old! Setting it to a non-number will throw a `TypeError`. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. * `updateAgeOnGet` When using time-expiring entries with `maxAge`, setting this to `true` will make each item's effective time update to the current time whenever it is retrieved from cache, causing it to not expire. (It can still fall out of cache based on recency of use, of course.) ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # http-proxy-middleware [![Build Status](https://img.shields.io/travis/chimurai/http-proxy-middleware/master.svg?style=flat-square)](https://travis-ci.org/chimurai/http-proxy-middleware) [![Coveralls](https://img.shields.io/coveralls/chimurai/http-proxy-middleware.svg?style=flat-square)](https://coveralls.io/r/chimurai/http-proxy-middleware) [![dependency Status](https://img.shields.io/david/chimurai/http-proxy-middleware.svg?style=flat-square)](https://david-dm.org/chimurai/http-proxy-middleware#info=dependencies) [![dependency Status](https://snyk.io/test/npm/http-proxy-middleware/badge.svg)](https://snyk.io/test/npm/http-proxy-middleware) [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) Node.js proxying made simple. Configure proxy middleware with ease for [connect](https://github.com/senchalabs/connect), [express](https://github.com/strongloop/express), [browser-sync](https://github.com/BrowserSync/browser-sync) and [many more](#compatible-servers). Powered by the popular Nodejitsu [`http-proxy`](https://github.com/nodejitsu/node-http-proxy). [![GitHub stars](https://img.shields.io/github/stars/nodejitsu/node-http-proxy.svg?style=social&label=Star)](https://github.com/nodejitsu/node-http-proxy) ## TL;DR Proxy `/api` requests to `http://www.example.org` ```javascript var express = require('express') var proxy = require('http-proxy-middleware') var app = express() app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true })) app.listen(3000) // http://localhost:3000/api/foo/bar -> http://www.example.org/api/foo/bar ``` _All_ `http-proxy` [options](https://github.com/nodejitsu/node-http-proxy#options) can be used, along with some extra `http-proxy-middleware` [options](#options). :bulb: **Tip:** Set the option `changeOrigin` to `true` for [name-based virtual hosted sites](http://en.wikipedia.org/wiki/Virtual_hosting#Name-based). ## Table of Contents <!-- MarkdownTOC autolink=true bracket=round depth=2 --> - [Install](#install) - [Core concept](#core-concept) - [Example](#example) - [Context matching](#context-matching) - [Options](#options) - [http-proxy-middleware options](#http-proxy-middleware-options) - [http-proxy events](#http-proxy-events) - [http-proxy options](#http-proxy-options) - [Shorthand](#shorthand) - [app.use\(path, proxy\)](#appusepath-proxy) - [WebSocket](#websocket) - [External WebSocket upgrade](#external-websocket-upgrade) - [Working examples](#working-examples) - [Recipes](#recipes) - [Compatible servers](#compatible-servers) - [Tests](#tests) - [Changelog](#changelog) - [License](#license) <!-- /MarkdownTOC --> ## Install ```javascript $ npm install --save-dev http-proxy-middleware ``` ## Core concept Proxy middleware configuration. #### proxy([context,] config) ```javascript var proxy = require('http-proxy-middleware') var apiProxy = proxy('/api', { target: 'http://www.example.org' }) // \____/ \_____________________________/ // | | // context options // 'apiProxy' is now ready to be used as middleware in a server. ``` - **context**: Determine which requests should be proxied to the target host. (more on [context matching](#context-matching)) - **options.target**: target host to proxy to. _(protocol + host)_ (full list of [`http-proxy-middleware` configuration options](#options)) #### proxy(uri [, config]) ```javascript // shorthand syntax for the example above: var apiProxy = proxy('http://www.example.org/api') ``` More about the [shorthand configuration](#shorthand). ## Example An example with `express` server. ```javascript // include dependencies var express = require('express') var proxy = require('http-proxy-middleware') // proxy middleware options var options = { target: 'http://www.example.org', // target host changeOrigin: true, // needed for virtual hosted sites ws: true, // proxy websockets pathRewrite: { '^/api/old-path': '/api/new-path', // rewrite path '^/api/remove/path': '/path' // remove base path }, router: { // when request.headers.host == 'dev.localhost:3000', // override target 'http://www.example.org' to 'http://localhost:8000' 'dev.localhost:3000': 'http://localhost:8000' } } // create the proxy (without context) var exampleProxy = proxy(options) // mount `exampleProxy` in web server var app = express() app.use('/api', exampleProxy) app.listen(3000) ``` ## Context matching Providing an alternative way to decide which requests should be proxied; In case you are not able to use the server's [`path` parameter](http://expressjs.com/en/4x/api.html#app.use) to mount the proxy or when you need more flexibility. [RFC 3986 `path`](https://tools.ietf.org/html/rfc3986#section-3.3) is used for context matching. ``` foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment ``` - **path matching** - `proxy({...})` - matches any path, all requests will be proxied. - `proxy('/', {...})` - matches any path, all requests will be proxied. - `proxy('/api', {...})` - matches paths starting with `/api` - **multiple path matching** - `proxy(['/api', '/ajax', '/someotherpath'], {...})` - **wildcard path matching** For fine-grained control you can use wildcard matching. Glob pattern matching is done by _micromatch_. Visit [micromatch](https://www.npmjs.com/package/micromatch) or [glob](https://www.npmjs.com/package/glob) for more globbing examples. - `proxy('**', {...})` matches any path, all requests will be proxied. - `proxy('**/*.html', {...})` matches any path which ends with `.html` - `proxy('/*.html', {...})` matches paths directly under path-absolute - `proxy('/api/**/*.html', {...})` matches requests ending with `.html` in the path of `/api` - `proxy(['/api/**', '/ajax/**'], {...})` combine multiple patterns - `proxy(['/api/**', '!**/bad.json'], {...})` exclusion **Note**: In multiple path matching, you cannot use string paths and wildcard paths together. - **custom matching** For full control you can provide a custom function to determine which requests should be proxied or not. ```javascript /** * @return {Boolean} */ var filter = function(pathname, req) { return pathname.match('^/api') && req.method === 'GET' } var apiProxy = proxy(filter, { target: 'http://www.example.org' }) ``` ## Options ### http-proxy-middleware options - **option.pathRewrite**: object/function, rewrite target's url path. Object-keys will be used as _RegExp_ to match paths. ```javascript // rewrite path pathRewrite: {'^/old/api' : '/new/api'} // remove path pathRewrite: {'^/remove/api' : ''} // add base path pathRewrite: {'^/' : '/basepath/'} // custom rewriting pathRewrite: function (path, req) { return path.replace('/api', '/base/api') } ``` - **option.router**: object/function, re-target `option.target` for specific requests. ```javascript // Use `host` and/or `path` to match requests. First match will be used. // The order of the configuration matters. router: { 'integration.localhost:3000' : 'http://localhost:8001', // host only 'staging.localhost:3000' : 'http://localhost:8002', // host only 'localhost:3000/api' : 'http://localhost:8003', // host + path '/rest' : 'http://localhost:8004' // path only } // Custom router function router: function(req) { return 'http://localhost:8004'; } ``` - **option.logLevel**: string, ['debug', 'info', 'warn', 'error', 'silent']. Default: `'info'` - **option.logProvider**: function, modify or replace log provider. Default: `console`. ```javascript // simple replace function logProvider(provider) { // replace the default console log provider. return require('winston') } ``` ```javascript // verbose replacement function logProvider(provider) { var logger = new (require('winston')).Logger() var myCustomProvider = { log: logger.log, debug: logger.debug, info: logger.info, warn: logger.warn, error: logger.error } return myCustomProvider } ``` - (DEPRECATED) **option.proxyHost**: Use `option.changeOrigin = true` instead. - (DEPRECATED) **option.proxyTable**: Use `option.router` instead. ### http-proxy events Subscribe to [http-proxy events](https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events): - **option.onError**: function, subscribe to http-proxy's `error` event for custom error handling. ```javascript function onError(err, req, res) { res.writeHead(500, { 'Content-Type': 'text/plain' }) res.end( 'Something went wrong. And we are reporting a custom error message.' ) } ``` - **option.onProxyRes**: function, subscribe to http-proxy's `proxyRes` event. ```javascript function onProxyRes(proxyRes, req, res) { proxyRes.headers['x-added'] = 'foobar' // add new header to response delete proxyRes.headers['x-removed'] // remove header from response } ``` - **option.onProxyReq**: function, subscribe to http-proxy's `proxyReq` event. ```javascript function onProxyReq(proxyReq, req, res) { // add custom header to request proxyReq.setHeader('x-added', 'foobar') // or log the req } ``` - **option.onProxyReqWs**: function, subscribe to http-proxy's `proxyReqWs` event. ```javascript function onProxyReqWs(proxyReq, req, socket, options, head) { // add custom header proxyReq.setHeader('X-Special-Proxy-Header', 'foobar') } ``` - **option.onOpen**: function, subscribe to http-proxy's `open` event. ```javascript function onOpen(proxySocket) { // listen for messages coming FROM the target here proxySocket.on('data', hybiParseAndLogMessage) } ``` - **option.onClose**: function, subscribe to http-proxy's `close` event. ```javascript function onClose(res, socket, head) { // view disconnected websocket connections console.log('Client disconnected') } ``` ### http-proxy options The following options are provided by the underlying [http-proxy](https://github.com/nodejitsu/node-http-proxy#options) library. - **option.target**: url string to be parsed with the url module - **option.forward**: url string to be parsed with the url module - **option.agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects) - **option.ssl**: object to be passed to https.createServer() - **option.ws**: true/false: if you want to proxy websockets - **option.xfwd**: true/false, adds x-forward headers - **option.secure**: true/false, if you want to verify the SSL Certs - **option.toProxy**: true/false, passes the absolute URL as the `path` (useful for proxying to proxies) - **option.prependPath**: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path - **option.ignorePath**: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required). - **option.localAddress** : Local interface string to bind for outgoing connections - **option.changeOrigin**: true/false, Default: false - changes the origin of the host header to the target URL - **option.preserveHeaderKeyCase**: true/false, Default: false - specify whether you want to keep letter case of response header key - **option.auth** : Basic authentication i.e. 'user:password' to compute an Authorization header. - **option.hostRewrite**: rewrites the location hostname on (301/302/307/308) redirects. - **option.autoRewrite**: rewrites the location host/port on (301/302/307/308) redirects based on requested host/port. Default: false. - **option.protocolRewrite**: rewrites the location protocol on (301/302/307/308) redirects to 'http' or 'https'. Default: null. - **option.cookieDomainRewrite**: rewrites domain of `set-cookie` headers. Possible values: - `false` (default): disable cookie rewriting - String: new domain, for example `cookieDomainRewrite: "new.domain"`. To remove the domain, use `cookieDomainRewrite: ""`. - Object: mapping of domains to new domains, use `"*"` to match all domains. For example keep one domain unchanged, rewrite one domain and remove other domains: ``` cookieDomainRewrite: { "unchanged.domain": "unchanged.domain", "old.domain": "new.domain", "*": "" } ``` - **option.cookiePathRewrite**: rewrites path of `set-cookie` headers. Possible values: - `false` (default): disable cookie rewriting - String: new path, for example `cookiePathRewrite: "/newPath/"`. To remove the path, use `cookiePathRewrite: ""`. To set path to root use `cookiePathRewrite: "/"`. - Object: mapping of paths to new paths, use `"*"` to match all paths. For example, to keep one path unchanged, rewrite one path and remove other paths: ``` cookiePathRewrite: { "/unchanged.path/": "/unchanged.path/", "/old.path/": "/new.path/", "*": "" } ``` - **option.headers**: object, adds [request headers](https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields). (Example: `{host:'www.example.org'}`) - **option.proxyTimeout**: timeout (in millis) when proxy receives no response from target - **option.timeout**: timeout (in millis) for incoming requests - **option.followRedirects**: true/false, Default: false - specify whether you want to follow redirects - **option.selfHandleResponse** true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the `proxyRes` event - **option.buffer**: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option: ``` 'use strict'; const streamify = require('stream-array'); const HttpProxy = require('http-proxy'); const proxy = new HttpProxy(); module.exports = (req, res, next) => { proxy.web(req, res, { target: 'http://localhost:4003/', buffer: streamify(req.rawBody) }, next); }; ``` ## Shorthand Use the shorthand syntax when verbose configuration is not needed. The `context` and `option.target` will be automatically configured when shorthand is used. Options can still be used if needed. ```javascript proxy('http://www.example.org:8000/api') // proxy('/api', {target: 'http://www.example.org:8000'}); proxy('http://www.example.org:8000/api/books/*/**.json') // proxy('/api/books/*/**.json', {target: 'http://www.example.org:8000'}); proxy('http://www.example.org:8000/api', { changeOrigin: true }) // proxy('/api', {target: 'http://www.example.org:8000', changeOrigin: true}); ``` ### app.use(path, proxy) If you want to use the server's `app.use` `path` parameter to match requests; Create and mount the proxy without the http-proxy-middleware `context` parameter: ```javascript app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true })) ``` `app.use` documentation: - express: http://expressjs.com/en/4x/api.html#app.use - connect: https://github.com/senchalabs/connect#mount-middleware ## WebSocket ```javascript // verbose api proxy('/', { target: 'http://echo.websocket.org', ws: true }) // shorthand proxy('http://echo.websocket.org', { ws: true }) // shorter shorthand proxy('ws://echo.websocket.org') ``` ### External WebSocket upgrade In the previous WebSocket examples, http-proxy-middleware relies on a initial http request in order to listen to the http `upgrade` event. If you need to proxy WebSockets without the initial http request, you can subscribe to the server's http `upgrade` event manually. ```javascript var wsProxy = proxy('ws://echo.websocket.org', { changeOrigin: true }) var app = express() app.use(wsProxy) var server = app.listen(3000) server.on('upgrade', wsProxy.upgrade) // <-- subscribe to http 'upgrade' ``` ## Working examples View and play around with [working examples](https://github.com/chimurai/http-proxy-middleware/tree/master/examples). - Browser-Sync ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/browser-sync/index.js)) - express ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/express/index.js)) - connect ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/connect/index.js)) - WebSocket ([example source](https://github.com/chimurai/http-proxy-middleware/tree/master/examples/websocket/index.js)) ## Recipes View the [recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes) for common use cases. ## Compatible servers `http-proxy-middleware` is compatible with the following servers: - [connect](https://www.npmjs.com/package/connect) - [express](https://www.npmjs.com/package/express) - [browser-sync](https://www.npmjs.com/package/browser-sync) - [lite-server](https://www.npmjs.com/package/lite-server) - [grunt-contrib-connect](https://www.npmjs.com/package/grunt-contrib-connect) - [grunt-browser-sync](https://www.npmjs.com/package/grunt-browser-sync) - [gulp-connect](https://www.npmjs.com/package/gulp-connect) - [gulp-webserver](https://www.npmjs.com/package/gulp-webserver) Sample implementations can be found in the [server recipes](https://github.com/chimurai/http-proxy-middleware/tree/master/recipes/servers.md). ## Tests Run the test suite: ```bash # install dependencies $ npm install # linting $ npm run lint # unit tests $ npm test # code coverage $ npm run cover ``` ## Changelog - [View changelog](https://github.com/chimurai/http-proxy-middleware/blob/master/CHANGELOG.md) ## License The MIT License (MIT) Copyright (c) 2015-2018 Steven Chim # sha.js [![NPM Package](https://img.shields.io/npm/v/sha.js.svg?style=flat-square)](https://www.npmjs.org/package/sha.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/sha.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/sha.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/sha.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/sha.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `SHA` on pure JavaScript. ```js var shajs = require('sha.js') console.log(shajs('sha256').update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 console.log(new shajs.sha256().update('42').digest('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 var sha256stream = shajs('sha256') sha256stream.end('42') console.log(sha256stream.read().toString('hex')) // => 73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049 ``` ## supported hashes `sha.js` currently implements: - SHA (SHA-0) -- **legacy, do not use in new systems** - SHA-1 -- **legacy, do not use in new systems** - SHA-224 - SHA-256 - SHA-384 - SHA-512 ## Not an actual stream Note, this doesn't actually implement a stream, but wrapping this in a stream is trivial. It does update incrementally, so you can hash things larger than RAM, as it uses a constant amount of memory (except when using base64 or utf8 encoding, see code comments). ## Acknowledgements This work is derived from Paul Johnston's [A JavaScript implementation of the Secure Hash Algorithm](http://pajhome.org.uk/crypt/md5/sha1.html). ## LICENSE [MIT](LICENSE) # rc The non-configurable configuration loader for lazy people. ## Usage The only option is to pass rc the name of your app, and your default configuration. ```javascript var conf = require('rc')(appname, { //defaults go here. port: 2468, //defaults which are objects will be merged, not replaced views: { engine: 'jade' } }); ``` `rc` will return your configuration options merged with the defaults you specify. If you pass in a predefined defaults object, it will be mutated: ```javascript var conf = {}; require('rc')(appname, conf); ``` If `rc` finds any config files for your app, the returned config object will have a `configs` array containing their paths: ```javascript var appCfg = require('rc')(appname, conf); appCfg.configs[0] // /etc/appnamerc appCfg.configs[1] // /home/dominictarr/.config/appname appCfg.config // same as appCfg.configs[appCfg.configs.length - 1] ``` ## Standards Given your application name (`appname`), rc will look in all the obvious places for configuration. * command line arguments, parsed by minimist _(e.g. `--foo baz`, also nested: `--foo.bar=baz`)_ * environment variables prefixed with `${appname}_` * or use "\_\_" to indicate nested properties <br/> _(e.g. `appname_foo__bar__baz` => `foo.bar.baz`)_ * if you passed an option `--config file` then from that file * a local `.${appname}rc` or the first found looking in `./ ../ ../../ ../../../` etc. * `$HOME/.${appname}rc` * `$HOME/.${appname}/config` * `$HOME/.config/${appname}` * `$HOME/.config/${appname}/config` * `/etc/${appname}rc` * `/etc/${appname}/config` * the defaults object you passed in. All configuration sources that were found will be flattened into one object, so that sources **earlier** in this list override later ones. ## Configuration File Formats Configuration files (e.g. `.appnamerc`) may be in either [json](http://json.org/example) or [ini](http://en.wikipedia.org/wiki/INI_file) format. **No** file extension (`.json` or `.ini`) should be used. The example configurations below are equivalent: #### Formatted as `ini` ``` ; You can include comments in `ini` format if you want. dependsOn=0.10.0 ; `rc` has built-in support for ini sections, see? [commands] www = ./commands/www console = ./commands/repl ; You can even do nested sections [generators.options] engine = ejs [generators.modules] new = generate-new engine = generate-backend ``` #### Formatted as `json` ```javascript { // You can even comment your JSON, if you want "dependsOn": "0.10.0", "commands": { "www": "./commands/www", "console": "./commands/repl" }, "generators": { "options": { "engine": "ejs" }, "modules": { "new": "generate-new", "backend": "generate-backend" } } } ``` Comments are stripped from JSON config via [strip-json-comments](https://github.com/sindresorhus/strip-json-comments). > Since ini, and env variables do not have a standard for types, your application needs be prepared for strings. To ensure that string representations of booleans and numbers are always converted into their proper types (especially useful if you intend to do strict `===` comparisons), consider using a module such as [parse-strings-in-object](https://github.com/anselanza/parse-strings-in-object) to wrap the config object returned from rc. ## Simple example demonstrating precedence Assume you have an application like this (notice the hard-coded defaults passed to rc): ``` const conf = require('rc')('myapp', { port: 12345, mode: 'test' }); console.log(JSON.stringify(conf, null, 2)); ``` You also have a file `config.json`, with these contents: ``` { "port": 9000, "foo": "from config json", "something": "else" } ``` And a file `.myapprc` in the same folder, with these contents: ``` { "port": "3001", "foo": "bar" } ``` Here is the expected output from various commands: `node .` ``` { "port": "3001", "mode": "test", "foo": "bar", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Default `mode` from hard-coded object is retained, but port is overridden by `.myapprc` file (automatically found based on appname match), and `foo` is added.* `node . --foo baz` ``` { "port": "3001", "mode": "test", "foo": "baz", "_": [], "configs": [ "/Users/stephen/repos/conftest/.myapprc" ], "config": "/Users/stephen/repos/conftest/.myapprc" } ``` *Same result as above but `foo` is overridden because command-line arguments take precedence over `.myapprc` file.* `node . --foo barbar --config config.json` ``` { "port": 9000, "mode": "test", "foo": "barbar", "something": "else", "_": [], "config": "config.json", "configs": [ "/Users/stephen/repos/conftest/.myapprc", "config.json" ] } ``` *Now the `port` comes from the `config.json` file specified (overriding the value from `.myapprc`), and `foo` value is overriden by command-line despite also being specified in the `config.json` file.* ## Advanced Usage #### Pass in your own `argv` You may pass in your own `argv` as the third argument to `rc`. This is in case you want to [use your own command-line opts parser](https://github.com/dominictarr/rc/pull/12). ```javascript require('rc')(appname, defaults, customArgvParser); ``` ## Pass in your own parser If you have a special need to use a non-standard parser, you can do so by passing in the parser as the 4th argument. (leave the 3rd as null to get the default args parser) ```javascript require('rc')(appname, defaults, null, parser); ``` This may also be used to force a more strict format, such as strict, valid JSON only. ## Note on Performance `rc` is running `fs.statSync`-- so make sure you don't use it in a hot code path (e.g. a request handler) ## License Multi-licensed under the two-clause BSD License, MIT License, or Apache License, version 2.0 # normalize-package-data [![Build Status](https://travis-ci.org/npm/normalize-package-data.png?branch=master)](https://travis-ci.org/npm/normalize-package-data) normalize-package-data exports a function that normalizes package metadata. This data is typically found in a package.json file, but in principle could come from any source - for example the npm registry. normalize-package-data is used by [read-package-json](https://npmjs.org/package/read-package-json) to normalize the data it reads from a package.json file. In turn, read-package-json is used by [npm](https://npmjs.org/package/npm) and various npm-related tools. ## Installation ``` npm install normalize-package-data ``` ## Usage Basic usage is really simple. You call the function that normalize-package-data exports. Let's call it `normalizeData`. ```javascript normalizeData = require('normalize-package-data') packageData = require("./package.json") normalizeData(packageData) // packageData is now normalized ``` #### Strict mode You may activate strict validation by passing true as the second argument. ```javascript normalizeData = require('normalize-package-data') packageData = require("./package.json") normalizeData(packageData, true) // packageData is now normalized ``` If strict mode is activated, only Semver 2.0 version strings are accepted. Otherwise, Semver 1.0 strings are accepted as well. Packages must have a name, and the name field must not have contain leading or trailing whitespace. #### Warnings Optionally, you may pass a "warning" function. It gets called whenever the `normalizeData` function encounters something that doesn't look right. It indicates less than perfect input data. ```javascript normalizeData = require('normalize-package-data') packageData = require("./package.json") warnFn = function(msg) { console.error(msg) } normalizeData(packageData, warnFn) // packageData is now normalized. Any number of warnings may have been logged. ``` You may combine strict validation with warnings by passing `true` as the second argument, and `warnFn` as third. When `private` field is set to `true`, warnings will be suppressed. ### Potential exceptions If the supplied data has an invalid name or version vield, `normalizeData` will throw an error. Depending on where you call `normalizeData`, you may want to catch these errors so can pass them to a callback. ## What normalization (currently) entails * The value of `name` field gets trimmed (unless in strict mode). * The value of the `version` field gets cleaned by `semver.clean`. See [documentation for the semver module](https://github.com/isaacs/node-semver). * If `name` and/or `version` fields are missing, they are set to empty strings. * If `files` field is not an array, it will be removed. * If `bin` field is a string, then `bin` field will become an object with `name` set to the value of the `name` field, and `bin` set to the original string value. * If `man` field is a string, it will become an array with the original string as its sole member. * If `keywords` field is string, it is considered to be a list of keywords separated by one or more white-space characters. It gets converted to an array by splitting on `\s+`. * All people fields (`author`, `maintainers`, `contributors`) get converted into objects with name, email and url properties. * If `bundledDependencies` field (a typo) exists and `bundleDependencies` field does not, `bundledDependencies` will get renamed to `bundleDependencies`. * If the value of any of the dependencies fields (`dependencies`, `devDependencies`, `optionalDependencies`) is a string, it gets converted into an object with familiar `name=>value` pairs. * The values in `optionalDependencies` get added to `dependencies`. The `optionalDependencies` array is left untouched. * As of v2: Dependencies that point at known hosted git providers (currently: github, bitbucket, gitlab) will have their URLs canonicalized, but protocols will be preserved. * As of v2: Dependencies that use shortcuts for hosted git providers (`org/proj`, `github:org/proj`, `bitbucket:org/proj`, `gitlab:org/proj`, `gist:docid`) will have the shortcut left in place. (In the case of github, the `org/proj` form will be expanded to `github:org/proj`.) THIS MARKS A BREAKING CHANGE FROM V1, where the shorcut was previously expanded to a URL. * If `description` field does not exist, but `readme` field does, then (more or less) the first paragraph of text that's found in the readme is taken as value for `description`. * If `repository` field is a string, it will become an object with `url` set to the original string value, and `type` set to `"git"`. * If `repository.url` is not a valid url, but in the style of "[owner-name]/[repo-name]", `repository.url` will be set to git+https://github.com/[owner-name]/[repo-name].git * If `bugs` field is a string, the value of `bugs` field is changed into an object with `url` set to the original string value. * If `bugs` field does not exist, but `repository` field points to a repository hosted on GitHub, the value of the `bugs` field gets set to an url in the form of https://github.com/[owner-name]/[repo-name]/issues . If the repository field points to a GitHub Gist repo url, the associated http url is chosen. * If `bugs` field is an object, the resulting value only has email and url properties. If email and url properties are not strings, they are ignored. If no valid values for either email or url is found, bugs field will be removed. * If `homepage` field is not a string, it will be removed. * If the url in the `homepage` field does not specify a protocol, then http is assumed. For example, `myproject.org` will be changed to `http://myproject.org`. * If `homepage` field does not exist, but `repository` field points to a repository hosted on GitHub, the value of the `homepage` field gets set to an url in the form of https://github.com/[owner-name]/[repo-name]#readme . If the repository field points to a GitHub Gist repo url, the associated http url is chosen. ### Rules for name field If `name` field is given, the value of the name field must be a string. The string may not: * start with a period. * contain the following characters: `/@\s+%` * contain any characters that would need to be encoded for use in urls. * resemble the word `node_modules` or `favicon.ico` (case doesn't matter). ### Rules for version field If `version` field is given, the value of the version field must be a valid *semver* string, as determined by the `semver.valid` method. See [documentation for the semver module](https://github.com/isaacs/node-semver). ### Rules for license field The `license` field should be a valid *SPDX license expression* or one of the special values allowed by [validate-npm-package-license](https://npmjs.com/package/validate-npm-package-license). See [documentation for the license field in package.json](https://docs.npmjs.com/files/package.json#license). ## Credits This package contains code based on read-package-json written by Isaac Z. Schlueter. Used with permisson. ## License normalize-package-data is released under the [BSD 2-Clause License](http://opensource.org/licenses/MIT). Copyright (c) 2013 Meryn Stol If you want to write an option parser, and have it be good, there are two ways to do it. The Right Way, and the Wrong Way. The Wrong Way is to sit down and write an option parser. We've all done that. The Right Way is to write some complex configurable program with so many options that you hit the limit of your frustration just trying to manage them all, and defer it with duct-tape solutions until you see exactly to the core of the problem, and finally snap and write an awesome option parser. If you want to write an option parser, don't write an option parser. Write a package manager, or a source control system, or a service restarter, or an operating system. You probably won't end up with a good one of those, but if you don't give up, and you are relentless and diligent enough in your procrastination, you may just end up with a very nice option parser. ## USAGE // my-program.js var nopt = require("nopt") , Stream = require("stream").Stream , path = require("path") , knownOpts = { "foo" : [String, null] , "bar" : [Stream, Number] , "baz" : path , "bloo" : [ "big", "medium", "small" ] , "flag" : Boolean , "pick" : Boolean , "many1" : [String, Array] , "many2" : [path] } , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] , "b7" : ["--bar", "7"] , "m" : ["--bloo", "medium"] , "p" : ["--pick"] , "f" : ["--flag"] } // everything is optional. // knownOpts and shorthands default to {} // arg list defaults to process.argv // slice defaults to 2 , parsed = nopt(knownOpts, shortHands, process.argv, 2) console.log(parsed) This would give you support for any of the following: ```bash $ node my-program.js --foo "blerp" --no-flag { "foo" : "blerp", "flag" : false } $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag { bar: 7, foo: "Mr. Hand", flag: true } $ node my-program.js --foo "blerp" -f -----p { foo: "blerp", flag: true, pick: true } $ node my-program.js -fp --foofoo { foo: "Mr. Foo", flag: true, pick: true } $ node my-program.js --foofoo -- -fp # -- stops the flag parsing. { foo: "Mr. Foo", argv: { remain: ["-fp"] } } $ node my-program.js --blatzk -fp # unknown opts are ok. { blatzk: true, flag: true, pick: true } $ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value { blatzk: 1000, flag: true, pick: true } $ node my-program.js --no-blatzk -fp # unless they start with "no-" { blatzk: false, flag: true, pick: true } $ node my-program.js --baz b/a/z # known paths are resolved. { baz: "/Users/isaacs/b/a/z" } # if Array is one of the types, then it can take many # values, and will always be an array. The other types provided # specify what types are allowed in the list. $ node my-program.js --many1 5 --many1 null --many1 foo { many1: ["5", "null", "foo"] } $ node my-program.js --many2 foo --many2 bar { many2: ["/path/to/foo", "path/to/bar"] } ``` Read the tests at the bottom of `lib/nopt.js` for more examples of what this puppy can do. ## Types The following types are supported, and defined on `nopt.typeDefs` * String: A normal string. No parsing is done. * path: A file system path. Gets resolved against cwd if not absolute. * url: A url. If it doesn't parse, it isn't accepted. * Number: Must be numeric. * Date: Must parse as a date. If it does, and `Date` is one of the options, then it will return a Date object, not a string. * Boolean: Must be either `true` or `false`. If an option is a boolean, then it does not need a value, and its presence will imply `true` as the value. To negate boolean flags, do `--no-whatever` or `--whatever false` * NaN: Means that the option is strictly not allowed. Any value will fail. * Stream: An object matching the "Stream" class in node. Valuable for use when validating programmatically. (npm uses this to let you supply any WriteStream on the `outfd` and `logfd` config options.) * Array: If `Array` is specified as one of the types, then the value will be parsed as a list of options. This means that multiple values can be specified, and that the value will always be an array. If a type is an array of values not on this list, then those are considered valid values. For instance, in the example above, the `--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, and any other value will be rejected. When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be interpreted as their JavaScript equivalents. You can also mix types and values, or multiple types, in a list. For instance `{ blah: [Number, null] }` would allow a value to be set to either a Number or null. When types are ordered, this implies a preference, and the first type that can be used to properly interpret the value will be used. To define a new type, add it to `nopt.typeDefs`. Each item in that hash is an object with a `type` member and a `validate` method. The `type` member is an object that matches what goes in the type list. The `validate` method is a function that gets called with `validate(data, key, val)`. Validate methods should assign `data[key]` to the valid value of `val` if it can be handled properly, or return boolean `false` if it cannot. You can also call `nopt.clean(data, types, typeDefs)` to clean up a config object and remove its invalid properties. ## Error Handling By default, nopt outputs a warning to standard error when invalid values for known options are found. You can change this behavior by assigning a method to `nopt.invalidHandler`. This method will be called with the offending `nopt.invalidHandler(key, val, types)`. If no `nopt.invalidHandler` is assigned, then it will console.error its whining. If it is assigned to boolean `false` then the warning is suppressed. ## Abbreviations Yes, they are supported. If you define options like this: ```javascript { "foolhardyelephants" : Boolean , "pileofmonkeys" : Boolean } ``` Then this will work: ```bash node program.js --foolhar --pil node program.js --no-f --pileofmon # etc. ``` ## Shorthands Shorthands are a hash of shorter option names to a snippet of args that they expand to. If multiple one-character shorthands are all combined, and the combination does not unambiguously match any other option or shorthand, then they will be broken up into their constituent parts. For example: ```json { "s" : ["--loglevel", "silent"] , "g" : "--global" , "f" : "--force" , "p" : "--parseable" , "l" : "--long" } ``` ```bash npm ls -sgflp # just like doing this: npm ls --loglevel silent --global --force --long --parseable ``` ## The Rest of the args The config object returned by nopt is given a special member called `argv`, which is an object with the following fields: * `remain`: The remaining args after all the parsing has occurred. * `original`: The args as they originally appeared. * `cooked`: The args after flags and shorthands are expanded. ## Slicing Node programs are called with more or less the exact argv as it appears in C land, after the v8 and node-specific options have been plucked off. As such, `argv[0]` is always `node` and `argv[1]` is always the JavaScript program being run. That's usually not very useful to you. So they're sliced off by default. If you want them, then you can pass in `0` as the last argument, or any other number that you'd like to slice off the start of the list. ## getpass Get a password from the terminal. Sounds simple? Sounds like the `readline` module should be able to do it? NOPE. ## Install and use it ```bash npm install --save getpass ``` ```javascript const mod_getpass = require('getpass'); ``` ## API ### `mod_getpass.getPass([options, ]callback)` Gets a password from the terminal. If available, this uses `/dev/tty` to avoid interfering with any data being piped in or out of stdio. This function prints a prompt (by default `Password:`) and then accepts input without echoing. Parameters: * `options`, an Object, with properties: * `prompt`, an optional String * `callback`, a `Func(error, password)`, with arguments: * `error`, either `null` (no error) or an `Error` instance * `password`, a String # node-libs-browser The node core libs for in-browser usage. [![dependencies status](http://david-dm.org/webpack/node-libs-browser.png)](http://david-dm.org/webpack/node-libs-browser) Exports a hash [object] of absolute paths to each lib, keyed by lib names. Modules without browser replacements are `null`. Some modules have mocks in the `mock` directory. These are replacements with minimal functionality. | lib name | browser implementation | mock implementation | |:--------:|:----------------------:|:-------------------:| | assert | [defunctzombie/commonjs-assert](https://github.com/defunctzombie/commonjs-assert) | --- | | buffer | [feross/buffer](https://github.com/feross/buffer) | [buffer.js](https://github.com/webpack/node-libs-browser/blob/master/mock/buffer.js) | | child_process | --- | --- | | cluster | --- | --- | | console | [Raynos/console-browserify](https://github.com/Raynos/console-browserify) | [console.js](https://github.com/webpack/node-libs-browser/blob/master/mock/console.js) | | constants | [juliangruber/constants-browserify](https://github.com/juliangruber/constants-browserify) | --- | | crypto | [crypto-browserify/crypto-browserify](https://github.com/crypto-browserify/crypto-browserify) | --- | | dgram | --- | --- | | dns | --- | [dns.js](https://github.com/webpack/node-libs-browser/blob/master/mock/dns.js) | | domain | [bevry/domain-browser](https://github.com/bevry/domain-browser) | --- | | events | [Gozala/events](https://github.com/Gozala/events) | --- | | fs | --- | --- | | http | [jhiesey/stream-http](https://github.com/jhiesey/stream-http) | --- | | https | [substack/https-browserify](https://github.com/substack/https-browserify) | --- | | module | --- | --- | | net | --- | [net.js](https://github.com/webpack/node-libs-browser/blob/master/mock/net.js) | | os | [CoderPuppy/os-browserify](https://github.com/CoderPuppy/os-browserify) | --- | | path | [substack/path-browserify](https://github.com/substack/path-browserify) | --- | | process | [shtylman/node-process](https://github.com/shtylman/node-process) | [process.js](https://github.com/webpack/node-libs-browser/blob/master/mock/process.js) | | punycode | [bestiejs/punycode.js](https://github.com/bestiejs/punycode.js) | --- | | querystring | [mike-spainhower/querystring](https://github.com/mike-spainhower/querystring) | --- | | readline | --- | --- | | repl | --- | --- | | stream | [substack/stream-browserify](https://github.com/substack/stream-browserify) | --- | | string_decoder | [rvagg/string_decoder](https://github.com/rvagg/string_decoder) | --- | | sys | [defunctzombie/node-util](https://github.com/defunctzombie/node-util) | --- | | timers | [jryans/timers-browserify](https://github.com/jryans/timers-browserify) | --- | | tls | --- | [tls.js](https://github.com/webpack/node-libs-browser/blob/master/mock/tls.js) | | tty | [substack/tty-browserify](https://github.com/substack/tty-browserify) | [tty.js](https://github.com/webpack/node-libs-browser/blob/master/mock/tty.js) | | url | [defunctzombie/node-url](https://github.com/defunctzombie/node-url) | --- | | util | [defunctzombie/node-util](https://github.com/defunctzombie/node-util) | --- | | vm | [substack/vm-browserify](https://github.com/substack/vm-browserify) | --- | | zlib | [devongovett/browserify-zlib](https://github.com/devongovett/browserify-zlib) | --- | ## Outdated versions ### `buffer` The current `buffer` implementation uses feross/[email protected] because feross/[email protected] relies on [typed arrays](https://github.com/feross/buffer/commit/5daca86b7cd5d2b8ccb167534d47421029f639e9#commitcomment-19698936). This will be dropped as soon as IE9 is not a typical browser target anymore. ### `punycode` The current `punycode` implementation uses bestiejs/[email protected] because bestiejs/[email protected] requires modern JS engines that understand `const` and `let`. It will be removed someday since it has already been [deprecated from the node API](https://nodejs.org/api/punycode.html). ## License MIT # yargs-parser [![Build Status](https://travis-ci.org/yargs/yargs-parser.png)](https://travis-ci.org/yargs/yargs-parser) [![Coverage Status](https://coveralls.io/repos/yargs/yargs-parser/badge.svg?branch=)](https://coveralls.io/r/yargs/yargs-parser?branch=master) [![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) [![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/yargs-parser/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/yargs-parser) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) The mighty option parser used by [yargs](https://github.com/yargs/yargs). visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. <img width="250" src="https://github.com/yargs/yargs-parser/blob/master/yargs-logo.png"> ## Example ```sh npm i yargs-parser --save ``` ```js var argv = require('yargs-parser')(process.argv.slice(2)) console.log(argv) ``` ```sh node example.js --foo=33 --bar hello { _: [], foo: 33, bar: 'hello' } ``` _or parse a string!_ ```js var argv = require('./')('--foo=99 --bar=33') console.log(argv) ``` ```sh { _: [], foo: 99, bar: 33 } ``` Convert an array of mixed types before passing to `yargs-parser`: ```js var parse = require('yargs-parser') parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings ``` ## API ### require('yargs-parser')(args, opts={}) Parses command line arguments returning a simple mapping of keys and values. **expects:** * `args`: a string or array of strings representing the options to parse. * `opts`: provide a set of hints indicating how `args` should be parsed: * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`. * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided (or throws an error), e.g. `{coerce: {foo: function (arg) {return modifiedArg}}}`. * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. * `opts.normalize`: `path.normalize()` will be applied to values set to this key. * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). * `opts.number`: keys should be treated as numbers. **returns:** * `obj`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. ### require('yargs-parser').detailed(args, opts={}) Parses a command line string, returning detailed information required by the yargs engine. **expects:** * `args`: a string or array of strings representing options to parse. * `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. **returns:** * `argv`: an object representing the parsed value of `args` * `key/value`: key value pairs for each argument and their aliases. * `_`: an array representing the positional arguments. * `error`: populated with an error object if an exception occurred during parsing. * `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. * `newAliases`: any new aliases added via camel-case expansion. * `configuration`: the configuration loaded from the `yargs` stanza in package.json. <a name="configuration"></a> ### Configuration The yargs-parser applies several automated transformations on the keys provided in `args`. These features can be turned on and off using the `configuration` field of `opts`. ```js var parsed = parser(['--no-dice'], { configuration: { 'boolean-negation': false } }) ``` ### short option groups * default: `true`. * key: `short-option-groups`. Should a group of short-options be treated as boolean flags? ```sh node example.js -abc { _: [], a: true, b: true, c: true } ``` _if disabled:_ ```sh node example.js -abc { _: [], abc: true } ``` ### camel-case expansion * default: `true`. * key: `camel-case-expansion`. Should hyphenated arguments be expanded into camel-case aliases? ```sh node example.js --foo-bar { _: [], 'foo-bar': true, fooBar: true } ``` _if disabled:_ ```sh node example.js --foo-bar { _: [], 'foo-bar': true } ``` ### dot-notation * default: `true` * key: `dot-notation` Should keys that contain `.` be treated as objects? ```sh node example.js --foo.bar { _: [], foo: { bar: true } } ``` _if disabled:_ ```sh node example.js --foo.bar { _: [], "foo.bar": true } ``` ### parse numbers * default: `true` * key: `parse-numbers` Should keys that look like numbers be treated as such? ```sh node example.js --foo=99.3 { _: [], foo: 99.3 } ``` _if disabled:_ ```sh node example.js --foo=99.3 { _: [], foo: "99.3" } ``` ### boolean negation * default: `true` * key: `boolean-negation` Should variables prefixed with `--no` be treated as negations? ```sh node example.js --no-foo { _: [], foo: false } ``` _if disabled:_ ```sh node example.js --no-foo { _: [], "no-foo": true } ``` ### duplicate arguments array * default: `true` * key: `duplicate-arguments-array` Should arguments be coerced into an array when duplicated: ```sh node example.js -x 1 -x 2 { _: [], x: [1, 2] } ``` _if disabled:_ ```sh node example.js -x 1 -x 2 { _: [], x: 2 } ``` ### flatten duplicate arrays * default: `true` * key: `flatten-duplicate-arrays` Should array arguments be coerced into a single array when duplicated: ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [1, 2, 3, 4] } ``` _if disabled:_ ```sh node example.js -x 1 2 -x 3 4 { _: [], x: [[1, 2], [3, 4]] } ``` ## Special Thanks The yargs project evolves from optimist and minimist. It owes its existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ ## License ISC # npmlog The logger util that npm uses. This logger is very basic. It does the logging for npm. It supports custom levels and colored output. By default, logs are written to stderr. If you want to send log messages to outputs other than streams, then you can change the `log.stream` member, or you can just listen to the events that it emits, and do whatever you want with them. # Installation ```console npm install npmlog --save ``` # Basic Usage ```javascript var log = require('npmlog') // additional stuff ---------------------------+ // message ----------+ | // prefix ----+ | | // level -+ | | | // v v v v log.info('fyi', 'I have a kitty cat: %j', myKittyCat) ``` ## log.level * {String} The level to display logs at. Any logs at or above this level will be displayed. The special level `silent` will prevent anything from being displayed ever. ## log.record * {Array} An array of all the log messages that have been entered. ## log.maxRecordSize * {Number} The maximum number of records to keep. If log.record gets bigger than 10% over this value, then it is sliced down to 90% of this value. The reason for the 10% window is so that it doesn't have to resize a large array on every log entry. ## log.prefixStyle * {Object} A style object that specifies how prefixes are styled. (See below) ## log.headingStyle * {Object} A style object that specifies how the heading is styled. (See below) ## log.heading * {String} Default: "" If set, a heading that is printed at the start of every line. ## log.stream * {Stream} Default: `process.stderr` The stream where output is written. ## log.enableColor() Force colors to be used on all messages, regardless of the output stream. ## log.disableColor() Disable colors on all messages. ## log.enableProgress() Enable the display of log activity spinner and progress bar ## log.disableProgress() Disable the display of a progress bar ## log.enableUnicode() Force the unicode theme to be used for the progress bar. ## log.disableUnicode() Disable the use of unicode in the progress bar. ## log.setGaugeTemplate(template) Set a template for outputting the progress bar. See the [gauge documentation] for details. [gauge documentation]: https://npmjs.com/package/gauge ## log.setGaugeThemeset(themes) Select a themeset to pick themes from for the progress bar. See the [gauge documentation] for details. ## log.pause() Stop emitting messages to the stream, but do not drop them. ## log.resume() Emit all buffered messages that were written while paused. ## log.log(level, prefix, message, ...) * `level` {String} The level to emit the message at * `prefix` {String} A string prefix. Set to "" to skip. * `message...` Arguments to `util.format` Emit a log message at the specified level. ## log\[level](prefix, message, ...) For example, * log.silly(prefix, message, ...) * log.verbose(prefix, message, ...) * log.info(prefix, message, ...) * log.http(prefix, message, ...) * log.warn(prefix, message, ...) * log.error(prefix, message, ...) Like `log.log(level, prefix, message, ...)`. In this way, each level is given a shorthand, so you can do `log.info(prefix, message)`. ## log.addLevel(level, n, style, disp) * `level` {String} Level indicator * `n` {Number} The numeric level * `style` {Object} Object with fg, bg, inverse, etc. * `disp` {String} Optional replacement for `level` in the output. Sets up a new level with a shorthand function and so forth. Note that if the number is `Infinity`, then setting the level to that will cause all log messages to be suppressed. If the number is `-Infinity`, then the only way to show it is to enable all log messages. ## log.newItem(name, todo, weight) * `name` {String} Optional; progress item name. * `todo` {Number} Optional; total amount of work to be done. Default 0. * `weight` {Number} Optional; the weight of this item relative to others. Default 1. This adds a new `are-we-there-yet` item tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `Tracker` object. ## log.newStream(name, todo, weight) This adds a new `are-we-there-yet` stream tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerStream` object. ## log.newGroup(name, weight) This adds a new `are-we-there-yet` tracker group to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerGroup` object. # Events Events are all emitted with the message object. * `log` Emitted for all messages * `log.<level>` Emitted for all messages with the `<level>` level. * `<prefix>` Messages with prefixes also emit their prefix as an event. # Style Objects Style objects can have the following fields: * `fg` {String} Color for the foreground text * `bg` {String} Color for the background * `bold`, `inverse`, `underline` {Boolean} Set the associated property * `bell` {Boolean} Make a noise (This is pretty annoying, probably.) # Message Objects Every log event is emitted with a message object, and the `log.record` list contains all of them that have been created. They have the following fields: * `id` {Number} * `level` {String} * `prefix` {String} * `message` {String} Result of `util.format()` * `messageRaw` {Array} Arguments to `util.format()` # Blocking TTYs We use [`set-blocking`](https://npmjs.com/package/set-blocking) to set stderr and stdout blocking if they are tty's and have the setBlocking call. This is a work around for an issue in early versions of Node.js 6.x, which made stderr and stdout non-blocking on OSX. (They are always blocking Windows and were never blocking on Linux.) `npmlog` needs them to be blocking so that it can allow output to stdout and stderr to be interlaced. # function-bind <!-- [![build status][travis-svg]][travis-url] [![NPM version][npm-badge-svg]][npm-url] [![Coverage Status][5]][6] [![gemnasium Dependency Status][7]][8] [![Dependency status][deps-svg]][deps-url] [![Dev Dependency status][dev-deps-svg]][dev-deps-url] --> <!-- [![browser support][11]][12] --> Implementation of function.prototype.bind ## Example I mainly do this for unit tests I run on phantomjs. PhantomJS does not have Function.prototype.bind :( ```js Function.prototype.bind = require("function-bind") ``` ## Installation `npm install function-bind` ## Contributors - Raynos ## MIT Licenced [travis-svg]: https://travis-ci.org/Raynos/function-bind.svg [travis-url]: https://travis-ci.org/Raynos/function-bind [npm-badge-svg]: https://badge.fury.io/js/function-bind.svg [npm-url]: https://npmjs.org/package/function-bind [5]: https://coveralls.io/repos/Raynos/function-bind/badge.png [6]: https://coveralls.io/r/Raynos/function-bind [7]: https://gemnasium.com/Raynos/function-bind.png [8]: https://gemnasium.com/Raynos/function-bind [deps-svg]: https://david-dm.org/Raynos/function-bind.svg [deps-url]: https://david-dm.org/Raynos/function-bind [dev-deps-svg]: https://david-dm.org/Raynos/function-bind/dev-status.svg [dev-deps-url]: https://david-dm.org/Raynos/function-bind#info=devDependencies [11]: https://ci.testling.com/Raynos/function-bind.png [12]: https://ci.testling.com/Raynos/function-bind > This README is for babel-loader v8 + Babel v7 > Check the [7.x branch](https://github.com/babel/babel-loader/tree/7.x) for docs with Babel v6 [![NPM Status](https://img.shields.io/npm/v/babel-loader.svg?style=flat)](https://www.npmjs.com/package/babel-loader) [![Build Status](https://travis-ci.org/babel/babel-loader.svg?branch=master)](https://travis-ci.org/babel/babel-loader) [![Build Status](https://ci.appveyor.com/api/projects/status/77y5mk6amwqt0q88/branch/master?svg=true)](https://ci.appveyor.com/project/babel/babel-loader/branch/master) [![codecov](https://codecov.io/gh/babel/babel-loader/branch/master/graph/badge.svg)](https://codecov.io/gh/babel/babel-loader) <div align="center"> <a href="https://github.com/babel/babel"> <img src="https://rawgit.com/babel/logo/master/babel.svg" alt="Babel logo" width="200" height="200"> </a> <a href="https://github.com/webpack/webpack"> <img src="https://webpack.js.org/assets/icon-square-big.svg" alt="webpack logo" width="200" height="200"> </a> </div> <h1 align="center">Babel Loader</h1> This package allows transpiling JavaScript files using [Babel](https://github.com/babel/babel) and [webpack](https://github.com/webpack/webpack). **Note**: Issues with the output should be reported on the Babel [Issues](https://github.com/babel/babel/issues) tracker. <h2 align="center">Install</h2> > webpack 4.x | babel-loader 8.x | babel 7.x ```bash npm install -D babel-loader @babel/core @babel/preset-env webpack ``` > webpack 4.x | babel-loader 7.x | babel 6.x ```bash npm install -D babel-loader@7 babel-core babel-preset-env webpack ``` <h2 align="center">Usage</h2> webpack documentation: [Loaders](https://webpack.js.org/loaders/) Within your webpack configuration object, you'll need to add the babel-loader to the list of modules, like so: ```javascript module: { rules: [ { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } ``` ### Options See the `babel` [options](https://babeljs.io/docs/en/options). You can pass options to the loader by using the [`options`](https://webpack.js.org/configuration/module/#rule-options-rule-query) property: ```javascript module: { rules: [ { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: ['@babel/plugin-proposal-object-rest-spread'] } } } ] } ``` This loader also supports the following loader-specific option: * `cacheDirectory`: Default `false`. When set, the given directory will be used to cache the results of the loader. Future webpack builds will attempt to read from the cache to avoid needing to run the potentially expensive Babel recompilation process on each run. If the value is blank (`loader: 'babel-loader?cacheDirectory'`) or `true` (`loader: 'babel-loader?cacheDirectory=true'`), the loader will use the default cache directory in `node_modules/.cache/babel-loader` or fallback to the default OS temporary file directory if no `node_modules` folder could be found in any root directory. * `cacheIdentifier`: Default is a string composed by the `babel-core`'s version, the `babel-loader`'s version, the contents of `.babelrc` file if it exists, and the value of the environment variable `BABEL_ENV` with a fallback to the `NODE_ENV` environment variable. This can be set to a custom value to force cache busting if the identifier changes. * `cacheCompression`: Default `true`. When set, each Babel transform output will be compressed with Gzip. If you want to opt-out of cache compression, set it to `false` -- your project may benefit from this if it transpiles thousands of files. * `customize`: Default `null`. The path of a module that exports a `custom` callback [like the one that you'd pass to `.custom()`](#customized-loader). Since you already have to make a new file to use this, it is recommended that you instead use `.custom` to create a wrapper loader. Only use this is you _must_ continue using `babel-loader` directly, but still want to customize. ## Troubleshooting ### babel-loader is slow! Make sure you are transforming as few files as possible. Because you are probably matching `/\.m?js$/`, you might be transforming the `node_modules` folder or other unwanted source. To exclude `node_modules`, see the `exclude` option in the `loaders` config as documented above. You can also speed up babel-loader by as much as 2x by using the `cacheDirectory` option. This will cache transformations to the filesystem. ### Babel is injecting helpers into each file and bloating my code! Babel uses very small helpers for common functions such as `_extend`. By default, this will be added to every file that requires it. You can instead require the Babel runtime as a separate module to avoid the duplication. The following configuration disables automatic per-file runtime injection in Babel, requiring `babel-plugin-transform-runtime` instead and making all helper references use it. See the [docs](https://babeljs.io/docs/plugins/transform-runtime/) for more information. **NOTE**: You must run `npm install -D @babel/plugin-transform-runtime` to include this in your project and `babel-runtime` itself as a dependency with `npm install @babel/runtime`. ```javascript rules: [ // the 'transform-runtime' plugin tells Babel to // require the runtime instead of inlining it. { test: /\.m?js$/, exclude: /(node_modules|bower_components)/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], plugins: ['@babel/plugin-transform-runtime'] } } } ] ``` #### **NOTE**: transform-runtime & custom polyfills (e.g. Promise library) Since [babel-plugin-transform-runtime](https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-runtime) includes a polyfill that includes a custom [regenerator-runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) and [core-js](https://github.com/zloirock/core-js), the following usual shimming method using `webpack.ProvidePlugin` will not work: ```javascript // ... new webpack.ProvidePlugin({ 'Promise': 'bluebird' }), // ... ``` The following approach will not work either: ```javascript require('@babel/runtime/core-js/promise').default = require('bluebird'); var promise = new Promise; ``` which outputs to (using `runtime`): ```javascript 'use strict'; var _Promise = require('@babel/runtime/core-js/promise')['default']; require('@babel/runtime/core-js/promise')['default'] = require('bluebird'); var promise = new _Promise(); ``` The previous `Promise` library is referenced and used before it is overridden. One approach is to have a "bootstrap" step in your application that would first override the default globals before your application: ```javascript // bootstrap.js require('@babel/runtime/core-js/promise').default = require('bluebird'); // ... require('./app'); ``` ### The Node.js API for `babel` has been moved to `babel-core`. If you receive this message, it means that you have the npm package `babel` installed and are using the short notation of the loader in the webpack config (which is not valid anymore as of webpack 2.x): ```javascript { test: /\.m?js$/, loader: 'babel', } ``` webpack then tries to load the `babel` package instead of the `babel-loader`. To fix this, you should uninstall the npm package `babel`, as it is deprecated in Babel v6. (Instead, install `babel-cli` or `babel-core`.) In the case one of your dependencies is installing `babel` and you cannot uninstall it yourself, use the complete name of the loader in the webpack config: ```javascript { test: /\.m?js$/, loader: 'babel-loader', } ``` ## Customized Loader `babel-loader` exposes a loader-builder utility that allows users to add custom handling of Babel's configuration for each file that it processes. `.custom` accepts a callback that will be called with the loader's instance of `babel` so that tooling can ensure that it using exactly the same `@babel/core` instance as the loader itself. In cases where you want to customize without actually having a file to call `.custom`, you may also pass the `customize` option with a string pointing at a file that exports your `custom` callback function. ### Example ```js // Export from "./my-custom-loader.js" or whatever you want. module.exports = require("babel-loader").custom(babel => { function myPlugin() { return { visitor: {}, }; } return { // Passed the loader options. customOptions({ opt1, opt2, ...loader }) { return { // Pull out any custom options that the loader might have. custom: { opt1, opt2 }, // Pass the options back with the two custom options removed. loader, }; }, // Passed Babel's 'PartialConfig' object. config(cfg) { if (cfg.hasFilesystemConfig()) { // Use the normal config return cfg.options; } return { ...cfg.options, plugins: [ ...(cfg.options.plugins || []), // Include a custom plugin in the options. myPlugin, ], }; }, result(result) { return { ...result, code: result.code + "\n// Generated by some custom loader", }; }, }; }); ``` ```js // And in your Webpack config module.exports = { // .. module: { rules: [{ // ... loader: path.join(__dirname, 'my-custom-loader.js'), // ... }] } }; ``` ### `customOptions(options: Object): { custom: Object, loader: Object }` Given the loader's options, split custom options out of `babel-loader`'s options. ### `config(cfg: PartialConfig): Object` Given Babel's `PartialConfig` object, return the `options` object that should be passed to `babel.transform`. ### `result(result: Result): Result` Given Babel's result object, allow loaders to make additional tweaks to it. ## License [MIT](https://couto.mit-license.org/) # unset-value [![NPM version](https://img.shields.io/npm/v/unset-value.svg?style=flat)](https://www.npmjs.com/package/unset-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/unset-value.svg?style=flat)](https://npmjs.org/package/unset-value) [![NPM total downloads](https://img.shields.io/npm/dt/unset-value.svg?style=flat)](https://npmjs.org/package/unset-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/unset-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/unset-value) > Delete nested properties from an object using dot notation. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save unset-value ``` ## Usage ```js var unset = require('unset-value'); var obj = {a: {b: {c: 'd', e: 'f'}}}; unset(obj, 'a.b.c'); console.log(obj); //=> {a: {b: {e: 'f'}}}; ``` ## Examples ### Updates the object when a property is deleted ```js var obj = {a: 'b'}; unset(obj, 'a'); console.log(obj); //=> {} ``` ### Returns true when a property is deleted ```js unset({a: 'b'}, 'a') // true ``` ### Returns `true` when a property does not exist This is consistent with `delete` behavior in that it does not throw when a property does not exist. ```js unset({a: {b: {c: 'd'}}}, 'd') // true ``` ### delete nested values ```js var one = {a: {b: {c: 'd'}}}; unset(one, 'a.b'); console.log(one); //=> {a: {}} var two = {a: {b: {c: 'd'}}}; unset(two, 'a.b.c'); console.log(two); //=> {a: {b: {}}} var three = {a: {b: {c: 'd', e: 'f'}}}; unset(three, 'a.b.c'); console.log(three); //=> {a: {b: {e: 'f'}}} ``` ### throws on invalid args ```js unset(); // 'expected an object.' ``` ## About ### Related projects * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [get-values](https://www.npmjs.com/package/get-values): Return an array of all values from the given object. | [homepage](https://github.com/jonschlinkert/get-values "Return an array of all values from the given object.") * [omit-value](https://www.npmjs.com/package/omit-value): Omit properties from an object or deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/omit-value) | [homepage](https://github.com/jonschlinkert/omit-value "Omit properties from an object or deeply nested property of an object using object path notation.") * [put-value](https://www.npmjs.com/package/put-value): Update only existing values from an object, works with dot notation paths like `a.b.c` and… [more](https://github.com/tunnckocore/put-value#readme) | [homepage](https://github.com/tunnckocore/put-value#readme "Update only existing values from an object, works with dot notation paths like `a.b.c` and support deep nesting.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [union-value](https://www.npmjs.com/package/union-value): Set an array of unique values as the property of an object. Supports setting deeply… [more](https://github.com/jonschlinkert/union-value) | [homepage](https://github.com/jonschlinkert/union-value "Set an array of unique values as the property of an object. Supports setting deeply nested properties using using object-paths/dot notation.") * [upsert-value](https://www.npmjs.com/package/upsert-value): Update or set nested values and any intermediaries with dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/doowb/upsert-value "Update or set nested values and any intermediaries with dot notation (`'a.b.c'`) paths.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 6 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.4.2, on February 25, 2017._ # lodash v4.17.11 The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules. ## Installation Using npm: ```shell $ npm i -g npm $ npm i --save lodash ``` In Node.js: ```js // Load the full build. var _ = require('lodash'); // Load the core build. var _ = require('lodash/core'); // Load the FP build for immutable auto-curried iteratee-first data-last methods. var fp = require('lodash/fp'); // Load method categories. var array = require('lodash/array'); var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles. var at = require('lodash/at'); var curryN = require('lodash/fp/curryN'); ``` See the [package source](https://github.com/lodash/lodash/tree/4.17.11-npm) for more details. **Note:**<br> Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL. ## Support Tested in Chrome 68-69, Firefox 61-62, IE 11, Edge 17, Safari 10-11, Node.js 6-10, & PhantomJS 2.1.1.<br> Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available. # is-callable <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] [![browser support][9]][10] Is this JS value callable? Works with Functions and GeneratorFunctions, despite ES6 @@toStringTag. ## Example ```js var isCallable = require('is-callable'); var assert = require('assert'); assert.notOk(isCallable(undefined)); assert.notOk(isCallable(null)); assert.notOk(isCallable(false)); assert.notOk(isCallable(true)); assert.notOk(isCallable([])); assert.notOk(isCallable({})); assert.notOk(isCallable(/a/g)); assert.notOk(isCallable(new RegExp('a', 'g'))); assert.notOk(isCallable(new Date())); assert.notOk(isCallable(42)); assert.notOk(isCallable(NaN)); assert.notOk(isCallable(Infinity)); assert.notOk(isCallable(new Number(42))); assert.notOk(isCallable('foo')); assert.notOk(isCallable(Object('foo'))); assert.ok(isCallable(function () {})); assert.ok(isCallable(function* () {})); assert.ok(isCallable(x => x * x)); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [1]: https://npmjs.org/package/is-callable [2]: http://versionbadg.es/ljharb/is-callable.svg [3]: https://travis-ci.org/ljharb/is-callable.svg [4]: https://travis-ci.org/ljharb/is-callable [5]: https://david-dm.org/ljharb/is-callable.svg [6]: https://david-dm.org/ljharb/is-callable [7]: https://david-dm.org/ljharb/is-callable/dev-status.svg [8]: https://david-dm.org/ljharb/is-callable#info=devDependencies [9]: https://ci.testling.com/ljharb/is-callable.png [10]: https://ci.testling.com/ljharb/is-callable [11]: https://nodei.co/npm/is-callable.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/is-callable.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/is-callable.svg [downloads-url]: http://npm-stat.com/charts.html?package=is-callable Like `chown -R`. Takes the same arguments as `fs.chown()` # parse-asn1 [![TRAVIS](https://secure.travis-ci.org/crypto-browserify/parse-asn1.png)](http://travis-ci.org/crypto-browserify/parse-asn1) [![NPM](http://img.shields.io/npm/v/parse-asn1.svg)](https://www.npmjs.org/package/parse-asn1) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) utility library for parsing asn1 files for use with browserify-sign. # fresh [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP response freshness testing ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ``` $ npm install fresh ``` ## API <!-- eslint-disable no-unused-vars --> ```js var fresh = require('fresh') ``` ### fresh(reqHeaders, resHeaders) Check freshness of the response using request and response headers. When the response is still "fresh" in the client's cache `true` is returned, otherwise `false` is returned to indicate that the client cache is now stale and the full response should be sent. When a client sends the `Cache-Control: no-cache` request header to indicate an end-to-end reload request, this module will return `false` to make handling these requests transparent. ## Known Issues This module is designed to only follow the HTTP specifications, not to work-around all kinda of client bugs (especially since this module typically does not recieve enough information to understand what the client actually is). There is a known issue that in certain versions of Safari, Safari will incorrectly make a request that allows this module to validate freshness of the resource even when Safari does not have a representation of the resource in the cache. The module [jumanji](https://www.npmjs.com/package/jumanji) can be used in an Express application to work-around this issue and also provides links to further reading on this Safari bug. ## Example ### API usage <!-- eslint-disable no-redeclare, no-undef --> ```js var reqHeaders = { 'if-none-match': '"foo"' } var resHeaders = { 'etag': '"bar"' } fresh(reqHeaders, resHeaders) // => false var reqHeaders = { 'if-none-match': '"foo"' } var resHeaders = { 'etag': '"foo"' } fresh(reqHeaders, resHeaders) // => true ``` ### Using with Node.js http server ```js var fresh = require('fresh') var http = require('http') var server = http.createServer(function (req, res) { // perform server logic // ... including adding ETag / Last-Modified response headers if (isFresh(req, res)) { // client has a fresh copy of resource res.statusCode = 304 res.end() return } // send the resource res.statusCode = 200 res.end('hello, world!') }) function isFresh (req, res) { return fresh(req.headers, { 'etag': res.getHeader('ETag'), 'last-modified': res.getHeader('Last-Modified') }) } server.listen(3000) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/fresh.svg [npm-url]: https://npmjs.org/package/fresh [node-version-image]: https://img.shields.io/node/v/fresh.svg [node-version-url]: https://nodejs.org/en/ [travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg [travis-url]: https://travis-ci.org/jshttp/fresh [coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master [downloads-image]: https://img.shields.io/npm/dm/fresh.svg [downloads-url]: https://npmjs.org/package/fresh # which-module > Find the module object for something that was require()d [![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) [![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) Find the `module` object in `require.cache` for something that was `require()`d or `import`ed - essentially a reverse `require()` lookup. Useful for libs that want to e.g. lookup a filename for a module or submodule that it did not `require()` itself. ## Install and Usage ``` npm install --save which-module ``` ```js const whichModule = require('which-module') console.log(whichModule(require('something'))) // Module { // id: '/path/to/project/node_modules/something/index.js', // exports: [Function], // parent: ..., // filename: '/path/to/project/node_modules/something/index.js', // loaded: true, // children: [], // paths: [ '/path/to/project/node_modules/something/node_modules', // '/path/to/project/node_modules', // '/path/to/node_modules', // '/path/node_modules', // '/node_modules' ] } ``` ## API ### `whichModule(exported)` Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), if any, that represents the given argument in the `require.cache`. `exported` can be anything that was previously `require()`d or `import`ed as a module, submodule, or dependency - which means `exported` is identical to the `module.exports` returned by this method. If `exported` did not come from the `exports` of a `module` in `require.cache`, then this method returns `null`. ## License ISC © Contributors # requires-port [![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](http://img.shields.io/npm/v/requires-port.svg?style=flat-square)](http://browsenpm.org/package/requires-port)[![Build Status](http://img.shields.io/travis/unshiftio/requires-port/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/requires-port)[![Dependencies](https://img.shields.io/david/unshiftio/requires-port.svg?style=flat-square)](https://david-dm.org/unshiftio/requires-port)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/requires-port/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/requires-port?branch=master)[![IRC channel](http://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](http://webchat.freenode.net/?channels=unshift) The module name says it all, check if a protocol requires a given port. ## Installation This module is intended to be used with browserify or Node.js and is distributed in the public npm registry. To install it simply run the following command from your CLI: ```j npm install --save requires-port ``` ## Usage The module exports it self as function and requires 2 arguments: 1. The port number, can be a string or number. 2. Protocol, can be `http`, `http:` or even `https://yomoma.com`. We just split it at `:` and use the first result. We currently accept the following protocols: - `http` - `https` - `ws` - `wss` - `ftp` - `gopher` - `file` It returns a boolean that indicates if protocol requires this port to be added to your URL. ```js 'use strict'; var required = require('requires-port'); console.log(required('8080', 'http')) // true console.log(required('80', 'http')) // false ``` # License MIT <h1 align="center">Neo-Async</h1> <p align="center"> <img src="https://raw.githubusercontent.com/wiki/suguru03/neo-async/images/neo_async_v2.png" width="250px" /> </p> <p align="center"> <a href="https://www.npmjs.com/package/neo-async"><img alt="npm" src="https://img.shields.io/npm/v/neo-async.svg"></a> <a href="https://travis-ci.org/suguru03/neo-async"><img alt="Travis Status" src="https://img.shields.io/travis/suguru03/neo-async.svg"></a> <a href="https://codecov.io/gh/suguru03/neo-async"><img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/suguru03/neo-async/master.svg"></a> <a href="https://www.npmjs.com/package/neo-async"><img alt="download" src="https://img.shields.io/npm/dm/neo-async.svg"></a> <a href="https://lgtm.com/projects/g/suguru03/neo-async/context:javascript"><img src="https://img.shields.io/lgtm/grade/javascript/g/suguru03/neo-async.svg?logo=lgtm&logoWidth=18" alt="Code Quality: Javascript" height="18"></a> <a href="https://lgtm.com/projects/g/suguru03/neo-async/alerts"><img src="https://img.shields.io/lgtm/alerts/g/suguru03/neo-async.svg?logo=lgtm&logoWidth=18" alt="Total Alerts" height="18"></a> </p> Neo-Async is thought to be used as a drop-in replacement for [Async](https://github.com/caolan/async), it almost fully covers its functionality and runs [faster](#benchmark). Benchmark is [here](#benchmark)! Bluebird's benchmark is [here](https://github.com/suguru03/bluebird/tree/aigle/benchmark)! ## Code Coverage ![coverage](https://raw.githubusercontent.com/wiki/suguru03/neo-async/images/coverage.png) ## Installation ### In a browser ```html <script src="async.min.js"></script> ``` ### In an AMD loader ```js require(['async'], function(async) {}); ``` ### Promise and async/await I recommend to use [`Aigle`](https://github.com/suguru03/aigle). It is optimized for Promise handling and has almost the same functionality as `neo-async`. ### Node.js #### standard ```bash $ npm install neo-async ``` ```js var async = require('neo-async'); ``` #### replacement ```bash $ npm install neo-async $ ln -s ./node_modules/neo-async ./node_modules/async ``` ```js var async = require('async'); ``` ### Bower ```bash bower install neo-async ``` ## Feature [JSDoc](http://suguru03.github.io/neo-async/doc/async.html) \* not in Async ### Collections - [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) - [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) - [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) - [`forEach`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) - [`forEachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) - [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) - [`eachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) - [`eachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) - [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`eachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) - [`forEachOf`](http://suguru03.github.io/neo-async/doc/async.each.html) -> [`each`](http://suguru03.github.io/neo-async/doc/async.each.html) - [`forEachOfSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) -> [`eachSeries`](http://suguru03.github.io/neo-async/doc/async.eachSeries.html) - [`eachOfLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) -> [`forEachLimit`](http://suguru03.github.io/neo-async/doc/async.eachLimit.html) - [`map`](http://suguru03.github.io/neo-async/doc/async.map.html) - [`mapSeries`](http://suguru03.github.io/neo-async/doc/async.mapSeries.html) - [`mapLimit`](http://suguru03.github.io/neo-async/doc/async.mapLimit.html) - [`mapValues`](http://suguru03.github.io/neo-async/doc/async.mapValues.html) - [`mapValuesSeries`](http://suguru03.github.io/neo-async/doc/async.mapValuesSeries.html) - [`mapValuesLimit`](http://suguru03.github.io/neo-async/doc/async.mapValuesLimit.html) - [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) - [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) - [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) - [`select`](http://suguru03.github.io/neo-async/doc/async.filter.html) -> [`filter`](http://suguru03.github.io/neo-async/doc/async.filter.html) - [`selectSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) -> [`filterSeries`](http://suguru03.github.io/neo-async/doc/async.filterSeries.html) - [`selectLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) -> [`filterLimit`](http://suguru03.github.io/neo-async/doc/async.filterLimit.html) - [`reject`](http://suguru03.github.io/neo-async/doc/async.reject.html) - [`rejectSeries`](http://suguru03.github.io/neo-async/doc/async.rejectSeries.html) - [`rejectLimit`](http://suguru03.github.io/neo-async/doc/async.rejectLimit.html) - [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) - [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) - [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) - [`find`](http://suguru03.github.io/neo-async/doc/async.detect.html) -> [`detect`](http://suguru03.github.io/neo-async/doc/async.detect.html) - [`findSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) -> [`detectSeries`](http://suguru03.github.io/neo-async/doc/async.detectSeries.html) - [`findLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) -> [`detectLimit`](http://suguru03.github.io/neo-async/doc/async.detectLimit.html) - [`pick`](http://suguru03.github.io/neo-async/doc/async.pick.html) * - [`pickSeries`](http://suguru03.github.io/neo-async/doc/async.pickSeries.html) * - [`pickLimit`](http://suguru03.github.io/neo-async/doc/async.pickLimit.html) * - [`omit`](http://suguru03.github.io/neo-async/doc/async.omit.html) * - [`omitSeries`](http://suguru03.github.io/neo-async/doc/async.omitSeries.html) * - [`omitLimit`](http://suguru03.github.io/neo-async/doc/async.omitLimit.html) * - [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) - [`inject`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) - [`foldl`](http://suguru03.github.io/neo-async/doc/async.reduce.html) -> [`reduce`](http://suguru03.github.io/neo-async/doc/async.reduce.html) - [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) - [`foldr`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) -> [`reduceRight`](http://suguru03.github.io/neo-async/doc/async.reduceRight.html) - [`transform`](http://suguru03.github.io/neo-async/doc/async.transform.html) - [`transformSeries`](http://suguru03.github.io/neo-async/doc/async.transformSeries.html) * - [`transformLimit`](http://suguru03.github.io/neo-async/doc/async.transformLimit.html) * - [`sortBy`](http://suguru03.github.io/neo-async/doc/async.sortBy.html) - [`sortBySeries`](http://suguru03.github.io/neo-async/doc/async.sortBySeries.html) * - [`sortByLimit`](http://suguru03.github.io/neo-async/doc/async.sortByLimit.html) * - [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) - [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) - [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) - [`any`](http://suguru03.github.io/neo-async/doc/async.some.html) -> [`some`](http://suguru03.github.io/neo-async/doc/async.some.html) - [`anySeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) -> [`someSeries`](http://suguru03.github.io/neo-async/doc/async.someSeries.html) - [`anyLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) -> [`someLimit`](http://suguru03.github.io/neo-async/doc/async.someLimit.html) - [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) - [`everySeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) - [`everyLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) - [`all`](http://suguru03.github.io/neo-async/doc/async.every.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.every.html) - [`allSeries`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everySeries.html) - [`allLimit`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) -> [`every`](http://suguru03.github.io/neo-async/doc/async.everyLimit.html) - [`concat`](http://suguru03.github.io/neo-async/doc/async.concat.html) - [`concatSeries`](http://suguru03.github.io/neo-async/doc/async.concatSeries.html) - [`concatLimit`](http://suguru03.github.io/neo-async/doc/async.concatLimit.html) * ### Control Flow - [`parallel`](http://suguru03.github.io/neo-async/doc/async.parallel.html) - [`series`](http://suguru03.github.io/neo-async/doc/async.series.html) - [`parallelLimit`](http://suguru03.github.io/neo-async/doc/async.series.html) - [`tryEach`](http://suguru03.github.io/neo-async/doc/async.tryEach.html) - [`waterfall`](http://suguru03.github.io/neo-async/doc/async.waterfall.html) - [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * - [`angelfall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) -> [`angelFall`](http://suguru03.github.io/neo-async/doc/async.angelFall.html) * - [`whilst`](#whilst) - [`doWhilst`](#doWhilst) - [`until`](#until) - [`doUntil`](#doUntil) - [`during`](#during) - [`doDuring`](#doDuring) - [`forever`](#forever) - [`compose`](#compose) - [`seq`](#seq) - [`applyEach`](#applyEach) - [`applyEachSeries`](#applyEachSeries) - [`queue`](#queue) - [`priorityQueue`](#priorityQueue) - [`cargo`](#cargo) - [`auto`](#auto) - [`autoInject`](#autoInject) - [`retry`](#retry) - [`retryable`](#retryable) - [`iterator`](#iterator) - [`times`](http://suguru03.github.io/neo-async/doc/async.times.html) - [`timesSeries`](http://suguru03.github.io/neo-async/doc/async.timesSeries.html) - [`timesLimit`](http://suguru03.github.io/neo-async/doc/async.timesLimit.html) - [`race`](#race) ### Utils - [`apply`](#apply) - [`setImmediate`](#setImmediate) - [`nextTick`](#nextTick) - [`memoize`](#memoize) - [`unmemoize`](#unmemoize) - [`ensureAsync`](#ensureAsync) - [`constant`](#constant) - [`asyncify`](#asyncify) - [`wrapSync`](#asyncify) -> [`asyncify`](#asyncify) - [`log`](#log) - [`dir`](#dir) - [`timeout`](http://suguru03.github.io/neo-async/doc/async.timeout.html) - [`reflect`](#reflect) - [`reflectAll`](#reflectAll) - [`createLogger`](#createLogger) ## Mode - [`safe`](#safe) * - [`fast`](#fast) * ## Benchmark [Benchmark: Async vs Neo-Async](http://suguru03.hatenablog.com/entry/2016/06/10/135559) ### How to check ```bash $ node perf ``` ### Environment * Darwin 17.3.0 x64 * Node.js v8.9.4 * async v2.6.0 * neo-async v2.5.0 * benchmark v2.1.4 ### Result The value is the ratio (Neo-Async/Async) of the average speed. #### Collections |function|benchmark| |---|--:| |each/forEach|2.43| |eachSeries/forEachSeries|1.75| |eachLimit/forEachLimit|1.68| |eachOf|3.29| |eachOfSeries|1.50| |eachOfLimit|1.59| |map|3.95| |mapSeries|1.81| |mapLimit|1.27| |mapValues|2.73| |mapValuesSeries|1.59| |mapValuesLimit|1.23| |filter|3.00| |filterSeries|1.74| |filterLimit|1.17| |reject|4.59| |rejectSeries|2.31| |rejectLimit|1.58| |detect|4.30| |detectSeries|1.86| |detectLimit|1.32| |reduce|1.82| |transform|2.46| |sortBy|4.08| |some|2.19| |someSeries|1.83| |someLimit|1.32| |every|2.09| |everySeries|1.84| |everyLimit|1.35| |concat|3.79| |concatSeries|4.45| #### Control Flow |funciton|benchmark| |---|--:| |parallel|2.93| |series|1.96| |waterfall|1.29| |whilst|1.00| |doWhilst|1.12| |until|1.12| |doUntil|1.12| |during|1.18| |doDuring|2.42| |times|4.25| |auto|1.97| TweetNaCl.js ============ Port of [TweetNaCl](http://tweetnacl.cr.yp.to) / [NaCl](http://nacl.cr.yp.to/) to JavaScript for modern browsers and Node.js. Public domain. [![Build Status](https://travis-ci.org/dchest/tweetnacl-js.svg?branch=master) ](https://travis-ci.org/dchest/tweetnacl-js) Demo: <https://tweetnacl.js.org> **:warning: The library is stable and API is frozen, however it has not been independently reviewed. If you can help reviewing it, please [contact me](mailto:[email protected]).** Documentation ============= * [Overview](#overview) * [Installation](#installation) * [Usage](#usage) * [Public-key authenticated encryption (box)](#public-key-authenticated-encryption-box) * [Secret-key authenticated encryption (secretbox)](#secret-key-authenticated-encryption-secretbox) * [Scalar multiplication](#scalar-multiplication) * [Signatures](#signatures) * [Hashing](#hashing) * [Random bytes generation](#random-bytes-generation) * [Constant-time comparison](#constant-time-comparison) * [System requirements](#system-requirements) * [Development and testing](#development-and-testing) * [Benchmarks](#benchmarks) * [Contributors](#contributors) * [Who uses it](#who-uses-it) Overview -------- The primary goal of this project is to produce a translation of TweetNaCl to JavaScript which is as close as possible to the original C implementation, plus a thin layer of idiomatic high-level API on top of it. There are two versions, you can use either of them: * `nacl.js` is the port of TweetNaCl with minimum differences from the original + high-level API. * `nacl-fast.js` is like `nacl.js`, but with some functions replaced with faster versions. Installation ------------ You can install TweetNaCl.js via a package manager: [Bower](http://bower.io): $ bower install tweetnacl [NPM](https://www.npmjs.org/): $ npm install tweetnacl or [download source code](https://github.com/dchest/tweetnacl-js/releases). Usage ----- All API functions accept and return bytes as `Uint8Array`s. If you need to encode or decode strings, use functions from <https://github.com/dchest/tweetnacl-util-js> or one of the more robust codec packages. In Node.js v4 and later `Buffer` objects are backed by `Uint8Array`s, so you can freely pass them to TweetNaCl.js functions as arguments. The returned objects are still `Uint8Array`s, so if you need `Buffer`s, you'll have to convert them manually; make sure to convert using copying: `new Buffer(array)`, instead of sharing: `new Buffer(array.buffer)`, because some functions return subarrays of their buffers. ### Public-key authenticated encryption (box) Implements *curve25519-xsalsa20-poly1305*. #### nacl.box.keyPair() Generates a new random key pair for box and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 32-byte secret key } #### nacl.box.keyPair.fromSecretKey(secretKey) Returns a key pair for box with public key corresponding to the given secret key. #### nacl.box(message, nonce, theirPublicKey, mySecretKey) Encrypt and authenticates message using peer's public key, our secret key, and the given nonce, which must be unique for each distinct message for a key pair. Returns an encrypted and authenticated message, which is `nacl.box.overheadLength` longer than the original message. #### nacl.box.open(box, nonce, theirPublicKey, mySecretKey) Authenticates and decrypts the given box with peer's public key, our secret key, and the given nonce. Returns the original message, or `false` if authentication fails. #### nacl.box.before(theirPublicKey, mySecretKey) Returns a precomputed shared key which can be used in `nacl.box.after` and `nacl.box.open.after`. #### nacl.box.after(message, nonce, sharedKey) Same as `nacl.box`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.open.after(box, nonce, sharedKey) Same as `nacl.box.open`, but uses a shared key precomputed with `nacl.box.before`. #### nacl.box.publicKeyLength = 32 Length of public key in bytes. #### nacl.box.secretKeyLength = 32 Length of secret key in bytes. #### nacl.box.sharedKeyLength = 32 Length of precomputed shared key in bytes. #### nacl.box.nonceLength = 24 Length of nonce in bytes. #### nacl.box.overheadLength = 16 Length of overhead added to box compared to original message. ### Secret-key authenticated encryption (secretbox) Implements *xsalsa20-poly1305*. #### nacl.secretbox(message, nonce, key) Encrypt and authenticates message using the key and the nonce. The nonce must be unique for each distinct message for this key. Returns an encrypted and authenticated message, which is `nacl.secretbox.overheadLength` longer than the original message. #### nacl.secretbox.open(box, nonce, key) Authenticates and decrypts the given secret box using the key and the nonce. Returns the original message, or `false` if authentication fails. #### nacl.secretbox.keyLength = 32 Length of key in bytes. #### nacl.secretbox.nonceLength = 24 Length of nonce in bytes. #### nacl.secretbox.overheadLength = 16 Length of overhead added to secret box compared to original message. ### Scalar multiplication Implements *curve25519*. #### nacl.scalarMult(n, p) Multiplies an integer `n` by a group element `p` and returns the resulting group element. #### nacl.scalarMult.base(n) Multiplies an integer `n` by a standard group element and returns the resulting group element. #### nacl.scalarMult.scalarLength = 32 Length of scalar in bytes. #### nacl.scalarMult.groupElementLength = 32 Length of group element in bytes. ### Signatures Implements [ed25519](http://ed25519.cr.yp.to). #### nacl.sign.keyPair() Generates new random key pair for signing and returns it as an object with `publicKey` and `secretKey` members: { publicKey: ..., // Uint8Array with 32-byte public key secretKey: ... // Uint8Array with 64-byte secret key } #### nacl.sign.keyPair.fromSecretKey(secretKey) Returns a signing key pair with public key corresponding to the given 64-byte secret key. The secret key must have been generated by `nacl.sign.keyPair` or `nacl.sign.keyPair.fromSeed`. #### nacl.sign.keyPair.fromSeed(seed) Returns a new signing key pair generated deterministically from a 32-byte seed. The seed must contain enough entropy to be secure. This method is not recommended for general use: instead, use `nacl.sign.keyPair` to generate a new key pair from a random seed. #### nacl.sign(message, secretKey) Signs the message using the secret key and returns a signed message. #### nacl.sign.open(signedMessage, publicKey) Verifies the signed message and returns the message without signature. Returns `null` if verification failed. #### nacl.sign.detached(message, secretKey) Signs the message using the secret key and returns a signature. #### nacl.sign.detached.verify(message, signature, publicKey) Verifies the signature for the message and returns `true` if verification succeeded or `false` if it failed. #### nacl.sign.publicKeyLength = 32 Length of signing public key in bytes. #### nacl.sign.secretKeyLength = 64 Length of signing secret key in bytes. #### nacl.sign.seedLength = 32 Length of seed for `nacl.sign.keyPair.fromSeed` in bytes. #### nacl.sign.signatureLength = 64 Length of signature in bytes. ### Hashing Implements *SHA-512*. #### nacl.hash(message) Returns SHA-512 hash of the message. #### nacl.hash.hashLength = 64 Length of hash in bytes. ### Random bytes generation #### nacl.randomBytes(length) Returns a `Uint8Array` of the given length containing random bytes of cryptographic quality. **Implementation note** TweetNaCl.js uses the following methods to generate random bytes, depending on the platform it runs on: * `window.crypto.getRandomValues` (WebCrypto standard) * `window.msCrypto.getRandomValues` (Internet Explorer 11) * `crypto.randomBytes` (Node.js) If the platform doesn't provide a suitable PRNG, the following functions, which require random numbers, will throw exception: * `nacl.randomBytes` * `nacl.box.keyPair` * `nacl.sign.keyPair` Other functions are deterministic and will continue working. If a platform you are targeting doesn't implement secure random number generator, but you somehow have a cryptographically-strong source of entropy (not `Math.random`!), and you know what you are doing, you can plug it into TweetNaCl.js like this: nacl.setPRNG(function(x, n) { // ... copy n random bytes into x ... }); Note that `nacl.setPRNG` *completely replaces* internal random byte generator with the one provided. ### Constant-time comparison #### nacl.verify(x, y) Compares `x` and `y` in constant time and returns `true` if their lengths are non-zero and equal, and their contents are equal. Returns `false` if either of the arguments has zero length, or arguments have different lengths, or their contents differ. System requirements ------------------- TweetNaCl.js supports modern browsers that have a cryptographically secure pseudorandom number generator and typed arrays, including the latest versions of: * Chrome * Firefox * Safari (Mac, iOS) * Internet Explorer 11 Other systems: * Node.js Development and testing ------------------------ Install NPM modules needed for development: $ npm install To build minified versions: $ npm run build Tests use minified version, so make sure to rebuild it every time you change `nacl.js` or `nacl-fast.js`. ### Testing To run tests in Node.js: $ npm run test-node By default all tests described here work on `nacl.min.js`. To test other versions, set environment variable `NACL_SRC` to the file name you want to test. For example, the following command will test fast minified version: $ NACL_SRC=nacl-fast.min.js npm run test-node To run full suite of tests in Node.js, including comparing outputs of JavaScript port to outputs of the original C version: $ npm run test-node-all To prepare tests for browsers: $ npm run build-test-browser and then open `test/browser/test.html` (or `test/browser/test-fast.html`) to run them. To run headless browser tests with `tape-run` (powered by Electron): $ npm run test-browser (If you get `Error: spawn ENOENT`, install *xvfb*: `sudo apt-get install xvfb`.) To run tests in both Node and Electron: $ npm test ### Benchmarking To run benchmarks in Node.js: $ npm run bench $ NACL_SRC=nacl-fast.min.js npm run bench To run benchmarks in a browser, open `test/benchmark/bench.html` (or `test/benchmark/bench-fast.html`). Benchmarks ---------- For reference, here are benchmarks from MacBook Pro (Retina, 13-inch, Mid 2014) laptop with 2.6 GHz Intel Core i5 CPU (Intel) in Chrome 53/OS X and Xiaomi Redmi Note 3 smartphone with 1.8 GHz Qualcomm Snapdragon 650 64-bit CPU (ARM) in Chrome 52/Android: | | nacl.js Intel | nacl-fast.js Intel | nacl.js ARM | nacl-fast.js ARM | | ------------- |:-------------:|:-------------------:|:-------------:|:-----------------:| | salsa20 | 1.3 MB/s | 128 MB/s | 0.4 MB/s | 43 MB/s | | poly1305 | 13 MB/s | 171 MB/s | 4 MB/s | 52 MB/s | | hash | 4 MB/s | 34 MB/s | 0.9 MB/s | 12 MB/s | | secretbox 1K | 1113 op/s | 57583 op/s | 334 op/s | 14227 op/s | | box 1K | 145 op/s | 718 op/s | 37 op/s | 368 op/s | | scalarMult | 171 op/s | 733 op/s | 56 op/s | 380 op/s | | sign | 77 op/s | 200 op/s | 20 op/s | 61 op/s | | sign.open | 39 op/s | 102 op/s | 11 op/s | 31 op/s | (You can run benchmarks on your devices by clicking on the links at the bottom of the [home page](https://tweetnacl.js.org)). In short, with *nacl-fast.js* and 1024-byte messages you can expect to encrypt and authenticate more than 57000 messages per second on a typical laptop or more than 14000 messages per second on a $170 smartphone, sign about 200 and verify 100 messages per second on a laptop or 60 and 30 messages per second on a smartphone, per CPU core (with Web Workers you can do these operations in parallel), which is good enough for most applications. Contributors ------------ See AUTHORS.md file. Third-party libraries based on TweetNaCl.js ------------------------------------------- * [forward-secrecy](https://github.com/alax/forward-secrecy) — Axolotl ratchet implementation * [nacl-stream](https://github.com/dchest/nacl-stream-js) - streaming encryption * [tweetnacl-auth-js](https://github.com/dchest/tweetnacl-auth-js) — implementation of [`crypto_auth`](http://nacl.cr.yp.to/auth.html) * [chloride](https://github.com/dominictarr/chloride) - unified API for various NaCl modules Who uses it ----------- Some notable users of TweetNaCl.js: * [miniLock](http://minilock.io/) * [Stellar](https://www.stellar.org/) [![build status](https://secure.travis-ci.org/dankogai/js-base64.png)](http://travis-ci.org/dankogai/js-base64) # base64.js Yet another Base64 transcoder ## Install ```javascript $ npm install --save js-base64 ``` If you are using it on ES6 transpilers, you may also need: ```javascript $ npm install --save babel-preset-env ``` Note `js-base64` itself is stand-alone so its `package.json` has no `dependencies`.  However, it is also tested on ES6 environment so `"babel-preset-env": "^1.7.0"` is on `devDependencies`. ## Usage ### In Browser ```html <script src="base64.js"></script> ``` ### node.js ```javascript var Base64 = require('js-base64').Base64; ``` ## es6+ ```javascript import { Base64 } from 'js-base64'; ``` ## SYNOPSIS ```javascript Base64.encode('dankogai'); // ZGFua29nYWk= Base64.encode('小飼弾'); // 5bCP6aO85by+ Base64.encodeURI('小飼弾'); // 5bCP6aO85by- Base64.decode('ZGFua29nYWk='); // dankogai Base64.decode('5bCP6aO85by+'); // 小飼弾 // note .decodeURI() is unnecessary since it accepts both flavors Base64.decode('5bCP6aO85by-'); // 小飼弾 ``` ### String Extension for ES5 ```javascript if (Base64.extendString) { // you have to explicitly extend String.prototype Base64.extendString(); // once extended, you can do the following 'dankogai'.toBase64(); // ZGFua29nYWk= '小飼弾'.toBase64(); // 5bCP6aO85by+ '小飼弾'.toBase64(true); // 5bCP6aO85by- '小飼弾'.toBase64URI(); // 5bCP6aO85by- 'ZGFua29nYWk='.fromBase64(); // dankogai '5bCP6aO85by+'.fromBase64(); // 小飼弾 '5bCP6aO85by-'.fromBase64(); // 小飼弾 } ``` ### TypeScript TypeScript 2.0 type definition was added to the [DefinitelyTyped repository](https://github.com/DefinitelyTyped/DefinitelyTyped). ```bash $ npm install --save @types/js-base64 ``` ## `.decode()` vs `.atob` (and `.encode()` vs `btoa()`) Suppose you have: ``` var pngBase64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="; ``` Which is a Base64-encoded 1x1 transparent PNG, **DO NOT USE** `Base64.decode(pngBase64)`.  Use `Base64.atob(pngBase64)` instead.  `Base64.decode()` decodes to UTF-8 string while `Base64.atob()` decodes to bytes, which is compatible to browser built-in `atob()` (Which is absent in node.js).  The same rule applies to the opposite direction. ## SEE ALSO + http://en.wikipedia.org/wiki/Base64 # media-typer [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Simple RFC 6838 media type parser ## Installation ```sh $ npm install media-typer ``` ## API ```js var typer = require('media-typer') ``` ### typer.parse(string) ```js var obj = typer.parse('image/svg+xml; charset=utf-8') ``` Parse a media type string. This will return an object with the following properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): - `type`: The type of the media type (always lower case). Example: `'image'` - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` ### typer.parse(req) ```js var obj = typer.parse(req) ``` Parse the `content-type` header from the given `req`. Short-cut for `typer.parse(req.headers['content-type'])`. ### typer.parse(res) ```js var obj = typer.parse(res) ``` Parse the `content-type` header set on the given `res`. Short-cut for `typer.parse(res.getHeader('content-type'))`. ### typer.format(obj) ```js var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) ``` Format an object into a media type string. This will return a string of the mime type for the given object. For the properties of the object, see the documentation for `typer.parse(string)`. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat [npm-url]: https://npmjs.org/package/media-typer [node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat [node-version-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat [travis-url]: https://travis-ci.org/jshttp/media-typer [coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat [coveralls-url]: https://coveralls.io/r/jshttp/media-typer [downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat [downloads-url]: https://npmjs.org/package/media-typer # faye-websocket * Travis CI build: [![Build status](https://secure.travis-ci.org/faye/faye-websocket-node.svg)](http://travis-ci.org/faye/faye-websocket-node) * Autobahn tests: [server](http://faye.jcoglan.com/autobahn/servers/), [client](http://faye.jcoglan.com/autobahn/clients/) This is a general-purpose WebSocket implementation extracted from the [Faye](http://faye.jcoglan.com) project. It provides classes for easily building WebSocket servers and clients in Node. It does not provide a server itself, but rather makes it easy to handle WebSocket connections within an existing [Node](http://nodejs.org/) application. It does not provide any abstraction other than the standard [WebSocket API](http://dev.w3.org/html5/websockets/). It also provides an abstraction for handling [EventSource](http://dev.w3.org/html5/eventsource/) connections, which are one-way connections that allow the server to push data to the client. They are based on streaming HTTP responses and can be easier to access via proxies than WebSockets. ## Installation ``` $ npm install faye-websocket ``` ## Handling WebSocket connections in Node You can handle WebSockets on the server side by listening for HTTP Upgrade requests, and creating a new socket for the request. This socket object exposes the usual WebSocket methods for receiving and sending messages. For example this is how you'd implement an echo server: ```js var WebSocket = require('faye-websocket'), http = require('http'); var server = http.createServer(); server.on('upgrade', function(request, socket, body) { if (WebSocket.isWebSocket(request)) { var ws = new WebSocket(request, socket, body); ws.on('message', function(event) { ws.send(event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); } }); server.listen(8000); ``` `WebSocket` objects are also duplex streams, so you could replace the `ws.on('message', ...)` line with: ```js ws.pipe(ws); ``` Note that under certain circumstances (notably a draft-76 client connecting through an HTTP proxy), the WebSocket handshake will not be complete after you call `new WebSocket()` because the server will not have received the entire handshake from the client yet. In this case, calls to `ws.send()` will buffer the message in memory until the handshake is complete, at which point any buffered messages will be sent to the client. If you need to detect when the WebSocket handshake is complete, you can use the `onopen` event. If the connection's protocol version supports it, you can call `ws.ping()` to send a ping message and wait for the client's response. This method takes a message string, and an optional callback that fires when a matching pong message is received. It returns `true` if and only if a ping message was sent. If the client does not support ping/pong, this method sends no data and returns `false`. ```js ws.ping('Mic check, one, two', function() { // fires when pong is received }); ``` ## Using the WebSocket client The client supports both the plain-text `ws` protocol and the encrypted `wss` protocol, and has exactly the same interface as a socket you would use in a web browser. On the wire it identifies itself as `hybi-13`. ```js var WebSocket = require('faye-websocket'), ws = new WebSocket.Client('ws://www.example.com/'); ws.on('open', function(event) { console.log('open'); ws.send('Hello, world!'); }); ws.on('message', function(event) { console.log('message', event.data); }); ws.on('close', function(event) { console.log('close', event.code, event.reason); ws = null; }); ``` The WebSocket client also lets you inspect the status and headers of the handshake response via its `statusCode` and `headers` properties. To connect via a proxy, set the `proxy` option to the HTTP origin of the proxy, including any authorization information, custom headers and TLS config you require. Only the `origin` setting is required. ```js var ws = new WebSocket.Client('ws://www.example.com/', [], { proxy: { origin: 'http://username:[email protected]', headers: {'User-Agent': 'node'}, tls: {cert: fs.readFileSync('client.crt')} } }); ``` The `tls` value is a Node 'TLS options' object that will be passed to [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback). ## Subprotocol negotiation The WebSocket protocol allows peers to select and identify the application protocol to use over the connection. On the client side, you can set which protocols the client accepts by passing a list of protocol names when you construct the socket: ```js var ws = new WebSocket.Client('ws://www.example.com/', ['irc', 'amqp']); ``` On the server side, you can likewise pass in the list of protocols the server supports after the other constructor arguments: ```js var ws = new WebSocket(request, socket, body, ['irc', 'amqp']); ``` If the client and server agree on a protocol, both the client- and server-side socket objects expose the selected protocol through the `ws.protocol` property. ## Protocol extensions faye-websocket is based on the [websocket-extensions](https://github.com/faye/websocket-extensions-node) framework that allows extensions to be negotiated via the `Sec-WebSocket-Extensions` header. To add extensions to a connection, pass an array of extensions to the `:extensions` option. For example, to add [permessage-deflate](https://github.com/faye/permessage-deflate-node): ```js var deflate = require('permessage-deflate'); var ws = new WebSocket(request, socket, body, [], {extensions: [deflate]}); ``` ## Initialization options Both the server- and client-side classes allow an options object to be passed in at initialization time, for example: ```js var ws = new WebSocket(request, socket, body, protocols, options); var ws = new WebSocket.Client(url, protocols, options); ``` `protocols` is an array of subprotocols as described above, or `null`. `options` is an optional object containing any of these fields: * `extensions` - an array of [websocket-extensions](https://github.com/faye/websocket-extensions-node) compatible extensions, as described above * `headers` - an object containing key-value pairs representing HTTP headers to be sent during the handshake process * `maxLength` - the maximum allowed size of incoming message frames, in bytes. The default value is `2^26 - 1`, or 1 byte short of 64 MiB. * `ping` - an integer that sets how often the WebSocket should send ping frames, measured in seconds The client accepts some additional options: * `proxy` - settings for a proxy as described above * `tls` - a Node 'TLS options' object containing TLS settings for the origin server, this will be passed to [`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) * `ca` - (legacy) a shorthand for passing `{tls: {ca: value}}` ## WebSocket API Both server- and client-side `WebSocket` objects support the following API. * <b>`on('open', function(event) {})`</b> fires when the socket connection is established. Event has no attributes. * <b>`on('message', function(event) {})`</b> fires when the socket receives a message. Event has one attribute, <b>`data`</b>, which is either a `String` (for text frames) or a `Buffer` (for binary frames). * <b>`on('error', function(event) {})`</b> fires when there is a protocol error due to bad data sent by the other peer. This event is purely informational, you do not need to implement error recover. * <b>`on('close', function(event) {})`</b> fires when either the client or the server closes the connection. Event has two optional attributes, <b>`code`</b> and <b>`reason`</b>, that expose the status code and message sent by the peer that closed the connection. * <b>`send(message)`</b> accepts either a `String` or a `Buffer` and sends a text or binary message over the connection to the other peer. * <b>`ping(message, function() {})`</b> sends a ping frame with an optional message and fires the callback when a matching pong is received. * <b>`close(code, reason)`</b> closes the connection, sending the given status code and reason text, both of which are optional. * <b>`version`</b> is a string containing the version of the `WebSocket` protocol the connection is using. * <b>`protocol`</b> is a string (which may be empty) identifying the subprotocol the socket is using. ## Handling EventSource connections in Node EventSource connections provide a very similar interface, although because they only allow the server to send data to the client, there is no `onmessage` API. EventSource allows the server to push text messages to the client, where each message has an optional event-type and ID. ```js var WebSocket = require('faye-websocket'), EventSource = WebSocket.EventSource, http = require('http'); var server = http.createServer(); server.on('request', function(request, response) { if (EventSource.isEventSource(request)) { var es = new EventSource(request, response); console.log('open', es.url, es.lastEventId); // Periodically send messages var loop = setInterval(function() { es.send('Hello') }, 1000); es.on('close', function() { clearInterval(loop); es = null; }); } else { // Normal HTTP request response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello'); } }); server.listen(8000); ``` The `send` method takes two optional parameters, `event` and `id`. The default event-type is `'message'` with no ID. For example, to send a `notification` event with ID `99`: ```js es.send('Breaking News!', {event: 'notification', id: '99'}); ``` The `EventSource` object exposes the following properties: * <b>`url`</b> is a string containing the URL the client used to create the EventSource. * <b>`lastEventId`</b> is a string containing the last event ID received by the client. You can use this when the client reconnects after a dropped connection to determine which messages need resending. When you initialize an EventSource with ` new EventSource()`, you can pass configuration options after the `response` parameter. Available options are: * <b>`headers`</b> is an object containing custom headers to be set on the EventSource response. * <b>`retry`</b> is a number that tells the client how long (in seconds) it should wait after a dropped connection before attempting to reconnect. * <b>`ping`</b> is a number that tells the server how often (in seconds) to send 'ping' packets to the client to keep the connection open, to defeat timeouts set by proxies. The client will ignore these messages. For example, this creates a connection that allows access from any origin, pings every 15 seconds and is retryable every 10 seconds if the connection is broken: ```js var es = new EventSource(request, response, { headers: {'Access-Control-Allow-Origin': '*'}, ping: 15, retry: 10 }); ``` You can send a ping message at any time by calling `es.ping()`. Unlike WebSocket, the client does not send a response to this; it is merely to send some data over the wire to keep the connection alive. ## License (The MIT License) Copyright (c) 2010-2015 James Coglan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # mime-types [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] The ultimate javascript content-type utility. Similar to [the `[email protected]` module](https://www.npmjs.com/package/mime), except: - __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. - No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. - No `.define()` functionality - Bug fixes for `.lookup(path)` Otherwise, the API is compatible with `mime` 1.x. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install mime-types ``` ## Adding Types All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), so open a PR there if you'd like to add mime types. ## API ```js var mime = require('mime-types') ``` All functions return `false` if input is invalid or not found. ### mime.lookup(path) Lookup the content-type associated with a file. ```js mime.lookup('json') // 'application/json' mime.lookup('.md') // 'text/markdown' mime.lookup('file.html') // 'text/html' mime.lookup('folder/file.js') // 'application/javascript' mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` ### mime.contentType(type) Create a full content-type header given a content-type or extension. When given an extension, `mime.lookup` is used to get the matching content-type, otherwise the given content-type is used. Then if the content-type does not already have a `charset` parameter, `mime.charset` is used to get the default charset and add to the returned content-type. ```js mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' mime.contentType('file.json') // 'application/json; charset=utf-8' mime.contentType('text/html') // 'text/html; charset=utf-8' mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' // from a full path mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' ``` ### mime.extension(type) Get the default extension for a content-type. ```js mime.extension('application/octet-stream') // 'bin' ``` ### mime.charset(type) Lookup the implied default charset of a content-type. ```js mime.charset('text/markdown') // 'UTF-8' ``` ### var type = mime.types[extension] A map of content-types by extension. ### [extensions...] = mime.extensions[type] A map of extensions by content-type. ## License [MIT](LICENSE) [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master [node-version-image]: https://badgen.net/npm/node/mime-types [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-types [npm-url]: https://npmjs.org/package/mime-types [npm-version-image]: https://badgen.net/npm/v/mime-types [travis-image]: https://badgen.net/travis/jshttp/mime-types/master [travis-url]: https://travis-ci.org/jshttp/mime-types # regexpu-core [![Build status](https://travis-ci.org/mathiasbynens/regexpu-core.svg?branch=master)](https://travis-ci.org/mathiasbynens/regexpu-core) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/regexpu-core.svg)](https://codecov.io/gh/mathiasbynens/regexpu-core) _regexpu_ is a source code transpiler that enables the use of ES6 Unicode regular expressions in JavaScript-of-today (ES5). _regexpu-core_ contains _regexpu_’s core functionality, i.e. `rewritePattern(pattern, flag)`, which enables rewriting regular expressions that make use of [the ES6 `u` flag](https://mathiasbynens.be/notes/es6-unicode-regex) into equivalent ES5-compatible regular expression patterns. ## Installation To use _regexpu-core_ programmatically, install it as a dependency via [npm](https://www.npmjs.com/): ```bash npm install regexpu-core --save ``` Then, `require` it: ```js const rewritePattern = require('regexpu-core'); ``` ## API This module exports a single function named `rewritePattern`. ### `rewritePattern(pattern, flags, options)` This function takes a string that represents a regular expression pattern as well as a string representing its flags, and returns an ES5-compatible version of the pattern. ```js rewritePattern('foo.bar', 'u'); // → 'foo(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\uDC00-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF])bar' rewritePattern('[\\u{1D306}-\\u{1D308}a-z]', 'u'); // → '(?:[a-z]|\\uD834[\\uDF06-\\uDF08])' rewritePattern('[\\u{1D306}-\\u{1D308}a-z]', 'ui'); // → '(?:[a-z\\u017F\\u212A]|\\uD834[\\uDF06-\\uDF08])' ``` _regexpu-core_ can rewrite non-ES6 regular expressions too, which is useful to demonstrate how their behavior changes once the `u` and `i` flags are added: ```js // In ES5, the dot operator only matches BMP symbols: rewritePattern('foo.bar'); // → 'foo(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uFFFF])bar' // But with the ES6 `u` flag, it matches astral symbols too: rewritePattern('foo.bar', 'u'); // → 'foo(?:[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uD7FF\\uDC00-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF])bar' ``` The optional `options` argument recognizes the following properties: #### `dotAllFlag` (default: `false`) Setting this option to `true` enables experimental support for [the `s` (`dotAll`) flag](https://github.com/mathiasbynens/es-regexp-dotall-flag). ```js rewritePattern('.'); // → '[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uFFFF]' rewritePattern('.', '', { 'dotAllFlag': true }); // → '[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uFFFF]' rewritePattern('.', 's', { 'dotAllFlag': true }); // → '[\\0-\\uFFFF]' rewritePattern('.', 'su', { 'dotAllFlag': true }); // → '(?:[\\0-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])' ``` #### `unicodePropertyEscape` (default: `false`) Setting this option to `true` enables [experimental support for Unicode property escapes](property-escapes.md): ```js rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', { 'unicodePropertyEscape': true }); // → '(?:\\uD811[\\uDC00-\\uDE46])' ``` #### `lookbehind` (default: `false`) Setting this option to `true` enables experimental support for [lookbehind assertions](https://github.com/tc39/proposal-regexp-lookbehind). ```js rewritePattern('(?<=.)a', '', { 'lookbehind': true }); // → '(?<=[\\0-\\t\\x0B\\f\\x0E-\\u2027\\u202A-\\uFFFF])a' ``` #### `namedGroup` (default: `false`) Setting this option to `true` enables experimental support for [named capture groups](https://github.com/tc39/proposal-regexp-named-groups). ```js rewritePattern('(?<name>.)\k<name>', '', { 'namedGroups': true }); // → '(.)\1' ``` #### `onNamedGroup` This option is a function that gets called when a named capture group is found. It receives two parameters: the name of the group, and its index. ```js rewritePattern('(?<name>.)\k<name>', '', { 'namedGroups': true, onNamedGroup(name, index) { console.log(name, index); // → 'name', 1 } }); ``` #### `useUnicodeFlag` (default: `false`) Setting this option to `true` enables the use of Unicode code point escapes of the form `\u{…}`. Note that in regular expressions, such escape sequences only work correctly when the ES6 `u` flag is set. Enabling this setting often results in more compact output, although there are cases (such as `\p{Lu}`) where it actually _increases_ the output size. ```js rewritePattern('\\p{Script_Extensions=Anatolian_Hieroglyphs}', 'u', { 'unicodePropertyEscape': true, 'useUnicodeFlag': true }); // → '[\\u{14400}-\\u{14646}]' ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _regexpu-core_ is available under the [MIT](https://mths.be/mit) license. # duplexify Turn a writeable and readable stream into a single streams2 duplex stream. Similar to [duplexer2](https://github.com/deoxxa/duplexer2) except it supports both streams2 and streams1 as input and it allows you to set the readable and writable part asynchronously using `setReadable(stream)` and `setWritable(stream)` ``` npm install duplexify ``` [![build status](http://img.shields.io/travis/mafintosh/duplexify.svg?style=flat)](http://travis-ci.org/mafintosh/duplexify) ## Usage Use `duplexify(writable, readable, streamOptions)` (or `duplexify.obj(writable, readable)` to create an object stream) ``` js var duplexify = require('duplexify') // turn writableStream and readableStream into a single duplex stream var dup = duplexify(writableStream, readableStream) dup.write('hello world') // will write to writableStream dup.on('data', function(data) { // will read from readableStream }) ``` You can also set the readable and writable parts asynchronously ``` js var dup = duplexify() dup.write('hello world') // write will buffer until the writable // part has been set // wait a bit ... dup.setReadable(readableStream) // maybe wait some more? dup.setWritable(writableStream) ``` If you call `setReadable` or `setWritable` multiple times it will unregister the previous readable/writable stream. To disable the readable or writable part call `setReadable` or `setWritable` with `null`. If the readable or writable streams emits an error or close it will destroy both streams and bubble up the event. You can also explicitly destroy the streams by calling `dup.destroy()`. The `destroy` method optionally takes an error object as argument, in which case the error is emitted as part of the `error` event. ``` js dup.on('error', function(err) { console.log('readable or writable emitted an error - close will follow') }) dup.on('close', function() { console.log('the duplex stream is destroyed') }) dup.destroy() // calls destroy on the readable and writable part (if present) ``` ## HTTP request example Turn a node core http request into a duplex stream is as easy as ``` js var duplexify = require('duplexify') var http = require('http') var request = function(opts) { var req = http.request(opts) var dup = duplexify(req) req.on('response', function(res) { dup.setReadable(res) }) return dup } var req = request({ method: 'GET', host: 'www.google.com', port: 80 }) req.end() req.pipe(process.stdout) ``` ## License MIT ## Related `duplexify` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # accepts [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use. In addition to negotiator, it allows: - Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`. - Allows type shorthands such as `json`. - Returns `false` when no types match - Treats non-existent headers as `*` ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install accepts ``` ## API <!-- eslint-disable no-unused-vars --> ```js var accepts = require('accepts') ``` ### accepts(req) Create a new `Accepts` object for the given `req`. #### .charset(charsets) Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned. #### .charsets() Return the charsets that the request accepts, in the order of the client's preference (most preferred first). #### .encoding(encodings) Return the first accepted encoding. If nothing in `encodings` is accepted, then `false` is returned. #### .encodings() Return the encodings that the request accepts, in the order of the client's preference (most preferred first). #### .language(languages) Return the first accepted language. If nothing in `languages` is accepted, then `false` is returned. #### .languages() Return the languages that the request accepts, in the order of the client's preference (most preferred first). #### .type(types) 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. The `types` array can contain full MIME types or file extensions. Any value that is not a full MIME types is passed to `require('mime-types').lookup`. #### .types() Return the types that the request accepts, in the order of the client's preference (most preferred first). ## Examples ### Simple type negotiation This simple example shows how to use `accepts` to return a different typed respond body based on what the client wants to accept. The server lists it's preferences in order and will get back the best match between the client and server. ```js var accepts = require('accepts') var http = require('http') function app (req, res) { var accept = accepts(req) // the order of this list is significant; should be server preferred order switch (accept.type(['json', 'html'])) { case 'json': res.setHeader('Content-Type', 'application/json') res.write('{"hello":"world!"}') break case 'html': res.setHeader('Content-Type', 'text/html') res.write('<b>hello, world!</b>') break default: // the fallback is text/plain, so no need to specify it above res.setHeader('Content-Type', 'text/plain') res.write('hello, world!') break } res.end() } http.createServer(app).listen(3000) ``` You can test this out with the cURL program: ```sh curl -I -H'Accept: text/html' http://localhost:3000/ ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/accepts.svg [npm-url]: https://npmjs.org/package/accepts [node-version-image]: https://img.shields.io/node/v/accepts.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg [travis-url]: https://travis-ci.org/jshttp/accepts [coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/accepts [downloads-image]: https://img.shields.io/npm/dm/accepts.svg [downloads-url]: https://npmjs.org/package/accepts cipher-base === [![Build Status](https://travis-ci.org/crypto-browserify/cipher-base.svg)](https://travis-ci.org/crypto-browserify/cipher-base) Abstract base class to inherit from if you want to create streams implementing the same api as node crypto streams. Requires you to implement 2 methods `_final` and `_update`. `_update` takes a buffer and should return a buffer, `_final` takes no arguments and should return a buffer. The constructor takes one argument and that is a string which if present switches it into hash mode, i.e. the object you get from crypto.createHash or crypto.createSign, this switches the name of the final method to be the string you passed instead of `final` and returns `this` from update. [![Build Status][ci-img]][ci] [![codecov][codecov-img]][codecov] [![npm][npm-img]][npm] # CSS Modules: Local by Default Transformation examples: ```css .foo { ... } /* => */ :local(.foo) { ... } .foo .bar { ... } /* => */ :local(.foo) :local(.bar) { ... } /* Shorthand global selector */ :global .foo .bar { ... } /* => */ .foo .bar { ... } .foo :global .bar { ... } /* => */ :local(.foo) .bar { ... } /* Targeted global selector */ :global(.foo) .bar { ... } /* => */ .foo :local(.bar) { ... } .foo:global(.bar) { ... } /* => */ :local(.foo).bar { ... } .foo :global(.bar) .baz { ... } /* => */ :local(.foo) .bar :local(.baz) { ... } .foo:global(.bar) .baz { ... } /* => */ :local(.foo).bar :local(.baz) { ... } ``` ## Building ```bash $ npm install $ npm test ``` - Build: [![Build Status][ci-img]][ci] - Lines: [![coveralls][coveralls-img]][coveralls] - Statements: [![codecov][codecov-img]][codecov] ## Development ```bash $ npm run autotest ``` ## License MIT ## With thanks - [Tobias Koppers](https://github.com/sokra) - [Glen Maddern](https://github.com/geelen) --- Mark Dalgleish, 2015. [ci-img]: https://img.shields.io/travis/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square [ci]: https://travis-ci.org/css-modules/postcss-modules-local-by-default [npm-img]: https://img.shields.io/npm/v/postcss-modules-local-by-default.svg?style=flat-square [npm]: https://www.npmjs.com/package/postcss-modules-local-by-default [coveralls-img]: https://img.shields.io/coveralls/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square [coveralls]: https://coveralls.io/r/css-modules/postcss-modules-local-by-default?branch=master [codecov-img]: https://img.shields.io/codecov/c/github/css-modules/postcss-modules-local-by-default/master.svg?style=flat-square [codecov]: https://codecov.io/github/css-modules/postcss-modules-local-by-default?branch=master # is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) > Returns true if a string has an extglob. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extglob ``` ## Usage ```js var isExtglob = require('is-extglob'); ``` **True** ```js isExtglob('?(abc)'); isExtglob('@(abc)'); isExtglob('!(abc)'); isExtglob('*(abc)'); isExtglob('+(abc)'); ``` **False** Escaped extglobs: ```js isExtglob('\\?(abc)'); isExtglob('\\@(abc)'); isExtglob('\\!(abc)'); isExtglob('\\*(abc)'); isExtglob('\\+(abc)'); ``` Everything else... ```js isExtglob('foo.js'); isExtglob('!foo.js'); isExtglob('*.js'); isExtglob('**/abc.js'); isExtglob('abc/*.js'); isExtglob('abc/(aaa|bbb).js'); isExtglob('abc/[a-z].js'); isExtglob('abc/{a,b}.js'); isExtglob('abc/?.js'); isExtglob('abc.js'); isExtglob('abc/def/ghi.js'); ``` ## History **v2.0** Adds support for escaping. Escaped exglobs no longer return true. ## About ### Related projects * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # osenv Look up environment settings specific to different operating systems. ## Usage ```javascript var osenv = require('osenv') var path = osenv.path() var user = osenv.user() // etc. // Some things are not reliably in the env, and have a fallback command: var h = osenv.hostname(function (er, hostname) { h = hostname }) // This will still cause it to be memoized, so calling osenv.hostname() // is now an immediate operation. // You can always send a cb, which will get called in the nextTick // if it's been memoized, or wait for the fallback data if it wasn't // found in the environment. osenv.hostname(function (er, hostname) { if (er) console.error('error looking up hostname') else console.log('this machine calls itself %s', hostname) }) ``` ## osenv.hostname() The machine name. Calls `hostname` if not found. ## osenv.user() The currently logged-in user. Calls `whoami` if not found. ## osenv.prompt() Either PS1 on unix, or PROMPT on Windows. ## osenv.tmpdir() The place where temporary files should be created. ## osenv.home() No place like it. ## osenv.path() An array of the places that the operating system will search for executables. ## osenv.editor() Return the executable name of the editor program. This uses the EDITOR and VISUAL environment variables, and falls back to `vi` on Unix, or `notepad.exe` on Windows. ## osenv.shell() The SHELL on Unix, which Windows calls the ComSpec. Defaults to 'bash' or 'cmd'. # babel # crypto-browserify A port of node's `crypto` module to the browser. [![Build Status](https://travis-ci.org/crypto-browserify/crypto-browserify.svg?branch=master)](https://travis-ci.org/crypto-browserify/crypto-browserify) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) [![Sauce Test Status](https://saucelabs.com/browser-matrix/crypto-browserify.svg)](https://saucelabs.com/u/crypto-browserify) The goal of this module is to reimplement node's crypto module, in pure javascript so that it can run in the browser. Here is the subset that is currently implemented: * createHash (sha1, sha224, sha256, sha384, sha512, md5, rmd160) * createHmac (sha1, sha224, sha256, sha384, sha512, md5, rmd160) * pbkdf2 * pbkdf2Sync * randomBytes * pseudoRandomBytes * createCipher (aes) * createDecipher (aes) * createDiffieHellman * createSign (rsa, ecdsa) * createVerify (rsa, ecdsa) * createECDH (secp256k1) * publicEncrypt/privateDecrypt (rsa) * privateEncrypt/publicDecrypt (rsa) ## todo these features from node's `crypto` are still unimplemented. * createCredentials ## contributions If you are interested in writing a feature, please implement as a new module, which will be incorporated into crypto-browserify as a dependency. All deps must be compatible with node's crypto (generate example inputs and outputs with node, and save base64 strings inside JSON, so that tests can run in the browser. see [sha.js](https://github.com/dominictarr/sha.js) Crypto is _extra serious_ so please do not hesitate to review the code, and post comments if you do. ## License MIT # Acorn A tiny, fast JavaScript parser written in JavaScript. ## Community Acorn is open source software released under an [MIT license](https://github.com/acornjs/acorn/blob/master/acorn/LICENSE). You are welcome to [report bugs](https://github.com/acornjs/acorn/issues) or create pull requests on [github](https://github.com/acornjs/acorn). For questions and discussion, please use the [Tern discussion forum](https://discuss.ternjs.net). ## Installation The easiest way to install acorn is from [`npm`](https://www.npmjs.com/): ```sh npm install acorn ``` Alternately, you can download the source and build acorn yourself: ```sh git clone https://github.com/acornjs/acorn.git cd acorn npm install ``` ## Interface **parse**`(input, options)` is the main interface to the library. The `input` parameter is a string, `options` can be undefined or an object setting some of the options listed below. The return value will be an abstract syntax tree object as specified by the [ESTree spec](https://github.com/estree/estree). ```javascript let acorn = require("acorn"); console.log(acorn.parse("1 + 1")); ``` When encountering a syntax error, the parser will raise a `SyntaxError` object with a meaningful message. The error object will have a `pos` property that indicates the string offset at which the error occurred, and a `loc` object that contains a `{line, column}` object referring to that same position. Options can be provided by passing a second argument, which should be an object containing any of these fields: - **ecmaVersion**: Indicates the ECMAScript version to parse. Must be either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018) or 10 (2019, partial support). This influences support for strict mode, the set of reserved words, and support for new syntax features. Default is 7. **NOTE**: Only 'stage 4' (finalized) ECMAScript features are being implemented by Acorn. Other proposed new features can be implemented through plugins. - **sourceType**: Indicate the mode the code should be parsed in. Can be either `"script"` or `"module"`. This influences global strict mode and parsing of `import` and `export` declarations. - **onInsertedSemicolon**: If given a callback, that callback will be called whenever a missing semicolon is inserted by the parser. The callback will be given the character offset of the point where the semicolon is inserted as argument, and if `locations` is on, also a `{line, column}` object representing this position. - **onTrailingComma**: Like `onInsertedSemicolon`, but for trailing commas. - **allowReserved**: If `false`, using a reserved word will generate an error. Defaults to `true` for `ecmaVersion` 3, `false` for higher versions. When given the value `"never"`, reserved words and keywords can also not be used as property names (as in Internet Explorer's old parser). - **allowReturnOutsideFunction**: By default, a return statement at the top level raises an error. Set this to `true` to accept such code. - **allowImportExportEverywhere**: By default, `import` and `export` declarations can only appear at a program's top level. Setting this option to `true` allows them anywhere where a statement is allowed. - **allowAwaitOutsideFunction**: By default, `await` expressions can only appear inside `async` functions. Setting this option to `true` allows to have top-level `await` expressions. They are still not allowed in non-`async` functions, though. - **allowHashBang**: When this is enabled (off by default), if the code starts with the characters `#!` (as in a shellscript), the first line will be treated as a comment. - **locations**: When `true`, each node has a `loc` object attached with `start` and `end` subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. Default is `false`. - **onToken**: If a function is passed for this option, each found token will be passed in same format as tokens returned from `tokenizer().getToken()`. If array is passed, each found token is pushed to it. Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **onComment**: If a function is passed for this option, whenever a comment is encountered the function will be called with the following parameters: - `block`: `true` if the comment is a block comment, false if it is a line comment. - `text`: The content of the comment. - `start`: Character offset of the start of the comment. - `end`: Character offset of the end of the comment. When the `locations` options is on, the `{line, column}` locations of the comment’s start and end are passed as two additional parameters. If array is passed for this option, each found comment is pushed to it as object in Esprima format: ```javascript { "type": "Line" | "Block", "value": "comment text", "start": Number, "end": Number, // If `locations` option is on: "loc": { "start": {line: Number, column: Number} "end": {line: Number, column: Number} }, // If `ranges` option is on: "range": [Number, Number] } ``` Note that you are not allowed to call the parser from the callback—that will corrupt its internal state. - **ranges**: Nodes have their start and end characters offsets recorded in `start` and `end` properties (directly on the node, rather than the `loc` object, which holds line/column data. To also add a [semi-standardized](https://bugzilla.mozilla.org/show_bug.cgi?id=745678) `range` property holding a `[start, end]` array with the same numbers, set the `ranges` option to `true`. - **program**: It is possible to parse multiple files into a single AST by passing the tree produced by parsing the first file as the `program` option in subsequent parses. This will add the toplevel forms of the parsed file to the "Program" (top) node of an existing parse tree. - **sourceFile**: When the `locations` option is `true`, you can pass this option to add a `source` attribute in every node’s `loc` object. Note that the contents of this option are not examined or processed in any way; you are free to use whatever format you choose. - **directSourceFile**: Like `sourceFile`, but a `sourceFile` property will be added (regardless of the `location` option) directly to the nodes, rather than the `loc` object. - **preserveParens**: If this option is `true`, parenthesized expressions are represented by (non-standard) `ParenthesizedExpression` nodes that have a single `expression` property containing the expression inside parentheses. **parseExpressionAt**`(input, offset, options)` will parse a single expression in a string, and return its AST. It will not complain if there is more of the string left after the expression. **tokenizer**`(input, options)` returns an object with a `getToken` method that can be called repeatedly to get the next token, a `{start, end, type, value}` object (with added `loc` property when the `locations` option is enabled and `range` property when the `ranges` option is enabled). When the token's type is `tokTypes.eof`, you should stop calling the method, since it will keep returning that same token forever. In ES6 environment, returned result can be used as any other protocol-compliant iterable: ```javascript for (let token of acorn.tokenizer(str)) { // iterate over the tokens } // transform code to array of tokens: var tokens = [...acorn.tokenizer(str)]; ``` **tokTypes** holds an object mapping names to the token type objects that end up in the `type` properties of tokens. **getLineInfo**`(input, offset)` can be used to get a `{line, column}` object for a given program string and offset. ### The `Parser` class Instances of the **`Parser`** class contain all the state and logic that drives a parse. It has static methods `parse`, `parseExpressionAt`, and `tokenizer` that match the top-level functions by the same name. When extending the parser with plugins, you need to call these methods on the extended version of the class. To extend a parser with plugins, you can use its static `extend` method. ```javascript var acorn = require("acorn"); var jsx = require("acorn-jsx"); var JSXParser = acorn.Parser.extend(jsx()); JSXParser.parse("foo(<bar/>)"); ``` The `extend` method takes any number of plugin values, and returns a new `Parser` class that includes the extra parser logic provided by the plugins. ## Command line interface The `bin/acorn` utility can be used to parse a file from the command line. It accepts as arguments its input file and the following options: - `--ecma3|--ecma5|--ecma6|--ecma7|--ecma8|--ecma9|--ecma10`: Sets the ECMAScript version to parse. Default is version 9. - `--module`: Sets the parsing mode to `"module"`. Is set to `"script"` otherwise. - `--locations`: Attaches a "loc" object to each node with "start" and "end" subobjects, each of which contains the one-based line and zero-based column numbers in `{line, column}` form. - `--allow-hash-bang`: If the code starts with the characters #! (as in a shellscript), the first line will be treated as a comment. - `--compact`: No whitespace is used in the AST output. - `--silent`: Do not output the AST, just return the exit status. - `--help`: Print the usage information and quit. The utility spits out the syntax tree as JSON data. ## Existing plugins - [`acorn-jsx`](https://github.com/RReverser/acorn-jsx): Parse [Facebook JSX syntax extensions](https://github.com/facebook/jsx) Plugins for ECMAScript proposals: - [`acorn-stage3`](https://github.com/acornjs/acorn-stage3): Parse most stage 3 proposals, bundling: - [`acorn-async-iteration`](https://github.com/acornjs/acorn-async-iteration): Parse [async iteration proposal](https://github.com/tc39/proposal-async-iteration) - [`acorn-bigint`](https://github.com/acornjs/acorn-bigint): Parse [BigInt proposal](https://github.com/tc39/proposal-bigint) - [`acorn-class-fields`](https://github.com/acornjs/acorn-class-fields): Parse [class fields proposal](https://github.com/tc39/proposal-class-fields) - [`acorn-dynamic-import`](https://github.com/kesne/acorn-dynamic-import): Parse [import() proposal](https://github.com/tc39/proposal-dynamic-import) - [`acorn-import-meta`](https://github.com/acornjs/acorn-import-meta): Parse [import.meta proposal](https://github.com/tc39/proposal-import-meta) - [`acorn-numeric-separator`](https://github.com/acornjs/acorn-numeric-separator): Parse [numeric separator proposal](https://github.com/tc39/proposal-numeric-separator) - [`acorn-private-methods`](https://github.com/acornjs/acorn-private-methods): parse [private methods, getters and setters proposal](https://github.com/tc39/proposal-private-methods)n # http-errors [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Create HTTP errors for Express, Koa, Connect, etc. with ease. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install http-errors ``` ## Example ```js var createError = require('http-errors') var express = require('express') var app = express() app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')) next() }) ``` ## API This is the current API, currently extracted from Koa and subject to change. All errors inherit from JavaScript `Error` and the exported `createError.HttpError`. ### Error Properties - `expose` - can be used to signal if `message` should be sent to the client, defaulting to `false` when `status` >= 500 - `headers` - can be an object of header names to values to be sent to the client, defaulting to `undefined`. When defined, the key names should all be lower-cased - `message` - the traditional error message, which should be kept short and all single line - `status` - the status code of the error, mirroring `statusCode` for general compatibility - `statusCode` - the status code of the error, defaulting to `500` ### createError([status], [message], [properties]) <!-- eslint-disable no-undef, no-unused-vars --> ```js var err = createError(404, 'This video does not exist!') ``` - `status: 500` - the status code as a number - `message` - the message of the error, defaulting to node's text for that status code. - `properties` - custom properties to attach to the object ### new createError\[code || name\](\[msg]\)) <!-- eslint-disable no-undef, no-unused-vars --> ```js var err = new createError.NotFound() ``` - `code` - the status code as a number - `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. #### List of all constructors |Status Code|Constructor Name | |-----------|-----------------------------| |400 |BadRequest | |401 |Unauthorized | |402 |PaymentRequired | |403 |Forbidden | |404 |NotFound | |405 |MethodNotAllowed | |406 |NotAcceptable | |407 |ProxyAuthenticationRequired | |408 |RequestTimeout | |409 |Conflict | |410 |Gone | |411 |LengthRequired | |412 |PreconditionFailed | |413 |PayloadTooLarge | |414 |URITooLong | |415 |UnsupportedMediaType | |416 |RangeNotSatisfiable | |417 |ExpectationFailed | |418 |ImATeapot | |421 |MisdirectedRequest | |422 |UnprocessableEntity | |423 |Locked | |424 |FailedDependency | |425 |UnorderedCollection | |426 |UpgradeRequired | |428 |PreconditionRequired | |429 |TooManyRequests | |431 |RequestHeaderFieldsTooLarge | |451 |UnavailableForLegalReasons | |500 |InternalServerError | |501 |NotImplemented | |502 |BadGateway | |503 |ServiceUnavailable | |504 |GatewayTimeout | |505 |HTTPVersionNotSupported | |506 |VariantAlsoNegotiates | |507 |InsufficientStorage | |508 |LoopDetected | |509 |BandwidthLimitExceeded | |510 |NotExtended | |511 |NetworkAuthenticationRequired| ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/http-errors.svg [npm-url]: https://npmjs.org/package/http-errors [node-version-image]: https://img.shields.io/node/v/http-errors.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg [travis-url]: https://travis-ci.org/jshttp/http-errors [coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg [coveralls-url]: https://coveralls.io/r/jshttp/http-errors [downloads-image]: https://img.shields.io/npm/dm/http-errors.svg [downloads-url]: https://npmjs.org/package/http-errors # default-gateway [![](https://img.shields.io/npm/v/default-gateway.svg?style=flat)](https://www.npmjs.org/package/default-gateway) [![](https://img.shields.io/npm/dm/default-gateway.svg)](https://www.npmjs.org/package/default-gateway) [![](https://api.travis-ci.org/silverwind/default-gateway.svg?style=flat)](https://travis-ci.org/silverwind/default-gateway) > Get the default network gateway, cross-platform. Obtains the machine's default gateway through `exec` calls to OS routing interfaces. On Linux and Android, the `ip` command must be available (usually provided by the `iproute2` package). On IBM i, the `db2util` command must be available (provided by the `db2util` package). ## Installation ``` $ npm install default-gateway ``` ## Example ```js const defaultGateway = require('default-gateway'); defaultGateway.v4().then(result => { // result = {gateway: '1.2.3.4', interface: 'en1'} }); defaultGateway.v6().then(result => { // result = {gateway: '2001:db8::1', interface: 'en2'} }); const result = defaultGateway.v4.sync(); // result = {gateway: '1.2.3.4', interface: 'en1'} const result = defaultGateway.v6.sync(); // result = {gateway: '2001:db8::1', interface: 'en2'} ``` ## API ### defaultGateway.v4() ### defaultGateway.v6() ### defaultGateway.v4.sync() ### defaultGateway.v6.sync() Returns: `result` *Object* - `gateway`: The IP address of the default gateway. - `interface`: The name of the interface. On Windows, this is the network adapter name. The `.v{4,6}()` methods return a Promise while the `.v{4,6}.sync()` variants will return the result synchronously. The `gateway` property will always be defined on success, while `interface` can be `null` if it cannot be determined. All methods reject/throw on unexpected conditions. ## License © [silverwind](https://github.com/silverwind), distributed under BSD licence # Methods [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] HTTP verbs that Node.js core's HTTP parser supports. This module provides an export that is just like `http.METHODS` from Node.js core, with the following differences: * All method names are lower-cased. * Contains a fallback list of methods for Node.js versions that do not have a `http.METHODS` export (0.10 and lower). * Provides the fallback list when using tools like `browserify` without pulling in the `http` shim module. ## Install ```bash $ npm install methods ``` ## API ```js var methods = require('methods') ``` ### methods This is an array of lower-cased method names that Node.js supports. If Node.js provides the `http.METHODS` export, then this is the same array lower-cased, otherwise it is a snapshot of the verbs from Node.js 0.10. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat [npm-url]: https://npmjs.org/package/methods [node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat [travis-url]: https://travis-ci.org/jshttp/methods [coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat [coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master [downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat [downloads-url]: https://npmjs.org/package/methods # stream-shift Returns the next buffer/object in a stream's readable queue ``` npm install stream-shift ``` [![build status](http://img.shields.io/travis/mafintosh/stream-shift.svg?style=flat)](http://travis-ci.org/mafintosh/stream-shift) ## Usage ``` js var shift = require('stream-shift') console.log(shift(someStream)) // first item in its buffer ``` ## Credit Thanks [@dignifiedquire](https://github.com/dignifiedquire) for making this work on node 6 ## License MIT # RegJSParser Parsing the JavaScript's RegExp in JavaScript. ## Installation ```bash npm install regjsparser ``` ## Usage ```js var parse = require('regjsparser').parse; var parseTree = parse('^a'); // /^a/ console.log(parseTree); // Toggle on/off additional features: var parseTree = parse('^a', '', { // SEE: https://github.com/jviereck/regjsparser/pull/78 unicodePropertyEscape: true, // SEE: https://github.com/jviereck/regjsparser/pull/83 namedGroups: true, // SEE: https://github.com/jviereck/regjsparser/pull/89 lookbehind: true }); console.log(parseTree); ``` ## Testing To run the tests, run the following command: ```bash npm test ``` To create a new reference file, execute… ```bash node test/update-fixtures.js ``` …from the repo top directory. <a href="http://promisesaplus.com/"> <img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo" title="Promises/A+ 1.1 compliant" align="right" /> </a> [![Build Status](https://travis-ci.org/petkaantonov/bluebird.svg?branch=master)](https://travis-ci.org/petkaantonov/bluebird) [![coverage-98%](https://img.shields.io/badge/coverage-98%25-brightgreen.svg?style=flat)](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) **Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) # Introduction Bluebird is a fully featured promise library with focus on innovative features and performance See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). ### Note Promises in Node.js 10 are significantly faster than before. Bluebird still includes a lot of features like cancellation, iteration methods and warnings that native promises don't. If you are using Bluebird for performance rather than for those - please consider giving native promises a shot and running the benchmarks yourself. # Questions and issues The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. ## Thanks Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. # License The MIT License (MIT) Copyright (c) 2013-2017 Petka Antonov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JSON Schema is a repository for the JSON Schema specification, reference schemas and a CommonJS implementation of JSON Schema (not the only JavaScript implementation of JSON Schema, JSV is another excellent JavaScript validator). Code is licensed under the AFL or BSD license as part of the Persevere project which is administered under the Dojo foundation, and all contributions require a Dojo CLA. # querystringify [![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](http://img.shields.io/npm/v/querystringify.svg?style=flat-square)](http://browsenpm.org/package/querystringify)[![Build Status](http://img.shields.io/travis/unshiftio/querystringify/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/querystringify)[![Dependencies](https://img.shields.io/david/unshiftio/querystringify.svg?style=flat-square)](https://david-dm.org/unshiftio/querystringify)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/querystringify/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/querystringify?branch=master)[![IRC channel](http://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](http://webchat.freenode.net/?channels=unshift) A somewhat JSON compatible interface for query string parsing. This query string parser is dumb, don't expect to much from it as it only wants to parse simple query strings. If you want to parse complex, multi level and deeply nested query strings then you should ask your self. WTF am I doing? ## Installation This module is released in npm as `querystringify`. It's also compatible with `browserify` so it can be used on the server as well as on the client. To install it simply run the following command from your CLI: ``` npm install --save querystringify ``` ## Usage In the following examples we assume that you've already required the library as: ```js 'use strict'; var qs = require('querystringify'); ``` ### qs.parse() The parse method transforms a given query string in to an object. Parameters without values are set to empty strings. It does not care if your query string is prefixed with a `?` or not. It just extracts the parts between the `=` and `&`: ```js qs.parse('?foo=bar'); // { foo: 'bar' } qs.parse('foo=bar'); // { foo: 'bar' } qs.parse('foo=bar&bar=foo'); // { foo: 'bar', bar: 'foo' } qs.parse('foo&bar=foo'); // { foo: '', bar: 'foo' } ``` ### qs.stringify() This transforms a given object in to a query string. By default we return the query string without a `?` prefix. If you want to prefix it by default simply supply `true` as second argument. If it should be prefixed by something else simply supply a string with the prefix value as second argument: ```js qs.stringify({ foo: bar }); // foo=bar qs.stringify({ foo: bar }, true); // ?foo=bar qs.stringify({ foo: bar }, '&'); // &foo=bar qs.stringify({ foo: '' }, '&'); // &foo= ``` ## License MIT # on-finished [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Execute a callback when a HTTP request closes, finishes, or errors. ## Install ```sh $ npm install on-finished ``` ## API ```js var onFinished = require('on-finished') ``` ### onFinished(res, listener) Attach a listener to listen for the response to finish. The listener will be invoked only once when the response finished. If the response finished to an error, the first argument will contain the error. If the response has already finished, the listener will be invoked. Listening to the end of a response would be used to close things associated with the response, like open files. Listener is invoked as `listener(err, res)`. ```js onFinished(res, function (err, res) { // clean up open fds, etc. // err contains the error is request error'd }) ``` ### onFinished(req, listener) Attach a listener to listen for the request to finish. The listener will be invoked only once when the request finished. If the request finished to an error, the first argument will contain the error. If the request has already finished, the listener will be invoked. Listening to the end of a request would be used to know when to continue after reading the data. Listener is invoked as `listener(err, req)`. ```js var data = '' req.setEncoding('utf8') res.on('data', function (str) { data += str }) onFinished(req, function (err, req) { // data is read unless there is err }) ``` ### onFinished.isFinished(res) Determine if `res` is already finished. This would be useful to check and not even start certain operations if the response has already finished. ### onFinished.isFinished(req) Determine if `req` is already finished. This would be useful to check and not even start certain operations if the request has already finished. ## Special Node.js requests ### HTTP CONNECT method The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: > The CONNECT method requests that the recipient establish a tunnel to > the destination origin server identified by the request-target and, > if successful, thereafter restrict its behavior to blind forwarding > of packets, in both directions, until the tunnel is closed. Tunnels > are commonly used to create an end-to-end virtual connection, through > one or more proxies, which can then be secured using TLS (Transport > Layer Security, [RFC5246]). In Node.js, these request objects come from the `'connect'` event on the HTTP server. When this module is used on a HTTP `CONNECT` request, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `CONNECT` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `CONNECT` request in Node.js, so there is no support for for one. ### HTTP Upgrade request The meaning of the `Upgrade` header from RFC 7230, section 6.1: > The "Upgrade" header field is intended to provide a simple mechanism > for transitioning from HTTP/1.1 to some other protocol on the same > connection. In Node.js, these request objects come from the `'upgrade'` event on the HTTP server. When this module is used on a HTTP request with an `Upgrade` header, the request is considered "finished" immediately, **due to limitations in the Node.js interface**. This means if the `Upgrade` request contains a request entity, the request will be considered "finished" even before it has been read. There is no such thing as a response object to a `Upgrade` request in Node.js, so there is no support for for one. ## Example The following code ensures that file descriptors are always closed once the response finishes. ```js var destroy = require('destroy') var http = require('http') var onFinished = require('on-finished') http.createServer(function onRequest(req, res) { var stream = fs.createReadStream('package.json') stream.pipe(res) onFinished(res, function (err) { destroy(stream) }) }) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/on-finished.svg [npm-url]: https://npmjs.org/package/on-finished [node-version-image]: https://img.shields.io/node/v/on-finished.svg [node-version-url]: http://nodejs.org/download/ [travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg [travis-url]: https://travis-ci.org/jshttp/on-finished [coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master [downloads-image]: https://img.shields.io/npm/dm/on-finished.svg [downloads-url]: https://npmjs.org/package/on-finished # raw-body [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] Gets the entire buffer of a stream either as a `Buffer` or a string. Validates the stream's length against an expected length and maximum limit. Ideal for parsing request bodies. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install raw-body ``` ### TypeScript This module includes a [TypeScript](https://www.typescriptlang.org/) declaration file to enable auto complete in compatible editors and type information for TypeScript projects. This module depends on the Node.js types, so install `@types/node`: ```sh $ npm install @types/node ``` ## API <!-- eslint-disable no-unused-vars --> ```js var getRawBody = require('raw-body') ``` ### getRawBody(stream, [options], [callback]) **Returns a promise if no callback specified and global `Promise` exists.** Options: - `length` - The length of the stream. If the contents of the stream do not add up to this length, an `400` error code is returned. - `limit` - The byte limit of the body. This is the number of bytes or any string format supported by [bytes](https://www.npmjs.com/package/bytes), for example `1000`, `'500kb'` or `'3mb'`. If the body ends up being larger than this limit, a `413` error code is returned. - `encoding` - The encoding to use to decode the body into a string. By default, a `Buffer` instance will be returned when no encoding is specified. Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). You can also pass a string in place of options to just specify the encoding. If an error occurs, the stream will be paused, everything unpiped, and you are responsible for correctly disposing the stream. For HTTP requests, no handling is required if you send a response. For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. ## Errors This module creates errors depending on the error condition during reading. The error may be an error from the underlying Node.js implementation, but is otherwise an error created by this module, which has the following attributes: * `limit` - the limit in bytes * `length` and `expected` - the expected length of the stream * `received` - the received bytes * `encoding` - the invalid encoding * `status` and `statusCode` - the corresponding status code for the error * `type` - the error type ### Types The errors from this module have a `type` property which allows for the progamatic determination of the type of error returned. #### encoding.unsupported This error will occur when the `encoding` option is specified, but the value does not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) module. #### entity.too.large This error will occur when the `limit` option is specified, but the stream has an entity that is larger. #### request.aborted This error will occur when the request stream is aborted by the client before reading the body has finished. #### request.size.invalid This error will occur when the `length` option is specified, but the stream has emitted more bytes. #### stream.encoding.set This error will occur when the given stream has an encoding set on it, making it a decoded stream. The stream should not have an encoding set and is expected to emit `Buffer` objects. ## Examples ### Simple Express example ```js var contentType = require('content-type') var express = require('express') var getRawBody = require('raw-body') var app = express() app.use(function (req, res, next) { getRawBody(req, { length: req.headers['content-length'], limit: '1mb', encoding: contentType.parse(req).parameters.charset }, function (err, string) { if (err) return next(err) req.text = string next() }) }) // now access req.text ``` ### Simple Koa example ```js var contentType = require('content-type') var getRawBody = require('raw-body') var koa = require('koa') var app = koa() app.use(function * (next) { this.text = yield getRawBody(this.req, { length: this.req.headers['content-length'], limit: '1mb', encoding: contentType.parse(this.req).parameters.charset }) yield next }) // now access this.text ``` ### Using as a promise To use this library as a promise, simply omit the `callback` and a promise is returned, provided that a global `Promise` is defined. ```js var getRawBody = require('raw-body') var http = require('http') var server = http.createServer(function (req, res) { getRawBody(req) .then(function (buf) { res.statusCode = 200 res.end(buf.length + ' bytes submitted') }) .catch(function (err) { res.statusCode = 500 res.end(err.message) }) }) server.listen(3000) ``` ### Using with TypeScript ```ts import * as getRawBody from 'raw-body'; import * as http from 'http'; const server = http.createServer((req, res) => { getRawBody(req) .then((buf) => { res.statusCode = 200; res.end(buf.length + ' bytes submitted'); }) .catch((err) => { res.statusCode = err.statusCode; res.end(err.message); }); }); server.listen(3000); ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/raw-body.svg [npm-url]: https://npmjs.org/package/raw-body [node-version-image]: https://img.shields.io/node/v/raw-body.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg [travis-url]: https://travis-ci.org/stream-utils/raw-body [coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg [coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master [downloads-image]: https://img.shields.io/npm/dm/raw-body.svg [downloads-url]: https://npmjs.org/package/raw-body # set-value [![NPM version](https://img.shields.io/npm/v/set-value.svg?style=flat)](https://www.npmjs.com/package/set-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/set-value.svg?style=flat)](https://npmjs.org/package/set-value) [![NPM total downloads](https://img.shields.io/npm/dt/set-value.svg?style=flat)](https://npmjs.org/package/set-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/set-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/set-value) > Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save set-value ``` ## Usage ```js var set = require('set-value'); set(object, prop, value); ``` ### Params * `object` **{object}**: The object to set `value` on * `prop` **{string}**: The property to set. Dot-notation may be used. * `value` **{any}**: The value to set on `object[prop]` ## Examples Updates and returns the given object: ```js var obj = {}; set(obj, 'a.b.c', 'd'); console.log(obj); //=> { a: { b: { c: 'd' } } } ``` ### Escaping **Escaping with backslashes** Prevent set-value from splitting on a dot by prefixing it with backslashes: ```js console.log(set({}, 'a\\.b.c', 'd')); //=> { 'a.b': { c: 'd' } } console.log(set({}, 'a\\.b\\.c', 'd')); //=> { 'a.b.c': 'd' } ``` **Escaping with double-quotes or single-quotes** Wrap double or single quotes around the string, or part of the string, that should not be split by set-value: ```js console.log(set({}, '"a.b".c', 'd')); //=> { 'a.b': { c: 'd' } } console.log(set({}, "'a.b'.c", "d")); //=> { 'a.b': { c: 'd' } } console.log(set({}, '"this/is/a/.file.path"', 'd')); //=> { 'this/is/a/file.path': 'd' } ``` ### Bracket support set-value does not split inside brackets or braces: ```js console.log(set({}, '[a.b].c', 'd')); //=> { '[a.b]': { c: 'd' } } console.log(set({}, "(a.b).c", "d")); //=> { '(a.b)': { c: 'd' } } console.log(set({}, "<a.b>.c", "d")); //=> { '<a.b>': { c: 'd' } } console.log(set({}, "{a..b}.c", "d")); //=> { '{a..b}': { c: 'd' } } ``` ## History ### v2.0.0 * Adds support for escaping with double or single quotes. See [escaping](#escaping) for examples. * Will no longer split inside brackets or braces. See [bracket support](#bracket-support) for examples. If there are any regressions please create a [bug report](../../issues/new). Thanks! ## About ### Related projects * [assign-value](https://www.npmjs.com/package/assign-value): Assign a value or extend a deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/assign-value) | [homepage](https://github.com/jonschlinkert/assign-value "Assign a value or extend a deeply nested property of an object using object path notation.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value "Returns true if a value exists, false if empty. Works with deeply nested values using object paths.") * [merge-value](https://www.npmjs.com/package/merge-value): Similar to assign-value but deeply merges object values or nested values using object path/dot notation. | [homepage](https://github.com/jonschlinkert/merge-value "Similar to assign-value but deeply merges object values or nested values using object path/dot notation.") * [omit-value](https://www.npmjs.com/package/omit-value): Omit properties from an object or deeply nested property of an object using object path… [more](https://github.com/jonschlinkert/omit-value) | [homepage](https://github.com/jonschlinkert/omit-value "Omit properties from an object or deeply nested property of an object using object path notation.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [union-value](https://www.npmjs.com/package/union-value): Set an array of unique values as the property of an object. Supports setting deeply… [more](https://github.com/jonschlinkert/union-value) | [homepage](https://github.com/jonschlinkert/union-value "Set an array of unique values as the property of an object. Supports setting deeply nested properties using using object-paths/dot notation.") * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value "Delete nested properties from an object using dot notation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [vadimdemedes](https://github.com/vadimdemedes) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 21, 2017._ Native Abstractions for Node.js =============================== **A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 11.** ***Current version: 2.13.2*** *(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* [![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) [![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](https://travis-ci.org/nodejs/nan) [![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. This project also contains some helper utilities that make addon development a bit more pleasant. * **[News & Updates](#news)** * **[Usage](#usage)** * **[Example](#example)** * **[API](#api)** * **[Tests](#tests)** * **[Knowns issues](#issues)** * **[Governance & Contributing](#governance)** <a name="news"></a> ## News & Updates <a name="usage"></a> ## Usage Simply add **NAN** as a dependency in the *package.json* of your Node addon: ``` bash $ npm install --save nan ``` Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files: ``` python "include_dirs" : [ "<!(node -e \"require('nan')\")" ] ``` This works like a `-I<path-to-NAN>` when compiling your addon. <a name="example"></a> ## Example Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. <a name="api"></a> ## API Additional to the NAN documentation below, please consult: * [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding) * [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide) * [V8 API Documentation](https://v8docs.nodesource.com/) * [Node Add-on Documentation](https://nodejs.org/api/addons.html) <!-- START API --> ### JavaScript-accessible methods A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. * **Method argument types** - <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a> - <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a> - <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a> * **Method declarations** - <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a> - <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a> - <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a> - <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a> - <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a> - <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a> - <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a> - <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a> - <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a> - <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a> - <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a> - <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a> - <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a> * Method and template helpers - <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a> - <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a> - <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a> - <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a> - <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a> - <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a> - <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a> - <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a> - <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a> - <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a> ### Scopes A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> - <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). ### Persistent references An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a> - <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a> - <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a> - <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a> - <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a> - <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a> - <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a> Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). ### New NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a> - <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a> - <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a> - <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a> - <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a> - <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a> ### Converters NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a> ### Maybe Types The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. * **Maybe Types** - <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a> - <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a> - <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a> - <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a> * **Maybe Helpers** - <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a> - <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a> - <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a> - <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a> - <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a> - <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a> - <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a> - <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a> - <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a> - <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a> - <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a> - <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a> - <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a> - <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a> - <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a> - <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a> - <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a> - <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a> - <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a> ### Script NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> - <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> ### JSON The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. - <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> - <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-8.11/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. ### Errors NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. Note that an Error object is simply a specialized form of `v8::Value`. Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a> - <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a> - <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a> - <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a> - <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a> - <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a> - <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a> - <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a> - <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a> - <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a> - <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a> - <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a> - <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a> ### Buffers NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> - <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> - <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> ### Nan::Callback `Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a> ### Asynchronous work helpers `Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. - <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a> - <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase &amp; Nan::AsyncProgressWorker</code></b></a> - <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a> - <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a> ### Strings & Bytes Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> - <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a> - <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> - <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> ### Object Wrappers The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a> ### V8 internals The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a> - <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a> - <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a> - <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a> - <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a> - <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a> - <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a> - <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a> - <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a> - <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a> - <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a> - <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a> - <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a> - <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a> - <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a> ### Miscellaneous V8 Helpers - <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> - <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> - <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> - <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> - <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> ### Miscellaneous Node Helpers - <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a> - <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a> - <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a> - <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a> <!-- END API --> <a name="tests"></a> ### Tests To run the NAN tests do: ``` sh npm install npm run-script rebuild-tests npm test ``` Or just: ``` sh npm install make test ``` <a name="issues"></a> ## Known issues ### Compiling against Node.js 0.12 on OSX With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12 do not compile anymore. The error looks something like: ``` ❯ CXX(target) Release/obj.target/accessors/cpp/accessors.o In file included from ../cpp/accessors.cpp:9: In file included from ../../nan.h:51: In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: /Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle( ~~~~~~~~~~~~~^~~~~~~~~~~~ ``` This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make `v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore this patch cannot be released by either project in an official release. For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support that configuration, you will need to either get an older compiler, or apply a source patch to the version of V8 headers as a workaround. <a name="governance"></a> ## Governance & Contributing NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api) ### Addon API Working Group (WG) The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects. The WG has final authority over this project including: * Technical direction * Project governance and process (including this policy) * Contribution policy * GitHub repository hosting * Maintaining the list of additional Collaborators For the current list of WG members, see the project [README.md](./README.md#collaborators). Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. _Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). ### Consensus Seeking Process The WG follows a [Consensus Seeking](https://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. <a id="developers-certificate-of-origin"></a> ## Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: * (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or * (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or * (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. * (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. <a name="collaborators"></a> ### WG Members / Collaborators <table><tbody> <tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr> <tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr> <tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr> <tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr> <tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr> <tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr> <tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr> <tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr> </tbody></table> ## Licence &amp; copyright Copyright (c) 2018 NAN WG Members / Collaborators (listed above). Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. has-unicode =========== Try to guess if your terminal supports unicode ```javascript var hasUnicode = require("has-unicode") if (hasUnicode()) { // the terminal probably has unicode support } ``` ```javascript var hasUnicode = require("has-unicode").tryHarder hasUnicode(function(unicodeSupported) { if (unicodeSupported) { // the terminal probably has unicode support } }) ``` ## Detecting Unicode What we actually detect is UTF-8 support, as that's what Node itself supports. If you have a UTF-16 locale then you won't be detected as unicode capable. ### Windows Since at least Windows 7, `cmd` and `powershell` have been unicode capable, but unfortunately even then it's not guaranteed. In many localizations it still uses legacy code pages and there's no facility short of running programs or linking C++ that will let us detect this. As such, we report any Windows installation as NOT unicode capable, and recommend that you encourage your users to override this via config. ### Unix Like Operating Systems We look at the environment variables `LC_ALL`, `LC_CTYPE`, and `LANG` in that order. For `LC_ALL` and `LANG`, it looks for `.UTF-8` in the value. For `LC_CTYPE` it looks to see if the value is `UTF-8`. This is sufficient for most POSIX systems. While locale data can be put in `/etc/locale.conf` as well, AFAIK it's always copied into the environment. # obuf - Offset buffer implementation. Byte buffer specialized for data in chunks with special cases for dropping bytes in the front, merging bytes in to various integer types and abandoning buffer without penalty for previous chunk merges. Used in spyd-transport, part of spdy support for http2. This software is licensed under the MIT License. By Fedor Indutny, 2015. # end-of-stream A node module that calls a callback when a readable/writable/duplex stream has completed or failed. npm install end-of-stream ## Usage Simply pass a stream and a callback to the `eos`. Both legacy streams, streams2 and stream3 are supported. ``` js var eos = require('end-of-stream'); eos(readableStream, function(err) { // this will be set to the stream instance if (err) return console.log('stream had an error or closed early'); console.log('stream has ended', this === readableStream); }); eos(writableStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished', this === writableStream); }); eos(duplexStream, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended and finished', this === duplexStream); }); eos(duplexStream, {readable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has finished but might still be readable'); }); eos(duplexStream, {writable:false}, function(err) { if (err) return console.log('stream had an error or closed early'); console.log('stream has ended but might still be writable'); }); eos(readableStream, {error:false}, function(err) { // do not treat emit('error', err) as a end-of-stream }); ``` ## License MIT ## Related `end-of-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # utils-merge [![Version](https://img.shields.io/npm/v/utils-merge.svg?label=version)](https://www.npmjs.com/package/utils-merge) [![Build](https://img.shields.io/travis/jaredhanson/utils-merge.svg)](https://travis-ci.org/jaredhanson/utils-merge) [![Quality](https://img.shields.io/codeclimate/github/jaredhanson/utils-merge.svg?label=quality)](https://codeclimate.com/github/jaredhanson/utils-merge) [![Coverage](https://img.shields.io/coveralls/jaredhanson/utils-merge.svg)](https://coveralls.io/r/jaredhanson/utils-merge) [![Dependencies](https://img.shields.io/david/jaredhanson/utils-merge.svg)](https://david-dm.org/jaredhanson/utils-merge) Merges the properties from a source object into a destination object. ## Install ```bash $ npm install utils-merge ``` ## Usage ```javascript var a = { foo: 'bar' } , b = { bar: 'baz' }; merge(a, b); // => { foo: 'bar', bar: 'baz' } ``` ## License [The MIT License](http://opensource.org/licenses/MIT) Copyright (c) 2013-2017 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> <a target='_blank' rel='nofollow' href='https://app.codesponsor.io/link/vK9dyjRnnWsMzzJTQ57fRJpH/jaredhanson/utils-merge'> <img alt='Sponsor' width='888' height='68' src='https://app.codesponsor.io/embed/vK9dyjRnnWsMzzJTQ57fRJpH/jaredhanson/utils-merge.svg' /></a> # is-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/is-buffer/master.svg [travis-url]: https://travis-ci.org/feross/is-buffer [npm-image]: https://img.shields.io/npm/v/is-buffer.svg [npm-url]: https://npmjs.org/package/is-buffer [downloads-image]: https://img.shields.io/npm/dm/is-buffer.svg [downloads-url]: https://npmjs.org/package/is-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Determine if an object is a [`Buffer`](http://nodejs.org/api/buffer.html) (including the [browserify Buffer](https://github.com/feross/buffer)) [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/is-buffer.svg [saucelabs-url]: https://saucelabs.com/u/is-buffer ## Why not use `Buffer.isBuffer`? This module lets you check if an object is a `Buffer` without using `Buffer.isBuffer` (which includes the whole [buffer](https://github.com/feross/buffer) module in [browserify](http://browserify.org/)). It's future-proof and works in node too! ## install ```bash npm install is-buffer ``` ## usage ```js var isBuffer = require('is-buffer') isBuffer(new Buffer(4)) // true isBuffer(undefined) // false isBuffer(null) // false isBuffer('') // false isBuffer(true) // false isBuffer(false) // false isBuffer(0) // false isBuffer(1) // false isBuffer(1.0) // false isBuffer('string') // false isBuffer({}) // false isBuffer(function foo () {}) // false ``` ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). # which Like the unix `which` utility. Finds the first instance of a specified executable in the PATH environment variable. Does not cache the results, so `hash -r` is not needed when the PATH changes. ## USAGE ```javascript var which = require('which') // async usage which('node', function (er, resolvedPath) { // er is returned if no "node" is found on the PATH // if it is found, then the absolute path to the exec is returned }) // sync usage // throws if not found var resolved = which.sync('node') // if nothrow option is used, returns null if not found resolved = which.sync('node', {nothrow: true}) // Pass options to override the PATH and PATHEXT environment vars. which('node', { path: someOtherPath }, function (er, resolved) { if (er) throw er console.log('found at %j', resolved) }) ``` ## CLI USAGE Same as the BSD `which(1)` binary. ``` usage: which [-as] program ... ``` ## OPTIONS You may pass an options object as the second argument. - `path`: Use instead of the `PATH` environment variable. - `pathExt`: Use instead of the `PATHEXT` environment variable. - `all`: Return all matches, instead of just the first one. Note that this means the function returns an array of strings instead of a single string. # npm-bundled Run this in a node package, and it'll tell you which things in node_modules are bundledDependencies, or transitive dependencies of bundled dependencies. [![Build Status](https://travis-ci.org/npm/npm-bundled.svg?branch=master)](https://travis-ci.org/npm/npm-bundled) ## USAGE To get the list of deps at the top level that are bundled (or transitive deps of a bundled dep) run this: ```js const bundled = require('npm-bundled') // async version bundled({ path: '/path/to/pkg/defaults/to/cwd'}, (er, list) => { // er means it had an error, which is _hella_ weird // list is a list of package names, like `fooblz` or `@corp/blerg` // the might not all be deps of the top level, because transitives }) // async promise version bundled({ path: '/path/to/pkg/defaults/to/cwd'}).then(list => { // so promisey! // actually the callback version returns a promise, too, it just // attaches the supplied callback to the promise }) // sync version, throws if there's an error const list = bundled({ path: '/path/to/pkg/defaults/to/cwd'}) ``` That's basically all you need to know. If you care to dig into it, you can also use the `bundled.Walker` and `bundled.WalkerSync` classes to get fancy. This library does not write anything to the filesystem, but it _may_ have undefined behavior if the structure of `node_modules` changes while it's reading deps. All symlinks are followed. This means that it can lead to surprising results if a symlinked bundled dependency has a missing dependency that is satisfied at the top level. Since package creation resolves symlinks as well, this is an edge case where package creation and development environment are not going to be aligned, and is best avoided. # detect-libc Node.js module to detect the C standard library (libc) implementation family and version in use on a given Linux system. Provides a value suitable for use with the `LIBC` option of [prebuild](https://www.npmjs.com/package/prebuild), [prebuild-ci](https://www.npmjs.com/package/prebuild-ci) and [prebuild-install](https://www.npmjs.com/package/prebuild-install), therefore allowing build and provision of pre-compiled binaries for musl-based Linux e.g. Alpine as well as glibc-based. Currently supports libc detection of `glibc` and `musl`. ## Install ```sh npm install detect-libc ``` ## Usage ### API ```js const { GLIBC, MUSL, family, version, isNonGlibcLinux } = require('detect-libc'); ``` * `GLIBC` is a String containing the value "glibc" for comparison with `family`. * `MUSL` is a String containing the value "musl" for comparison with `family`. * `family` is a String representing the system libc family. * `version` is a String representing the system libc version number. * `isNonGlibcLinux` is a Boolean representing whether the system is a non-glibc Linux, e.g. Alpine. ### detect-libc command line tool When run on a Linux system with a non-glibc libc, the child command will be run with the `LIBC` environment variable set to the relevant value. On all other platforms will run the child command as-is. The command line feature requires `spawnSync` provided by Node v0.12+. ```sh detect-libc child-command ``` ## Integrating with prebuild ```json "scripts": { "install": "detect-libc prebuild-install || node-gyp rebuild", "test": "mocha && detect-libc prebuild-ci" }, "dependencies": { "detect-libc": "^1.0.2", "prebuild-install": "^2.2.0" }, "devDependencies": { "prebuild": "^6.2.1", "prebuild-ci": "^2.2.3" } ``` ## Licence Copyright 2017 Lovell Fuller Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # homedir-polyfill [![NPM version](https://img.shields.io/npm/v/homedir-polyfill.svg?style=flat)](https://www.npmjs.com/package/homedir-polyfill) [![NPM monthly downloads](https://img.shields.io/npm/dm/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![NPM total downloads](https://img.shields.io/npm/dt/homedir-polyfill.svg?style=flat)](https://npmjs.org/package/homedir-polyfill) [![Linux Build Status](https://img.shields.io/travis/doowb/homedir-polyfill.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/homedir-polyfill) [![Windows Build Status](https://img.shields.io/appveyor/ci/doowb/homedir-polyfill.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/doowb/homedir-polyfill) > Node.js os.homedir polyfill for older versions of node.js. Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save homedir-polyfill ``` ## Usage ```js var homedir = require('homedir-polyfill'); console.log(homedir()); //=> /Users/doowb ``` ## Reasoning This library is a polyfill for the [node.js os.homedir](https://nodejs.org/api/os.html#os_os_homedir) method found in modern versions of node.js. This implementation tries to follow the implementation found in `libuv` by finding the current user using the `process.geteuid()` method and the `/etc/passwd` file. This should usually work in a linux environment, but will also fallback to looking at user specific environment variables to build the user's home directory if neccessary. Since `/etc/passwd` is not available on windows platforms, this implementation will use environment variables to find the home directory. In modern versions of node.js, [os.homedir](https://nodejs.org/api/os.html#os_os_homedir) is used. ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](contributing.md) for advice on opening issues, pull requests, and coding standards. </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: [parse-passwd](https://www.npmjs.com/package/parse-passwd): Parse a passwd file into a list of users. | [homepage](https://github.com/doowb/parse-passwd "Parse a passwd file into a list of users.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 19 | [doowb](https://github.com/doowb) | | 2 | [martinheidegger](https://github.com/martinheidegger) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) ### License Copyright © 2016 - 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on February 21, 2019._ # body-parser [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Node.js body parsing middleware. Parse incoming request bodies in a middleware before your handlers, available under the `req.body` property. **Note** As `req.body`'s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, `req.body.foo.toString()` may fail in multiple ways, for example the `foo` property may not be there or may not be a string, and `toString` may not be a function and instead a string or other user input. [Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). _This does not handle multipart bodies_, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules: * [busboy](https://www.npmjs.org/package/busboy#readme) and [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) * [multiparty](https://www.npmjs.org/package/multiparty#readme) and [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) * [formidable](https://www.npmjs.org/package/formidable#readme) * [multer](https://www.npmjs.org/package/multer#readme) This module provides the following parsers: * [JSON body parser](#bodyparserjsonoptions) * [Raw body parser](#bodyparserrawoptions) * [Text body parser](#bodyparsertextoptions) * [URL-encoded form body parser](#bodyparserurlencodedoptions) Other body parsers you might be interested in: - [body](https://www.npmjs.org/package/body#readme) - [co-body](https://www.npmjs.org/package/co-body#readme) ## Installation ```sh $ npm install body-parser ``` ## API <!-- eslint-disable no-unused-vars --> ```js var bodyParser = require('body-parser') ``` The `bodyParser` object exposes various factories to create middlewares. All middlewares will populate the `req.body` property with the parsed body when the `Content-Type` request header matches the `type` option, or an empty object (`{}`) if there was no body to parse, the `Content-Type` was not matched, or an error occurred. The various errors returned by this module are described in the [errors section](#errors). ### bodyParser.json([options]) Returns middleware that only parses `json` and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts any Unicode encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). #### Options The `json` function takes an optional `options` object that may contain any of the following keys: ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. ##### reviver The `reviver` option is passed directly to `JSON.parse` as the second argument. You can find more information on this argument [in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). ##### strict When set to `true`, will only accept arrays and objects; when `false` will accept anything `JSON.parse` accepts. Defaults to `true`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `json`), a mime type (like `application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/json`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.raw([options]) Returns middleware that parses all bodies as a `Buffer` and only looks at requests where the `Content-Type` header matches the `type` option. This parser supports automatic inflation of `gzip` and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a `Buffer` object of the body. #### Options The `raw` function takes an optional `options` object that may contain any of the following keys: ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `bin`), a mime type (like `application/octet-stream`), or a mime type with a wildcard (like `*/*` or `application/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/octet-stream`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.text([options]) Returns middleware that parses all bodies as a string and only looks at requests where the `Content-Type` header matches the `type` option. This parser supports automatic inflation of `gzip` and `deflate` encodings. A new `body` string containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This will be a string of the body. #### Options The `text` function takes an optional `options` object that may contain any of the following keys: ##### defaultCharset Specify the default character set for the text content if the charset is not specified in the `Content-Type` header of the request. Defaults to `utf-8`. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `txt`), a mime type (like `text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `text/plain`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ### bodyParser.urlencoded([options]) Returns middleware that only parses `urlencoded` bodies and only looks at requests where the `Content-Type` header matches the `type` option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of `gzip` and `deflate` encodings. A new `body` object containing the parsed data is populated on the `request` object after the middleware (i.e. `req.body`). This object will contain key-value pairs, where the value can be a string or array (when `extended` is `false`), or any type (when `extended` is `true`). #### Options The `urlencoded` function takes an optional `options` object that may contain any of the following keys: ##### extended The `extended` option allows to choose between parsing the URL-encoded data with the `querystring` library (when `false`) or the `qs` library (when `true`). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please [see the qs library](https://www.npmjs.org/package/qs#readme). Defaults to `true`, but using the default has been deprecated. Please research into the difference between `qs` and `querystring` and choose the appropriate setting. ##### inflate When set to `true`, then deflated (compressed) bodies will be inflated; when `false`, deflated bodies are rejected. Defaults to `true`. ##### limit Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the [bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults to `'100kb'`. ##### parameterLimit The `parameterLimit` option controls the maximum number of parameters that are allowed in the URL-encoded data. If a request contains more parameters than this value, a 413 will be returned to the client. Defaults to `1000`. ##### type The `type` option is used to determine what media type the middleware will parse. This option can be a string, array of strings, or a function. If not a function, `type` option is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) library and this can be an extension name (like `urlencoded`), a mime type (like `application/x-www-form-urlencoded`), or a mime type with a wildcard (like `*/x-www-form-urlencoded`). If a function, the `type` option is called as `fn(req)` and the request is parsed if it returns a truthy value. Defaults to `application/x-www-form-urlencoded`. ##### verify The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, where `buf` is a `Buffer` of the raw request body and `encoding` is the encoding of the request. The parsing can be aborted by throwing an error. ## Errors The middlewares provided by this module create errors depending on the error condition during parsing. The errors will typically have a `status`/`statusCode` property that contains the suggested HTTP response code, an `expose` property to determine if the `message` property should be displayed to the client, a `type` property to determine the type of error without matching against the `message`, and a `body` property containing the read body, if available. The following are the common errors emitted, though any error can come through for various reasons. ### content encoding unsupported This error will occur when the request had a `Content-Encoding` header that contained an encoding but the "inflation" option was set to `false`. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `charset` property will be set to the encoding that is unsupported. ### request aborted This error will occur when the request is aborted by the client before reading the body has finished. The `received` property will be set to the number of bytes received before the request was aborted and the `expected` property is set to the number of expected bytes. The `status` property is set to `400` and `type` property is set to `'request.aborted'`. ### request entity too large This error will occur when the request body's size is larger than the "limit" option. The `limit` property will be set to the byte limit and the `length` property will be set to the request body's length. The `status` property is set to `413` and the `type` property is set to `'entity.too.large'`. ### request size did not match content length This error will occur when the request's length did not match the length from the `Content-Length` header. This typically occurs when the request is malformed, typically when the `Content-Length` header was calculated based on characters instead of bytes. The `status` property is set to `400` and the `type` property is set to `'request.size.invalid'`. ### stream encoding should not be set This error will occur when something called the `req.setEncoding` method prior to this middleware. This module operates directly on bytes only and you cannot call `req.setEncoding` when using this module. The `status` property is set to `500` and the `type` property is set to `'stream.encoding.set'`. ### too many parameters This error will occur when the content of the request exceeds the configured `parameterLimit` for the `urlencoded` parser. The `status` property is set to `413` and the `type` property is set to `'parameters.too.many'`. ### unsupported charset "BOGUS" This error will occur when the request had a charset parameter in the `Content-Type` header, but the `iconv-lite` module does not support it OR the parser does not support it. The charset is contained in the message as well as in the `charset` property. The `status` property is set to `415`, the `type` property is set to `'charset.unsupported'`, and the `charset` property is set to the charset that is unsupported. ### unsupported content encoding "bogus" This error will occur when the request had a `Content-Encoding` header that contained an unsupported encoding. The encoding is contained in the message as well as in the `encoding` property. The `status` property is set to `415`, the `type` property is set to `'encoding.unsupported'`, and the `encoding` property is set to the encoding that is unsupported. ## Examples ### Express/Connect top-level generic This example demonstrates adding a generic JSON and URL-encoded parser as a top-level middleware, which will parse the bodies of all incoming requests. This is the simplest setup. ```js var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.use(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('you posted:\n') res.end(JSON.stringify(req.body, null, 2)) }) ``` ### Express route-specific This example demonstrates adding body parsers specifically to the routes that need them. In general, this is the most recommended way to use body-parser with Express. ```js var express = require('express') var bodyParser = require('body-parser') var app = express() // create application/json parser var jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login gets urlencoded bodies app.post('/login', urlencodedParser, function (req, res) { if (!req.body) return res.sendStatus(400) res.send('welcome, ' + req.body.username) }) // POST /api/users gets JSON bodies app.post('/api/users', jsonParser, function (req, res) { if (!req.body) return res.sendStatus(400) // create user in req.body }) ``` ### Change accepted type for parsers All the parsers accept a `type` option which allows you to change the `Content-Type` that the middleware will parse. ```js var express = require('express') var bodyParser = require('body-parser') var app = express() // parse various different custom JSON types as JSON app.use(bodyParser.json({ type: 'application/*+json' })) // parse some custom thing into a Buffer app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) // parse an HTML body into a string app.use(bodyParser.text({ type: 'text/html' })) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/body-parser.svg [npm-url]: https://npmjs.org/package/body-parser [travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg [travis-url]: https://travis-ci.org/expressjs/body-parser [coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg [coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master [downloads-image]: https://img.shields.io/npm/dm/body-parser.svg [downloads-url]: https://npmjs.org/package/body-parser # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![Coverage Status](https://coveralls.io/repos/github/mozilla/source-map/badge.svg)](https://coveralls.io/github/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://unpkg.com/[email protected]/dist/source-map.js"></script> <script> sourceMap.SourceMapConsumer.initialize({ "lib/mappings.wasm": "https://unpkg.com/[email protected]/lib/mappings.wasm" }); </script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [SourceMapConsumer.initialize(options)](#sourcemapconsumerinitializeoptions) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.with](#sourcemapconsumerwith) - [SourceMapConsumer.prototype.destroy()](#sourcemapconsumerprototypedestroy) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js const rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => { console.log(consumer.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(consumer.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(consumer.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } consumer.eachMapping(function (m) { // ... }); return computeWhatever(); }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A `SourceMapConsumer` instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### SourceMapConsumer.initialize(options) When using `SourceMapConsumer` outside of node.js, for example on the Web, it needs to know from what URL to load `lib/mappings.wasm`. You must inform it by calling `initialize` before constructing any `SourceMapConsumer`s. The options object has the following properties: * `"lib/mappings.wasm"`: A `String` containing the URL of the `lib/mappings.wasm` file. ```js sourceMap.SourceMapConsumer.initialize({ "lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm" }); ``` #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. The promise of the constructed souce map consumer is returned. When the `SourceMapConsumer` will no longer be used anymore, you must call its `destroy` method. ```js const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData); doStuffWith(consumer); consumer.destroy(); ``` Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember to call `destroy`. #### SourceMapConsumer.with Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl` (see the `SourceMapConsumer` constructor for details. Then, invoke the `async function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait for `f` to complete, call `destroy` on the consumer, and return `f`'s return value. You must not use the consumer after `f` completes! By using `with`, you do not have to remember to manually call `destroy` on the consumer, since it will be called automatically once `f` completes. ```js const xSquared = await SourceMapConsumer.with( myRawSourceMap, null, async function (consumer) { // Use `consumer` inside here and don't worry about remembering // to call `destroy`. const x = await whatever(consumer); return x * x; } ); // You may not use that `consumer` anymore out here; it has // been destroyed. But you can use `xSquared`. console.log(xSquared); ``` #### SourceMapConsumer.prototype.destroy() Free this source map consumer's associated wasm data that is manually-managed. ```js consumer.destroy(); ``` Alternatively, you can use `SourceMapConsumer.with` to avoid needing to remember to call `destroy`. #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js const consumer = await new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); const node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # jsprim: utilities for primitive JavaScript types This module provides miscellaneous facilities for working with strings, numbers, dates, and objects and arrays of these basic types. ### deepCopy(obj) Creates a deep copy of a primitive type, object, or array of primitive types. ### deepEqual(obj1, obj2) Returns whether two objects are equal. ### isEmpty(obj) Returns true if the given object has no properties and false otherwise. This is O(1) (unlike `Object.keys(obj).length === 0`, which is O(N)). ### hasKey(obj, key) Returns true if the given object has an enumerable, non-inherited property called `key`. [For information on enumerability and ownership of properties, see the MDN documentation.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) ### forEachKey(obj, callback) Like Array.forEach, but iterates enumerable, owned properties of an object rather than elements of an array. Equivalent to: for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { callback(key, obj[key]); } } ### flattenObject(obj, depth) Flattens an object up to a given level of nesting, returning an array of arrays of length "depth + 1", where the first "depth" elements correspond to flattened columns and the last element contains the remaining object . For example: flattenObject({ 'I': { 'A': { 'i': { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] }, 'ii': { 'datum1': [ 3, 4 ] } }, 'B': { 'i': { 'datum1': [ 5, 6 ] }, 'ii': { 'datum1': [ 7, 8 ], 'datum2': [ 3, 4 ], }, 'iii': { } } }, 'II': { 'A': { 'i': { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } } } }, 3) becomes: [ [ 'I', 'A', 'i', { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ], [ 'I', 'A', 'ii', { 'datum1': [ 3, 4 ] } ], [ 'I', 'B', 'i', { 'datum1': [ 5, 6 ] } ], [ 'I', 'B', 'ii', { 'datum1': [ 7, 8 ], 'datum2': [ 3, 4 ] } ], [ 'I', 'B', 'iii', {} ], [ 'II', 'A', 'i', { 'datum1': [ 1, 2 ], 'datum2': [ 3, 4 ] } ] ] This function is strict: "depth" must be a non-negative integer and "obj" must be a non-null object with at least "depth" levels of nesting under all keys. ### flattenIter(obj, depth, func) This is similar to `flattenObject` except that instead of returning an array, this function invokes `func(entry)` for each `entry` in the array that `flattenObject` would return. `flattenIter(obj, depth, func)` is logically equivalent to `flattenObject(obj, depth).forEach(func)`. Importantly, this version never constructs the full array. Its memory usage is O(depth) rather than O(n) (where `n` is the number of flattened elements). There's another difference between `flattenObject` and `flattenIter` that's related to the special case where `depth === 0`. In this case, `flattenObject` omits the array wrapping `obj` (which is regrettable). ### pluck(obj, key) Fetch nested property "key" from object "obj", traversing objects as needed. For example, `pluck(obj, "foo.bar.baz")` is roughly equivalent to `obj.foo.bar.baz`, except that: 1. If traversal fails, the resulting value is undefined, and no error is thrown. For example, `pluck({}, "foo.bar")` is just undefined. 2. If "obj" has property "key" directly (without traversing), the corresponding property is returned. For example, `pluck({ 'foo.bar': 1 }, 'foo.bar')` is 1, not undefined. This is also true recursively, so `pluck({ 'a': { 'foo.bar': 1 } }, 'a.foo.bar')` is also 1, not undefined. ### randElt(array) Returns an element from "array" selected uniformly at random. If "array" is empty, throws an Error. ### startsWith(str, prefix) Returns true if the given string starts with the given prefix and false otherwise. ### endsWith(str, suffix) Returns true if the given string ends with the given suffix and false otherwise. ### parseInteger(str, options) Parses the contents of `str` (a string) as an integer. On success, the integer value is returned (as a number). On failure, an error is **returned** describing why parsing failed. By default, leading and trailing whitespace characters are not allowed, nor are trailing characters that are not part of the numeric representation. This behaviour can be toggled by using the options below. The empty string (`''`) is not considered valid input. If the return value cannot be precisely represented as a number (i.e., is smaller than `Number.MIN_SAFE_INTEGER` or larger than `Number.MAX_SAFE_INTEGER`), an error is returned. Additionally, the string `'-0'` will be parsed as the integer `0`, instead of as the IEEE floating point value `-0`. This function accepts both upper and lowercase characters for digits, similar to `parseInt()`, `Number()`, and [strtol(3C)](https://illumos.org/man/3C/strtol). The following may be specified in `options`: Option | Type | Default | Meaning ------------------ | ------- | ------- | --------------------------- base | number | 10 | numeric base (radix) to use, in the range 2 to 36 allowSign | boolean | true | whether to interpret any leading `+` (positive) and `-` (negative) characters allowImprecise | boolean | false | whether to accept values that may have lost precision (past `MAX_SAFE_INTEGER` or below `MIN_SAFE_INTEGER`) allowPrefix | boolean | false | whether to interpret the prefixes `0b` (base 2), `0o` (base 8), `0t` (base 10), or `0x` (base 16) allowTrailing | boolean | false | whether to ignore trailing characters trimWhitespace | boolean | false | whether to trim any leading or trailing whitespace/line terminators leadingZeroIsOctal | boolean | false | whether a leading zero indicates octal Note that if `base` is unspecified, and `allowPrefix` or `leadingZeroIsOctal` are, then the leading characters can change the default base from 10. If `base` is explicitly specified and `allowPrefix` is true, then the prefix will only be accepted if it matches the specified base. `base` and `leadingZeroIsOctal` cannot be used together. **Context:** It's tricky to parse integers with JavaScript's built-in facilities for several reasons: - `parseInt()` and `Number()` by default allow the base to be specified in the input string by a prefix (e.g., `0x` for hex). - `parseInt()` allows trailing nonnumeric characters. - `Number(str)` returns 0 when `str` is the empty string (`''`). - Both functions return incorrect values when the input string represents a valid integer outside the range of integers that can be represented precisely. Specifically, `parseInt('9007199254740993')` returns 9007199254740992. - Both functions always accept `-` and `+` signs before the digit. - Some older JavaScript engines always interpret a leading 0 as indicating octal, which can be surprising when parsing input from users who expect a leading zero to be insignificant. While each of these may be desirable in some contexts, there are also times when none of them are wanted. `parseInteger()` grants greater control over what input's permissible. ### iso8601(date) Converts a Date object to an ISO8601 date string of the form "YYYY-MM-DDTHH:MM:SS.sssZ". This format is not customizable. ### parseDateTime(str) Parses a date expressed as a string, as either a number of milliseconds since the epoch or any string format that Date accepts, giving preference to the former where these two sets overlap (e.g., strings containing small numbers). ### hrtimeDiff(timeA, timeB) Given two hrtime readings (as from Node's `process.hrtime()`), where timeA is later than timeB, compute the difference and return that as an hrtime. It is illegal to invoke this for a pair of times where timeB is newer than timeA. ### hrtimeAdd(timeA, timeB) Add two hrtime intervals (as from Node's `process.hrtime()`), returning a new hrtime interval array. This function does not modify either input argument. ### hrtimeAccum(timeA, timeB) Add two hrtime intervals (as from Node's `process.hrtime()`), storing the result in `timeA`. This function overwrites (and returns) the first argument passed in. ### hrtimeNanosec(timeA), hrtimeMicrosec(timeA), hrtimeMillisec(timeA) This suite of functions converts a hrtime interval (as from Node's `process.hrtime()`) into a scalar number of nanoseconds, microseconds or milliseconds. Results are truncated, as with `Math.floor()`. ### validateJsonObject(schema, object) Uses JSON validation (via JSV) to validate the given object against the given schema. On success, returns null. On failure, *returns* (does not throw) a useful Error object. ### extraProperties(object, allowed) Check an object for unexpected properties. Accepts the object to check, and an array of allowed property name strings. If extra properties are detected, an array of extra property names is returned. If no properties other than those in the allowed list are present on the object, the returned array will be of zero length. ### mergeObjects(provided, overrides, defaults) Merge properties from objects "provided", "overrides", and "defaults". The intended use case is for functions that accept named arguments in an "args" object, but want to provide some default values and override other values. In that case, "provided" is what the caller specified, "overrides" are what the function wants to override, and "defaults" contains default values. The function starts with the values in "defaults", overrides them with the values in "provided", and then overrides those with the values in "overrides". For convenience, any of these objects may be falsey, in which case they will be ignored. The input objects are never modified, but properties in the returned object are not deep-copied. For example: mergeObjects(undefined, { 'objectMode': true }, { 'highWaterMark': 0 }) returns: { 'objectMode': true, 'highWaterMark': 0 } For another example: mergeObjects( { 'highWaterMark': 16, 'objectMode': 7 }, /* from caller */ { 'objectMode': true }, /* overrides */ { 'highWaterMark': 0 }); /* default */ returns: { 'objectMode': true, 'highWaterMark': 16 } # Contributing See separate [contribution guidelines](CONTRIBUTING.md). # ESLint Scope ESLint Scope is the [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) scope analyzer used in ESLint. It is a fork of [escope](http://github.com/estools/escope). ## Usage Install: ``` npm i eslint-scope --save ``` Example: ```js var eslintScope = require('eslint-scope'); var espree = require('espree'); var estraverse = require('estraverse'); var ast = espree.parse(code); var scopeManager = eslintScope.analyze(ast); var currentScope = scopeManager.acquire(ast); // global scope estraverse.traverse(ast, { enter: function(node, parent) { // do stuff if (/Function/.test(node.type)) { currentScope = scopeManager.acquire(node); // get current function scope } }, leave: function(node, parent) { if (/Function/.test(node.type)) { currentScope = currentScope.upper; // set to parent scope } // do stuff } }); ``` ## Contributing Issues and pull requests will be triaged and responded to as quickly as possible. We operate under the [ESLint Contributor Guidelines](http://eslint.org/docs/developer-guide/contributing), so please be sure to read them before contributing. If you're not sure where to dig in, check out the [issues](https://github.com/eslint/eslint-scope/issues). ## Build Commands * `npm test` - run all linting and tests * `npm run lint` - run all linting ## License ESLint Scope is licensed under a permissive BSD 2-clause license. <p align="center"> <img width="250" src="/yargs-logo.png"> </p> <h1 align="center"> Yargs </h1> <p align="center"> <b >Yargs be a node.js library fer hearties tryin' ter parse optstrings</b> </p> <br> [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] [![Conventional Commits][conventional-commits-image]][conventional-commits-url] [![Slack][slack-image]][slack-url] ## Description : Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. It gives you: * commands and (grouped) options (`my-program.js serve --port=5000`). * a dynamically generated help menu based on your arguments. > <img width="400" src="/screen.png"> * bash-completion shortcuts for commands and options. * and [tons more](/docs/api.md). ## Installation Stable version: ```bash npm i yargs --save ``` Bleeding edge version with the most recent features: ```bash npm i yargs@next --save ``` ## Usage : ### Simple Example ````javascript #!/usr/bin/env node const argv = require('yargs').argv if (argv.ships > 3 && argv.distance < 53.5) { console.log('Plunder more riffiwobbles!') } else { console.log('Retreat from the xupptumblers!') } ```` ```bash $ ./plunder.js --ships=4 --distance=22 Plunder more riffiwobbles! $ ./plunder.js --ships 12 --distance 98.7 Retreat from the xupptumblers! ``` ### Complex Example ```javascript #!/usr/bin/env node require('yargs') // eslint-disable-line .command('serve [port]', 'start the server', (yargs) => { yargs .positional('port', { describe: 'port to bind on', default: 5000 }) }, (argv) => { if (argv.verbose) console.info(`start server on :${argv.port}`) serve(argv.port) }) .option('verbose', { alias: 'v', default: false }) .argv ``` Run the example above with `--help` to see the help for the application. ## Community : Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). ## Documentation : ### Table of Contents * [Yargs' API](/docs/api.md) * [Examples](/docs/examples.md) * [Parsing Tricks](/docs/tricks.md) * [Stop the Parser](/docs/tricks.md#stop) * [Negating Boolean Arguments](/docs/tricks.md#negate) * [Numbers](/docs/tricks.md#numbers) * [Arrays](/docs/tricks.md#arrays) * [Objects](/docs/tricks.md#objects) * [Advanced Topics](/docs/advanced.md) * [Composing Your App Using Commands](/docs/advanced.md#commands) * [Building Configurable CLI Apps](/docs/advanced.md#configuration) * [Customizing Yargs' Parser](/docs/advanced.md#customizing) * [Contributing](/contributing.md) [travis-url]: https://travis-ci.org/yargs/yargs [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg [coveralls-url]: https://coveralls.io/github/yargs/yargs [coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg [npm-url]: https://www.npmjs.com/package/yargs [npm-image]: https://img.shields.io/npm/v/yargs.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: http://standardjs.com/ [conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg [conventional-commits-url]: https://conventionalcommits.org/ [slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg [slack-url]: http://devtoolscommunity.herokuapp.com # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ This folder contains entry points for all stable `core-js` features with dependencies. It's the recommended way for usage only required features. # Console Control Strings A library of cross-platform tested terminal/console command strings for doing things like color and cursor positioning. This is a subset of both ansi and vt100. All control codes included work on both Windows & Unix-like OSes, except where noted. ## Usage ```js var consoleControl = require('console-control-strings') console.log(consoleControl.color('blue','bgRed', 'bold') + 'hi there' + consoleControl.color('reset')) process.stdout.write(consoleControl.goto(75, 10)) ``` ## Why Another? There are tons of libraries similar to this one. I wanted one that was: 1. Very clear about compatibility goals. 2. Could emit, for instance, a start color code without an end one. 3. Returned strings w/o writing to streams. 4. Was not weighed down with other unrelated baggage. ## Functions ### var code = consoleControl.up(_num = 1_) Returns the escape sequence to move _num_ lines up. ### var code = consoleControl.down(_num = 1_) Returns the escape sequence to move _num_ lines down. ### var code = consoleControl.forward(_num = 1_) Returns the escape sequence to move _num_ lines righ. ### var code = consoleControl.back(_num = 1_) Returns the escape sequence to move _num_ lines left. ### var code = consoleControl.nextLine(_num = 1_) Returns the escape sequence to move _num_ lines down and to the beginning of the line. ### var code = consoleControl.previousLine(_num = 1_) Returns the escape sequence to move _num_ lines up and to the beginning of the line. ### var code = consoleControl.eraseData() Returns the escape sequence to erase everything from the current cursor position to the bottom right of the screen. This is line based, so it erases the remainder of the current line and all following lines. ### var code = consoleControl.eraseLine() Returns the escape sequence to erase to the end of the current line. ### var code = consoleControl.goto(_x_, _y_) Returns the escape sequence to move the cursor to the designated position. Note that the origin is _1, 1_ not _0, 0_. ### var code = consoleControl.gotoSOL() Returns the escape sequence to move the cursor to the beginning of the current line. (That is, it returns a carriage return, `\r`.) ### var code = consoleControl.beep() Returns the escape sequence to cause the termianl to beep. (That is, it returns unicode character `\x0007`, a Control-G.) ### var code = consoleControl.hideCursor() Returns the escape sequence to hide the cursor. ### var code = consoleControl.showCursor() Returns the escape sequence to show the cursor. ### var code = consoleControl.color(_colors = []_) ### var code = consoleControl.color(_color1_, _color2_, _…_, _colorn_) Returns the escape sequence to set the current terminal display attributes (mostly colors). Arguments can either be a list of attributes or an array of attributes. The difference between passing in an array or list of colors and calling `.color` separately for each one, is that in the former case a single escape sequence will be produced where as in the latter each change will have its own distinct escape sequence. Each attribute can be one of: * Reset: * **reset** – Reset all attributes to the terminal default. * Styles: * **bold** – Display text as bold. In some terminals this means using a bold font, in others this means changing the color. In some it means both. * **italic** – Display text as italic. This is not available in most Windows terminals. * **underline** – Underline text. This is not available in most Windows Terminals. * **inverse** – Invert the foreground and background colors. * **stopBold** – Do not display text as bold. * **stopItalic** – Do not display text as italic. * **stopUnderline** – Do not underline text. * **stopInverse** – Do not invert foreground and background. * Colors: * **white** * **black** * **blue** * **cyan** * **green** * **magenta** * **red** * **yellow** * **grey** / **brightBlack** * **brightRed** * **brightGreen** * **brightYellow** * **brightBlue** * **brightMagenta** * **brightCyan** * **brightWhite** * Background Colors: * **bgWhite** * **bgBlack** * **bgBlue** * **bgCyan** * **bgGreen** * **bgMagenta** * **bgRed** * **bgYellow** * **bgGrey** / **bgBrightBlack** * **bgBrightRed** * **bgBrightGreen** * **bgBrightYellow** * **bgBrightBlue** * **bgBrightMagenta** * **bgBrightCyan** * **bgBrightWhite** # safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) # ajv-errors Custom error messages in JSON-Schema for Ajv validator [![Build Status](https://travis-ci.org/epoberezkin/ajv-errors.svg?branch=master)](https://travis-ci.org/epoberezkin/ajv-errors) [![npm version](https://badge.fury.io/js/ajv-errors.svg)](http://badge.fury.io/js/ajv-errors) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/ajv-errors/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/ajv-errors?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) ## Contents - [Install](#install) - [Usage](#usage) - [Single message](#single-message) - [Messages for keywords](#messages-for-keywords) - [Messages for properties and items](#messages-for-properties-and-items) - [Default message](#default-message) - [Templates](#templates) - [Options](#options) - [License](#license) ## Install ``` npm install ajv-errors ``` ## Usage Add the keyword `errorMessages` to Ajv instance: ```javascript var Ajv = require('ajv'); var ajv = new Ajv({allErrors: true, jsonPointers: true}); // Ajv options allErrors and jsonPointers are required require('ajv-errors')(ajv /*, {singleError: true} */); ``` See [Options](#options) below. ### Single message Replace all errors in the current schema and subschemas with a single message: ```javascript var schema = { type: 'object', required: ['foo'], properties: { foo: { type: 'integer' } }, additionalProperties: false, errorMessage: 'should be an object with an integer property foo only' }; var validate = ajv.compile(schema); console.log(validate({foo: 'a', bar: 2})); // false console.log(validate.errors); // processed errors ``` Processed errors: ```javascript [ { keyword: 'errorMessage', message: 'should be an object with an integer property foo only', // ... params: { errors: [ { keyword: 'additionalProperties', dataPath: '' /* , ... */ }, { keyword: 'type', dataPath: '.foo' /* , ... */ } ] } } ] ``` ### Messages for keywords Replace errors for certain keywords in the current schema only: ```javascript var schema = { type: 'object', required: ['foo'], properties: { foo: { type: 'integer' } }, additionalProperties: false, errorMessage: { type: 'should be an object', // will not replace internal "type" error for the property "foo" required: 'should have property foo', additionalProperties: 'should not have properties other than foo' } }; var validate = ajv.compile(schema); console.log(validate({foo: 'a', bar: 2})); // false console.log(validate.errors); // processed errors ``` Processed errors: ```javascript [ { // original error keyword: type, dataPath: '/foo', // ... message: 'should be integer' }, { // generated error keyword: 'errorMessage', message: 'should not have properties other than foo', // ... params: { errors: [ { keyword: 'additionalProperties' /* , ... */ } ] }, } ] ``` For keywords "required" and "dependencies" it is possible to specify different messages for different properties: ```javascript var schema = { type: 'object', required: ['foo', 'bar'], properties: { foo: { type: 'integer' }, bar: { type: 'string' } }, errorMessage: { type: 'should be an object', // will not replace internal "type" error for the property "foo" required: { foo: 'should have an integer property "foo"', bar: 'should have a string property "bar"' } } }; ``` ### Messages for properties and items Replace errors for properties / items (and deeper), regardless where in schema they were created: ```javascript var schema = { type: 'object', required: ['foo', 'bar'], allOf: [{ properties: { foo: { type: 'integer', minimum: 2 }, bar: { type: 'string', minLength: 2 } }, additionalProperties: false }], errorMessage: { properties: { foo: 'data.foo should be integer >= 2', bar: 'data.bar should be string with length >= 2' } } }; var validate = ajv.compile(schema); console.log(validate({foo: 1, bar: 'a'})); // false console.log(validate.errors); // processed errors ``` Processed errors: ```javascript [ { keyword: 'errorMessage', message: 'data.foo should be integer >= 2', dataPath: '/foo', // ... params: { errors: [ { keyword: 'minimum' /* , ... */ } ] }, }, { keyword: 'errorMessage', message: 'data.bar should be string with length >= 2', dataPath: '/bar', // ... params: { errors: [ { keyword: 'minLength' /* , ... */ } ] }, } ] ``` ### Default message When the value of keyword `errorMessage` is an object you can specify a message that will be used if any error appears that is not specified by keywords/properties/items: ```javascript var schema = { type: 'object', required: ['foo', 'bar'], allOf: [{ properties: { foo: { type: 'integer', minimum: 2 }, bar: { type: 'string', minLength: 2 } }, additionalProperties: false }], errorMessage: { type: 'data should be an object', properties: { foo: 'data.foo should be integer >= 2', bar: 'data.bar should be string with length >= 2' }, _: 'data should have properties "foo" and "bar" only' } }; var validate = ajv.compile(schema); console.log(validate({})); // false console.log(validate.errors); // processed errors ``` Processed errors: ```javascript [ { keyword: 'errorMessage', message: 'data should be an object with properties "foo" and "bar" only', dataPath: '', // ... params: { errors: [ { keyword: 'required' /* , ... */ }, { keyword: 'required' /* , ... */ } ] }, } ] ``` The message in property `_` of `errorMessage` replaces the same errors that would have been replaced if `errorMessage` were a string. ## Templates Custom error messages used in `errorMessage` keyword can be templates using [JSON-pointers](https://tools.ietf.org/html/rfc6901) or [relative JSON-pointers](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) to data being validated, in which case the value will be interpolated. Also see [examples](https://gist.github.com/geraintluff/5911303) of relative JSON-pointers. The syntax to interpolate a value is `${<pointer>}`. The values used in messages will be JSON-stringified: - to differentiate between `false` and `"false"`, etc. - to support structured values. Example: ```json { "type": "object", "properties": { "size": { "type": "number", "minimum": 4 } }, "errorMessage": { "properties": { "size": "size should be a number bigger or equal to 4, current value is ${/size}" } } } ``` ## Options Defaults: ```javascript { keepErrors: false, singleError: false } ``` - _keepErrors_: keep original errors. Default is to remove matched errors (they will still be available in `params.errors` property of generated error). If an error was matched and included in the error generated by `errorMessage` keyword it will have property `emUsed: true`. - _singleError_: create one error for all keywords used in `errorMessage` keyword (error messages defined for properties and items are not merged because they have different dataPaths). Multiple error messages are concatenated. Option values: - `false` (default): create multiple errors, one for each message - `true`: create single error, messages are concatenated using `"; "` - non-empty string: this string is used as a separator to concatenate messages ## Supporters [<img src="https://media.licdn.com/mpr/mpr/shrinknp_400_400/AAEAAQAAAAAAAAwEAAAAJDg1YzBlYzFjLTA3YWYtNGEzOS1iMTdjLTQ0MTU1NWZjOGM0ZQ.jpg" width="48" height="48">](https://www.linkedin.com/in/rogerkepler/) [Roger Kepler](https://www.linkedin.com/in/rogerkepler/) ## License [MIT](https://github.com/epoberezkin/ajv-errors/blob/master/LICENSE) # multicast-dns Low level multicast-dns implementation in pure javascript ``` npm install multicast-dns ``` [![build status](http://img.shields.io/travis/mafintosh/multicast-dns.svg?style=flat)](http://travis-ci.org/mafintosh/multicast-dns) ## Usage ``` js var mdns = require('multicast-dns')() mdns.on('response', function(response) { console.log('got a response packet:', response) }) mdns.on('query', function(query) { console.log('got a query packet:', query) }) // lets query for an A record for 'brunhilde.local' mdns.query({ questions:[{ name: 'brunhilde.local', type: 'A' }] }) ``` Running the above (change `brunhilde.local` to `your-own-hostname.local`) will print an echo of the query packet first ``` js got a query packet: { type: 'query', questions: [ { name: 'brunhilde.local', type: 'A', class: 1 } ], answers: [], authorities: [], additionals: [] } ``` And then a response packet ``` js got a response packet: { type: 'response', questions: [], answers: [ { name: 'brunhilde.local', type: 'A', class: 1, ttl: 120, flush: true, data: '192.168.1.5' } ], authorities: [], additionals: [ { name: 'brunhilde.local', type: 'A', class: 1, ttl: 120, flush: true, data: '192.168.1.5' }, { name: 'brunhilde.local', type: 'AAAA', class: 1, ttl: 120, flush: true, data: 'fe80::5ef9:38ff:fe8c:ceaa' } ] } ``` # CLI ``` npm install -g multicast-dns ``` ``` multicast-dns brunhilde.local > 192.168.1.1 ``` # API A packet has the following format ``` js { questions: [{ name:'brunhilde.local', type:'A' }], answers: [{ name:'brunhilde.local', type:'A', ttl:seconds, data:(record type specific data) }], additionals: [ (same format as answers) ], authorities: [ (same format as answers) ] } ``` Currently data from `SRV`, `A`, `PTR`, `TXT`, `AAAA` and `HINFO` records is passed #### `mdns = multicastdns([options])` Creates a new `mdns` instance. Options can contain the following ``` js { multicast: true // use udp multicasting interface: '192.168.0.2' // explicitly specify a network interface. defaults to all port: 5353, // set the udp port ip: '224.0.0.251', // set the udp ip ttl: 255, // set the multicast ttl loopback: true, // receive your own packets reuseAddr: true // set the reuseAddr option when creating the socket (requires node >=0.11.13) } ``` #### `mdns.on('query', (packet, rinfo))` Emitted when a query packet is received. ``` js mdns.on('query', function(query) { if (query.questions[0] && query.questions[0].name === 'brunhilde.local') { mdns.respond(someResponse) // see below } }) ``` #### `mdns.on('response', (packet, rinfo))` Emitted when a response packet is received. The response might not be a response to a query you send as this is the result of someone multicasting a response. #### `mdns.query(packet, [cb])` Send a dns query. The callback will be called when the packet was sent. The following shorthands are equivalent ``` js mdns.query('brunhilde.local', 'A') mdns.query([{name:'brunhilde.local', type:'A'}]) mdns.query({ questions: [{name:'brunhilde.local', type:'A'}] }) ``` #### `mdns.respond(packet, [cb])` Send a dns response. The callback will be called when the packet was sent. ``` js // reply with a SRV and a A record as an answer mdns.respond({ answers: [{ name: 'my-service', type: 'SRV', data: { port:9999, weigth: 0, priority: 10, target: 'my-service.example.com' } }, { name: 'brunhilde.local', type: 'A', ttl: 300, data: '192.168.1.5' }] }) ``` The following shorthands are equivalent ``` js mdns.respond([{name:'brunhilde.local', type:'A', data:'192.158.1.5'}]) mdns.respond({ answers: [{name:'brunhilde.local', type:'A', data:'192.158.1.5'}] }) ``` #### `mdns.destroy()` Destroy the mdns instance. Closes the udp socket. # Development To start hacking on this module you can use this example to get started ``` git clone git://github.com/mafintosh/multicast-dns.git npm install node example.js node cli.js $(hostname).local ``` ## License MIT # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] # webpack-dev-middleware An express-style development middleware for use with [webpack](https://webpack.js.org) bundles and allows for serving of the files emitted from webpack. This should be used for **development only**. Some of the benefits of using this middleware include: - No files are written to disk, rather it handles files in memory - If files changed in watch mode, the middleware delays requests until compiling has completed. - Supports hot module reload (HMR). ## Requirements This module requires a minimum of Node v6.9.0 and Webpack v4.0.0, and must be used with a server that accepts express-style middleware. ## Getting Started First thing's first, install the module: ```console npm install webpack-dev-middleware --save-dev ``` _Note: We do not recommend installing this module globally._ ## Usage ```js const webpack = require('webpack'); const middleware = require('webpack-dev-middleware'); const compiler = webpack({ // webpack options }); const express = require('express'); const app = express(); app.use( middleware(compiler, { // webpack-dev-middleware options }) ); app.listen(3000, () => console.log('Example app listening on port 3000!')); ``` ## Options The middleware accepts an `options` Object. The following is a property reference for the Object. _Note: The `publicPath` property is required, whereas all other options are optional_ ### methods Type: `Array` Default: `[ 'GET' ]` This property allows a user to pass the list of HTTP request methods accepted by the server. ### headers Type: `Object` Default: `undefined` This property allows a user to pass custom HTTP headers on each request. eg. `{ "X-Custom-Header": "yes" }` ### index Type: `String` Default: `undefined` "index.html", // The index path for web server, defaults to "index.html". // If falsy (but not undefined), the server will not respond to requests to the root URL. ### lazy Type: `Boolean` Default: `undefined` This option instructs the module to operate in 'lazy' mode, meaning that it won't recompile when files change, but rather on each request. ### logger Type: `Object` Default: [`webpack-log`](https://github.com/webpack-contrib/webpack-log/blob/master/index.js) In the rare event that a user would like to provide a custom logging interface, this property allows the user to assign one. The module leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme) for creating the [`loglevelnext`](https://github.com/shellscape/loglevelnext#readme) logging management by default. Any custom logger must adhere to the same exports for compatibility. Specifically, all custom loggers must have the following exported methods at a minimum: - `log.trace` - `log.debug` - `log.info` - `log.warn` - `log.error` Please see the documentation for `loglevel` for more information. ### logLevel Type: `String` Default: `'info'` This property defines the level of messages that the module will log. Valid levels include: - `trace` - `debug` - `info` - `warn` - `error` - `silent` Setting a log level means that all other levels below it will be visible in the console. Setting `logLevel: 'silent'` will hide all console output. The module leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme) for logging management, and more information can be found on its page. ### logTime Type: `Boolean` Default: `false` If `true` the log output of the module will be prefixed by a timestamp in the `HH:mm:ss` format. ### mimeTypes Type: `Object` Default: `null` This property allows a user to register custom mime types or extension mappings. eg. `mimeTypes: { 'text/html': [ 'phtml' ] }`. By default node-mime will throw an error if you try to map a type to an extension that is already assigned to another type. Passing `force: true` will suppress this behavior (overriding any previous mapping). eg. `mimeTypes: { typeMap: { 'text/html': [ 'phtml' ] } }, force: true }`. Please see the documentation for [`node-mime`](https://github.com/broofa/node-mime#mimedefinetypemap-force--false) for more information. ### publicPath Type: `String` _Required_ The public path that the middleware is bound to. _Best Practice: use the same `publicPath` defined in your webpack config. For more information about `publicPath`, please see [the webpack documentation](https://webpack.js.org/guides/public-path)._ ### reporter Type: `Object` Default: `undefined` Allows users to provide a custom reporter to handle logging within the module. Please see the [default reporter](/lib/reporter.js) for an example. ### serverSideRender Type: `Boolean` Default: `undefined` Instructs the module to enable or disable the server-side rendering mode. Please see [Server-Side Rendering](#server-side-rendering) for more information. ### stats Type: `Object` Default: `{ context: process.cwd() }` Options for formatting statistics displayed during and after compile. For more information and property details, please see the [webpack documentation](https://webpack.js.org/configuration/stats/#stats). ### watchOptions Type: `Object` Default: `{ aggregateTimeout: 200 }` The module accepts an `Object` containing options for file watching, which is passed directly to the compiler provided. For more information on watch options please see the [webpack documentation](https://webpack.js.org/configuration/watch/#watchoptions) ### writeToDisk Type: `Boolean|Function` Default: `false` If `true`, the option will instruct the module to write files to the configured location on disk as specified in your `webpack` config file. _Setting `writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`, and bundle files accessed through the browser will still be served from memory._ This option provides the same capabilities as the [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls). This option also accepts a `Function` value, which can be used to filter which files are written to disk. The function follows the same premise as [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) in which a return value of `false` _will not_ write the file, and a return value of `true` _will_ write the file to disk. eg. ```js { writeToDisk: (filePath) => { return /superman\.css$/.test(filePath); }; } ``` ### fs Type: `Object` Default: `MemoryFileSystem` Set the default file system which will be used by webpack as primary destination of generated files. Default is set to webpack's default file system: [memory-fs](https://github.com/webpack/memory-fs). This option isn't affected by the [writeToDisk](#writeToDisk) option. **Note:** As of 3.5.x version of the middleware you have to provide `.join()` method to the `fs` instance manually. This can be done simply by using `path.join`: ```js fs.join = path.join; // no need to bind ``` ## API `webpack-dev-middleware` also provides convenience methods that can be use to interact with the middleware at runtime: ### `close(callback)` Instructs a webpack-dev-middleware instance to stop watching for file changes. ### Parameters #### callback Type: `Function` A function executed once the middleware has stopped watching. ### `invalidate()` Instructs a webpack-dev-middleware instance to recompile the bundle. e.g. after a change to the configuration. ```js const webpack = require('webpack'); const compiler = webpack({ ... }); const middleware = require('webpack-dev-middleware'); const instance = middleware(compiler); app.use(instance); setTimeout(() => { // After a short delay the configuration is changed and a banner plugin is added // to the config compiler.apply(new webpack.BannerPlugin('A new banner')); // Recompile the bundle with the banner plugin: instance.invalidate(); }, 1000); ``` ### `waitUntilValid(callback)` Executes a callback function when the compiler bundle is valid, typically after compilation. ### Parameters #### callback Type: `Function` A function executed when the bundle becomes valid. If the bundle is valid at the time of calling, the callback is executed immediately. ```js const webpack = require('webpack'); const compiler = webpack({ ... }); const middleware = require('webpack-dev-middleware'); const instance = middleware(compiler); app.use(instance); instance.waitUntilValid(() => { console.log('Package is in a valid state'); }); ``` ## Known Issues ### Multiple Successive Builds Watching (by means of `lazy: false`) will frequently cause multiple compilations as the bundle changes during compilation. This is due in part to cross-platform differences in file watchers, so that webpack doesn't loose file changes when watched files change rapidly. If you run into this situation, please make use of the [`TimeFixPlugin`](https://github.com/egoist/time-fix-plugin). ## Server-Side Rendering _Note: this feature is experimental and may be removed or changed completely in the future._ In order to develop an app using server-side rendering, we need access to the [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is generated with each build. With server-side rendering enabled, `webpack-dev-middleware` sets the `stat` to `res.locals.webpackStats` and the memory filesystem to `res.locals.fs` before invoking the next middleware, allowing a developer to render the page body and manage the response to clients. _Note: Requests for bundle files will still be handled by `webpack-dev-middleware` and all requests will be pending until the build process is finished with server-side rendering enabled._ Example Implementation: ```js const webpack = require('webpack'); const compiler = webpack({ // webpack options }); const isObject = require('is-object'); const middleware = require('webpack-dev-middleware'); // This function makes server rendering of asset references consistent with different webpack chunk/entry configurations function normalizeAssets(assets) { if (isObject(assets)) { return Object.values(assets); } return Array.isArray(assets) ? assets : [assets]; } app.use(middleware(compiler, { serverSideRender: true })); // The following middleware would not be invoked until the latest build is finished. app.use((req, res) => { const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName; const fs = res.locals.fs; const outputPath = res.locals.webpackStats.toJson().outputPath; // then use `assetsByChunkName` for server-sider rendering // For example, if you have only one main chunk: res.send(` <html> <head> <title>My App</title> <style> ${normalizeAssets(assetsByChunkName.main) .filter((path) => path.endsWith('.css')) .map((path) => fs.readFileSync(outputPath + '/' + path)) .join('\n')} </style> </head> <body> <div id="root"></div> ${normalizeAssets(assetsByChunkName.main) .filter((path) => path.endsWith('.js')) .map((path) => `<script src="${path}"></script>`) .join('\n')} </body> </html> `); }); ``` ## Support We do our best to keep Issues in the repository focused on bugs, features, and needed modifications to the code for the module. Because of that, we ask users with general support, "how-to", or "why isn't this working" questions to try one of the other support channels that are available. Your first-stop-shop for support for webpack-dev-server should by the excellent [documentation][docs-url] for the module. If you see an opportunity for improvement of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a pull request. From there, we encourage users to visit the [webpack Gitter chat][chat-url] and talk to the fine folks there. If your quest for answers comes up dry in chat, head over to [StackOverflow][stack-url] and do a quick search or open a new question. Remember; It's always much easier to answer questions that include your `webpack.config.js` and relevant files! If you're twitter-savvy you can tweet [#webpack][hash-url] with your question and someone should be able to reach out and lend a hand. If you have discovered a :bug:, have a feature suggestion, of would like to see a modification, please feel free to create an issue on Github. _Note: The issue template isn't optional, so please be sure not to remove it, and please fill it out completely._ ## Contributing Please take a moment to read our contributing guidelines if you haven't yet done so. [CONTRIBUTING.md](CONTRIBUTING.md) ## License [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg [npm-url]: https://npmjs.com/package/webpack-dev-middleware [node]: https://img.shields.io/node/v/webpack-dev-middleware.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack/webpack-dev-middleware.svg [deps-url]: https://david-dm.org/webpack/webpack-dev-middleware [tests]: http://img.shields.io/travis/webpack/webpack-dev-middleware.svg [tests-url]: https://travis-ci.org/webpack/webpack-dev-middleware [cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack [docs-url]: https://webpack.js.org/guides/development/#using-webpack-dev-middleware [hash-url]: https://twitter.com/search?q=webpack [middleware-url]: https://github.com/webpack/webpack-dev-middleware [stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-middleware [uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin [wjo-url]: https://github.com/webpack/webpack.js.org # to-regex [![NPM version](https://img.shields.io/npm/v/to-regex.svg?style=flat)](https://www.npmjs.com/package/to-regex) [![NPM monthly downloads](https://img.shields.io/npm/dm/to-regex.svg?style=flat)](https://npmjs.org/package/to-regex) [![NPM total downloads](https://img.shields.io/npm/dt/to-regex.svg?style=flat)](https://npmjs.org/package/to-regex) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/to-regex.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/to-regex) > Generate a regex from a string or array of strings. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. - [Install](#install) - [Usage](#usage) - [Options](#options) * [options.contains](#optionscontains) * [options.negate](#optionsnegate) * [options.nocase](#optionsnocase) * [options.flags](#optionsflags) * [options.cache](#optionscache) * [options.safe](#optionssafe) - [About](#about) * [Related projects](#related-projects) * [Author](#author) * [License](#license) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save to-regex ``` ## Usage ```js var toRegex = require('to-regex'); console.log(toRegex('foo')); //=> /^(?:foo)$/ console.log(toRegex('foo', {negate: true})); //=> /^(?:(?:(?!^(?:foo)$).)*)$/ console.log(toRegex('foo', {contains: true})); //=> /(?:foo)/ console.log(toRegex(['foo', 'bar'], {negate: true})); //=> /^(?:(?:(?!^(?:(?:foo)|(?:bar))$).)*)$/ console.log(toRegex(['foo', 'bar'], {negate: true, contains: true})); //=> /^(?:(?:(?!(?:(?:foo)|(?:bar))).)*)$/ ``` ## Options ### options.contains **Type**: `Boolean` **Default**: `undefined` Generate a regex that will match any string that _contains_ the given pattern. By default, regex is strict will only return true for exact matches. ```js var toRegex = require('to-regex'); console.log(toRegex('foo', {contains: true})); //=> /(?:foo)/ ``` ### options.negate **Type**: `Boolean` **Default**: `undefined` Create a regex that will match everything except the given pattern. ```js var toRegex = require('to-regex'); console.log(toRegex('foo', {negate: true})); //=> /^(?:(?:(?!^(?:foo)$).)*)$/ ``` ### options.nocase **Type**: `Boolean` **Default**: `undefined` Adds the `i` flag, to enable case-insensitive matching. ```js var toRegex = require('to-regex'); console.log(toRegex('foo', {nocase: true})); //=> /^(?:foo)$/i ``` Alternatively you can pass the flags you want directly on [options.flags](#options.flags). ### options.flags **Type**: `String` **Default**: `undefined` Define the flags you want to use on the generated regex. ```js var toRegex = require('to-regex'); console.log(toRegex('foo', {flags: 'gm'})); //=> /^(?:foo)$/gm console.log(toRegex('foo', {flags: 'gmi', nocase: true})); //<= handles redundancy //=> /^(?:foo)$/gmi ``` ### options.cache **Type**: `Boolean` **Default**: `true` Generated regex is cached based on the provided string and options. As a result, runtime compilation only happens once per pattern (as long as options are also the same), which can result in dramatic speed improvements. This also helps with debugging, since adding options and pattern are added to the generated regex. **Disable caching** ```js toRegex('foo', {cache: false}); ``` ### options.safe **Type**: `Boolean` **Default**: `undefined` Check the generated regular expression with [safe-regex](https://github.com/substack/safe-regex) and throw an error if the regex is potentially unsafe. **Examples** ```js console.log(toRegex('(x+x+)+y')); //=> /^(?:(x+x+)+y)$/ // The following would throw an error toRegex('(x+x+)+y', {safe: true}); ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [path-regex](https://www.npmjs.com/package/path-regex): Regular expression for matching the parts of a file path. | [homepage](https://github.com/regexps/path-regex "Regular expression for matching the parts of a file path.") * [to-regex-range](https://www.npmjs.com/package/to-regex-range): Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than… [more](https://github.com/micromatch/to-regex-range) | [homepage](https://github.com/micromatch/to-regex-range "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.78 million test assertions.") ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 24, 2018._ # y18n [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![NPM version][npm-image]][npm-url] [![js-standard-style][standard-image]][standard-url] The bare-bones internationalization library used by yargs. Inspired by [i18n](https://www.npmjs.com/package/i18n). ## Examples _simple string translation:_ ```js var __ = require('y18n').__ console.log(__('my awesome string %s', 'foo')) ``` output: `my awesome string foo` _pluralization support:_ ```js var __n = require('y18n').__n console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) ``` output: `2 fishes foo` ## JSON Language Files The JSON language files should be stored in a `./locales` folder. File names correspond to locales, e.g., `en.json`, `pirate.json`. When strings are observed for the first time they will be added to the JSON file corresponding to the current locale. ## Methods ### require('y18n')(config) Create an instance of y18n with the config provided, options include: * `directory`: the locale directory, default `./locales`. * `updateFiles`: should newly observed strings be updated in file, default `true`. * `locale`: what locale should be used. * `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) be allowed if a file matching the locale does not exist (e.g. `en_US.json`), default `true`. ### y18n.\_\_(str, arg, arg, arg) Print a localized string, `%s` will be replaced with `arg`s. ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided in the string, the `count` will replace this placeholder. ### y18n.setLocale(str) Set the current locale being used. ### y18n.getLocale() What locale is currently being used? ### y18n.updateLocale(obj) Update the current locale with the key value pairs in `obj`. ## License ISC [travis-url]: https://travis-ci.org/yargs/y18n [travis-image]: https://img.shields.io/travis/yargs/y18n.svg [coveralls-url]: https://coveralls.io/github/yargs/y18n [coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg [npm-url]: https://npmjs.org/package/y18n [npm-image]: https://img.shields.io/npm/v/y18n.svg [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg [standard-url]: https://github.com/feross/standard This folder contains internal parts of `core-js` like helpers. # block-stream A stream of blocks. Write data into it, and it'll output data in buffer blocks the size you specify, padding with zeroes if necessary. ```javascript var block = new BlockStream(512) fs.createReadStream("some-file").pipe(block) block.pipe(fs.createWriteStream("block-file")) ``` When `.end()` or `.flush()` is called, it'll pad the block with zeroes. # util [![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util) > Node.js's [util][util] module for all engines. This implements the Node.js [`util`][util] module for environments that do not have it, like browsers. ## Install You usually do not have to install `util` yourself. If your code runs in Node.js, `util` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `util` module. But if none of those apply, with npm do: ```shell npm install util ``` ## Usage ```javascript var util = require('util') var EventEmitter = require('events') function MyClass() { EventEmitter.call(this) } util.inherits(MyClass, EventEmitter) ``` ## Browser Support The `util` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`. To use `util.promisify` and `util.callbackify`, Promises must already be available. If you need to support browsers like IE11 that do not support Promises, use a shim. [es6-promise](https://github.com/stefanpenner/es6-promise) is a popular one but there are many others available on npm. ## API See the [Node.js util docs][util]. `util` currently supports the Node 8 LTS API. However, some of the methods are outdated. The `inspect` and `format` methods included in this module are a lot more simple and barebones than the ones in Node.js. ## Contributing PRs are very welcome! The main way to contribute to `util` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js. This module intends to provide exactly the same API as Node.js, so features that are not available in the core `util` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js. If there is a difference in behaviour between Node.js's `util` module and this module, please open an issue! ## License [MIT](./LICENSE) [util]: https://nodejs.org/docs/latest-v8.x/api/util.html # expand-tilde [![NPM version](https://img.shields.io/npm/v/expand-tilde.svg?style=flat)](https://www.npmjs.com/package/expand-tilde) [![NPM downloads](https://img.shields.io/npm/dm/expand-tilde.svg?style=flat)](https://npmjs.org/package/expand-tilde) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/expand-tilde.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/expand-tilde) > Bash-like tilde expansion for node.js. Expands a leading tilde in a file path to the user home directory, or `~+` to the cwd. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save expand-tilde ``` ## Usage See the [Bash documentation for Tilde Expansion](https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html). ```js var expandTilde = require('expand-tilde'); expandTilde('~') //=> '/Users/jonschlinkert' expandTilde('~+') //=> process.cwd() ``` ## Run tests Install dev dependencies: ```bash npm i -d && npm test ``` ## About ### Related projects * [braces](https://www.npmjs.com/package/braces): Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on December 08, 2016._ # pumpify Combine an array of streams into a single duplex stream using [pump](https://github.com/mafintosh/pump) and [duplexify](https://github.com/mafintosh/duplexify). If one of the streams closes/errors all streams in the pipeline will be destroyed. ``` npm install pumpify ``` [![build status](http://img.shields.io/travis/mafintosh/pumpify.svg?style=flat)](http://travis-ci.org/mafintosh/pumpify) ## Usage Pass the streams you want to pipe together to pumpify `pipeline = pumpify(s1, s2, s3, ...)`. `pipeline` is a duplex stream that writes to the first streams and reads from the last one. Streams are piped together using [pump](https://github.com/mafintosh/pump) so if one of them closes all streams will be destroyed. ``` js var pumpify = require('pumpify') var tar = require('tar-fs') var zlib = require('zlib') var fs = require('fs') var untar = pumpify(zlib.createGunzip(), tar.extract('output-folder')) // you can also pass an array instead // var untar = pumpify([zlib.createGunzip(), tar.extract('output-folder')]) fs.createReadStream('some-gzipped-tarball.tgz').pipe(untar) ``` If you are pumping object streams together use `pipeline = pumpify.obj(s1, s2, ...)`. Call `pipeline.destroy()` to destroy the pipeline (including the streams passed to pumpify). ### Using `setPipeline(s1, s2, ...)` Similar to [duplexify](https://github.com/mafintosh/duplexify) you can also define the pipeline asynchronously using `setPipeline(s1, s2, ...)` ``` js var untar = pumpify() setTimeout(function() { // will start draining the input now untar.setPipeline(zlib.createGunzip(), tar.extract('output-folder')) }, 1000) fs.createReadStream('some-gzipped-tarball.tgz').pipe(untar) ``` ## License MIT ## Related `pumpify` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # qs <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] A querystring parsing and stringifying library with some added security. Lead Maintainer: [Jordan Harband](https://github.com/ljharb) The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). ## Usage ```javascript var qs = require('qs'); var assert = require('assert'); var obj = qs.parse('a=c'); assert.deepEqual(obj, { a: 'c' }); var str = qs.stringify(obj); assert.equal(str, 'a=c'); ``` ### Parsing Objects [](#preventEval) ```javascript qs.parse(string, [options]); ``` **qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. For example, the string `'foo[bar]=baz'` converts to: ```javascript assert.deepEqual(qs.parse('foo[bar]=baz'), { foo: { bar: 'baz' } }); ``` When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: ```javascript var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); ``` By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. ```javascript var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); ``` URI encoded strings work too: ```javascript assert.deepEqual(qs.parse('a%5Bb%5D=c'), { a: { b: 'c' } }); ``` You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: ```javascript assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { foo: { bar: { baz: 'foobarbaz' } } }); ``` By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: ```javascript var expected = { a: { b: { c: { d: { e: { f: { '[g][h][i]': 'j' } } } } } } }; var string = 'a[b][c][d][e][f][g][h][i]=j'; assert.deepEqual(qs.parse(string), expected); ``` This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: ```javascript var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); ``` The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: ```javascript var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); assert.deepEqual(limited, { a: 'b' }); ``` To bypass the leading question mark, use `ignoreQueryPrefix`: ```javascript var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); assert.deepEqual(prefixed, { a: 'b', c: 'd' }); ``` An optional delimiter can also be passed: ```javascript var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); assert.deepEqual(delimited, { a: 'b', c: 'd' }); ``` Delimiters can be a regular expression too: ```javascript var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); ``` Option `allowDots` can be used to enable dot notation: ```javascript var withDots = qs.parse('a.b=c', { allowDots: true }); assert.deepEqual(withDots, { a: { b: 'c' } }); ``` ### Parsing Arrays **qs** can also parse arrays using a similar `[]` notation: ```javascript var withArray = qs.parse('a[]=b&a[]=c'); assert.deepEqual(withArray, { a: ['b', 'c'] }); ``` You may specify an index as well: ```javascript var withIndexes = qs.parse('a[1]=c&a[0]=b'); assert.deepEqual(withIndexes, { a: ['b', 'c'] }); ``` Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving their order: ```javascript var noSparse = qs.parse('a[1]=b&a[15]=c'); assert.deepEqual(noSparse, { a: ['b', 'c'] }); ``` Note that an empty string is also a value, and will be preserved: ```javascript var withEmptyString = qs.parse('a[]=&a[]=b'); assert.deepEqual(withEmptyString, { a: ['', 'b'] }); var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); ``` **qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will instead be converted to an object with the index as the key: ```javascript var withMaxIndex = qs.parse('a[100]=b'); assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); ``` This limit can be overridden by passing an `arrayLimit` option: ```javascript var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); ``` To disable array parsing entirely, set `parseArrays` to `false`. ```javascript var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); ``` If you mix notations, **qs** will merge the two items into an object: ```javascript var mixedNotation = qs.parse('a[0]=b&a[b]=c'); assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); ``` You can also create arrays of objects: ```javascript var arraysOfObjects = qs.parse('a[][b]=c'); assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); ``` ### Stringifying [](#preventEval) ```javascript qs.stringify(object, [options]); ``` When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: ```javascript assert.equal(qs.stringify({ a: 'b' }), 'a=b'); assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); ``` This encoding can be disabled by setting the `encode` option to `false`: ```javascript var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); assert.equal(unencoded, 'a[b]=c'); ``` Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: ```javascript var encodedValues = qs.stringify( { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, { encodeValuesOnly: true } ); assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); ``` This encoding can also be replaced by a custom encoding method set as `encoder` option: ```javascript var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { // Passed in values `a`, `b`, `c` return // Return encoded string }}) ``` _(Note: the `encoder` option does not apply if `encode` is `false`)_ Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: ```javascript var decoded = qs.parse('x=z', { decoder: function (str) { // Passed in values `x`, `z` return // Return decoded string }}) ``` Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. When arrays are stringified, by default they are given explicit indices: ```javascript qs.stringify({ a: ['b', 'c', 'd'] }); // 'a[0]=b&a[1]=c&a[2]=d' ``` You may override this by setting the `indices` option to `false`: ```javascript qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); // 'a=b&a=c&a=d' ``` You may use the `arrayFormat` option to specify the format of the output array: ```javascript qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) // 'a[0]=b&a[1]=c' qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) // 'a[]=b&a[]=c' qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) // 'a=b&a=c' ``` When objects are stringified, by default they use bracket notation: ```javascript qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); // 'a[b][c]=d&a[b][e]=f' ``` You may override this to use dot notation by setting the `allowDots` option to `true`: ```javascript qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); // 'a.b.c=d&a.b.e=f' ``` Empty strings and null values will omit the value, but the equals sign (=) remains in place: ```javascript assert.equal(qs.stringify({ a: '' }), 'a='); ``` Key with no values (such as an empty object or array) will return nothing: ```javascript assert.equal(qs.stringify({ a: [] }), ''); assert.equal(qs.stringify({ a: {} }), ''); assert.equal(qs.stringify({ a: [{}] }), ''); assert.equal(qs.stringify({ a: { b: []} }), ''); assert.equal(qs.stringify({ a: { b: {}} }), ''); ``` Properties that are set to `undefined` will be omitted entirely: ```javascript assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); ``` The query string may optionally be prepended with a question mark: ```javascript assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); ``` The delimiter may be overridden with stringify as well: ```javascript assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); ``` If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: ```javascript var date = new Date(7); assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); assert.equal( qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), 'a=7' ); ``` You may use the `sort` option to affect the order of parameter keys: ```javascript function alphabeticalSort(a, b) { return a.localeCompare(b); } assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); ``` Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you pass an array, it will be used to select properties and array indices for stringification: ```javascript function filterFunc(prefix, value) { if (prefix == 'b') { // Return an `undefined` value to omit a property. return; } if (prefix == 'e[f]') { return value.getTime(); } if (prefix == 'e[g][0]') { return value * 2; } return value; } qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); // 'a=b&c=d&e[f]=123&e[g][0]=4' qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); // 'a=b&e=f' qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); // 'a[0]=b&a[2]=d' ``` ### Handling of `null` values By default, `null` values are treated like empty strings: ```javascript var withNull = qs.stringify({ a: null, b: '' }); assert.equal(withNull, 'a=&b='); ``` Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. ```javascript var equalsInsensitive = qs.parse('a&b='); assert.deepEqual(equalsInsensitive, { a: '', b: '' }); ``` To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` values have no `=` sign: ```javascript var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); assert.equal(strictNull, 'a&b='); ``` To parse values without `=` back to `null` use the `strictNullHandling` flag: ```javascript var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); assert.deepEqual(parsedStrictNull, { a: null, b: '' }); ``` To completely skip rendering keys with `null` values, use the `skipNulls` flag: ```javascript var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); assert.equal(nullsSkipped, 'a=b'); ``` ### Dealing with special character sets By default the encoding and decoding of characters is done in `utf-8`. If you wish to encode querystrings to a different character set (i.e. [Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the [`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: ```javascript var encoder = require('qs-iconv/encoder')('shift_jis'); var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); ``` This also works for decoding of query strings: ```javascript var decoder = require('qs-iconv/decoder')('shift_jis'); var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); assert.deepEqual(obj, { a: 'こんにちは!' }); ``` ### RFC 3986 and RFC 1738 space encoding RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. ``` assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); ``` [1]: https://npmjs.org/package/qs [2]: http://versionbadg.es/ljharb/qs.svg [3]: https://api.travis-ci.org/ljharb/qs.svg [4]: https://travis-ci.org/ljharb/qs [5]: https://david-dm.org/ljharb/qs.svg [6]: https://david-dm.org/ljharb/qs [7]: https://david-dm.org/ljharb/qs/dev-status.svg [8]: https://david-dm.org/ljharb/qs?type=dev [9]: https://ci.testling.com/ljharb/qs.png [10]: https://ci.testling.com/ljharb/qs [11]: https://nodei.co/npm/qs.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/qs.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/qs.svg [downloads-url]: http://npm-stat.com/charts.html?package=qs # is-data-descriptor [![NPM version](https://img.shields.io/npm/v/is-data-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-data-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-data-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-data-descriptor) > Returns true if a value has the characteristics of a valid JavaScript data descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-data-descriptor ``` ## Usage ```js var isDataDesc = require('is-data-descriptor'); ``` ## Examples `true` when the descriptor has valid properties with valid values. ```js // `value` can be anything isDataDesc({value: 'foo'}) isDataDesc({value: function() {}}) isDataDesc({value: true}) //=> true ``` `false` when not an object ```js isDataDesc('a') //=> false isDataDesc(null) //=> false isDataDesc([]) //=> false ``` `false` when the object has invalid properties ```js isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', get: function(){}}) //=> false isDataDesc({get: function(){}, value: 'foo'}) //=> false ``` `false` when a value is not the correct type ```js isDataDesc({value: 'foo', enumerable: 'foo'}) //=> false isDataDesc({value: 'foo', configurable: 'foo'}) //=> false isDataDesc({value: 'foo', writable: 'foo'}) //=> false ``` ## Valid properties The only valid data descriptor properties are the following: * `configurable` (required) * `enumerable` (required) * `value` (optional) * `writable` (optional) To be a valid data descriptor, either `value` or `writable` must be defined. **Invalid properties** A descriptor may have additional _invalid_ properties (an error will **not** be thrown). ```js var foo = {}; Object.defineProperty(foo, 'bar', { enumerable: true, whatever: 'blah', // invalid, but doesn't cause an error get: function() { return 'baz'; } }); console.log(foo.bar); //=> 'baz' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 21 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # has-value [![NPM version](https://img.shields.io/npm/v/has-value.svg?style=flat)](https://www.npmjs.com/package/has-value) [![NPM monthly downloads](https://img.shields.io/npm/dm/has-value.svg?style=flat)](https://npmjs.org/package/has-value) [![NPM total downloads](https://img.shields.io/npm/dt/has-value.svg?style=flat)](https://npmjs.org/package/has-value) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/has-value.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/has-value) > Returns true if a value exists, false if empty. Works with deeply nested values using object paths. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save has-value ``` **Works for:** * booleans * functions * numbers * strings * nulls * object * arrays ## Usage Works with property values (supports object-path notation, like `foo.bar`) or a single value: ```js var hasValue = require('has-value'); hasValue('foo'); hasValue({foo: 'bar'}, 'foo'); hasValue({a: {b: {c: 'foo'}}}, 'a.b.c'); //=> true hasValue(''); hasValue({foo: ''}, 'foo'); //=> false hasValue(0); hasValue(1); hasValue({foo: 0}, 'foo'); hasValue({foo: 1}, 'foo'); hasValue({foo: null}, 'foo'); hasValue({foo: {bar: 'a'}}}, 'foo'); hasValue({foo: {bar: 'a'}}}, 'foo.bar'); //=> true hasValue({foo: {}}}, 'foo'); hasValue({foo: {bar: {}}}}, 'foo.bar'); hasValue({foo: undefined}, 'foo'); //=> false hasValue([]); hasValue([[]]); hasValue([[], []]); hasValue([undefined]); hasValue({foo: []}, 'foo'); //=> false hasValue([0]); hasValue([null]); hasValue(['foo']); hasValue({foo: ['a']}, 'foo'); //=> true hasValue(function() {}) hasValue(function(foo) {}) hasValue({foo: function(foo) {}}, 'foo'); hasValue({foo: function() {}}, 'foo'); //=> true hasValue(true); hasValue(false); hasValue({foo: true}, 'foo'); hasValue({foo: false}, 'foo'); //=> true ``` ## isEmpty To do the opposite and test for empty values, do: ```js function isEmpty(o) { return !hasValue.apply(hasValue, arguments); } ``` ## Release history ### v1.0.0 * `zero` always returns true * `array` now recurses, so that an array of empty arrays will return `false` * `null` now returns true ## About ### Related projects * [define-property](https://www.npmjs.com/package/define-property): Define a non-enumerable property on an object. | [homepage](https://github.com/jonschlinkert/define-property "Define a non-enumerable property on an object.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value "Delete nested properties from an object using dot notation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 17 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [rmharrison](https://github.com/rmharrison) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 19, 2017._ # map-cache [![NPM version](https://img.shields.io/npm/v/map-cache.svg?style=flat)](https://www.npmjs.com/package/map-cache) [![NPM downloads](https://img.shields.io/npm/dm/map-cache.svg?style=flat)](https://npmjs.org/package/map-cache) [![Build Status](https://img.shields.io/travis/jonschlinkert/map-cache.svg?style=flat)](https://travis-ci.org/jonschlinkert/map-cache) Basic cache object for storing key-value pairs. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install map-cache --save ``` Based on MapCache in Lo-dash v3.0. [MIT License](https://github.com/lodash/lodash/blob/master/LICENSE.txt) ## Usage ```js var MapCache = require('map-cache'); var mapCache = new MapCache(); ``` ## API ### [MapCache](index.js#L28) Creates a cache object to store key/value pairs. **Example** ```js var cache = new MapCache(); ``` ### [.set](index.js#L45) Adds `value` to `key` on the cache. **Params** * `key` **{String}**: The key of the value to cache. * `value` **{any}**: The value to cache. * `returns` **{Object}**: Returns the `Cache` object for chaining. **Example** ```js cache.set('foo', 'bar'); ``` ### [.get](index.js#L65) Gets the cached value for `key`. **Params** * `key` **{String}**: The key of the value to get. * `returns` **{any}**: Returns the cached value. **Example** ```js cache.get('foo'); //=> 'bar' ``` ### [.has](index.js#L82) Checks if a cached value for `key` exists. **Params** * `key` **{String}**: The key of the entry to check. * `returns` **{Boolean}**: Returns `true` if an entry for `key` exists, else `false`. **Example** ```js cache.has('foo'); //=> true ``` ### [.del](index.js#L98) Removes `key` and its value from the cache. **Params** * `key` **{String}**: The key of the value to remove. * `returns` **{Boolean}**: Returns `true` if the entry was removed successfully, else `false`. **Example** ```js cache.del('foo'); ``` ## Related projects You might also be interested in these projects: * [cache-base](https://www.npmjs.com/package/cache-base): Basic object cache with `get`, `set`, `del`, and `has` methods for node.js/javascript projects. | [homepage](https://github.com/jonschlinkert/cache-base) * [config-cache](https://www.npmjs.com/package/config-cache): General purpose JavaScript object storage methods. | [homepage](https://github.com/jonschlinkert/config-cache) * [option-cache](https://www.npmjs.com/package/option-cache): Simple API for managing options in JavaScript applications. | [homepage](https://github.com/jonschlinkert/option-cache) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/map-cache/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/map-cache/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on May 10, 2016._ # define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i define-property --save ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## Related projects * [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object) * [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._ [RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js [![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) [![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie) # Synopsis ``` javascript var tough = require('tough-cookie'); var Cookie = tough.Cookie; var cookie = Cookie.parse(header); cookie.value = 'somethingdifferent'; header = cookie.toString(); var cookiejar = new tough.CookieJar(); cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); // ... cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { res.headers['cookie'] = cookies.join('; '); }); ``` # Installation It's _so_ easy! `npm install tough-cookie` Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. ## Version Support Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. # API ## tough Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". **Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. ### `parseDate(string)` Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. ### `formatDate(date)` Format a Date into a RFC1123 string (the RFC6265-recommended format). ### `canonicalDomain(str)` Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). ### `domainMatch(str,domStr[,canonicalize=true])` Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. ### `defaultPath(path)` Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. ### `pathMatch(reqPath,cookiePath)` Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. ### `parse(cookieString[, options])` alias for `Cookie.parse(cookieString[, options])` ### `fromJSON(string)` alias for `Cookie.fromJSON(string)` ### `getPublicSuffix(hostname)` Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). ### `cookieCompare(a,b)` For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: * Longest `.path` * oldest `.creation` (which has a 1ms precision, same as `Date`) * lowest `.creationIndex` (to get beyond the 1ms precision) ``` javascript var cookies = [ /* unsorted array of Cookie objects */ ]; cookies = cookies.sort(cookieCompare); ``` **Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. ### `permuteDomain(domain)` Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. ### `permutePath(path)` Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. ## Cookie Exported via `tough.Cookie`. ### `Cookie.parse(cookieString[, options])` Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. The options parameter is not required and currently has only one property: * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. If options is not an object, it is ignored, which means you can use `Array#map` with it. Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: ``` javascript if (res.headers['set-cookie'] instanceof Array) cookies = res.headers['set-cookie'].map(Cookie.parse); else cookies = [Cookie.parse(res.headers['set-cookie'])]; ``` _Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) ### Properties Cookie object properties: * _key_ - string - the name or key of the cookie (default "") * _value_ - string - the value of the cookie (default "") * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` * _domain_ - string - the `Domain=` attribute of the cookie * _path_ - string - the `Path=` of the cookie * _secure_ - boolean - the `Secure` cookie flag * _httpOnly_ - boolean - the `HttpOnly` cookie flag * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) * _creation_ - `Date` - when this cookie was constructed * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. ### `Cookie([{properties}])` Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. ### `.toString()` encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. ### `.cookieString()` encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). ### `.setExpires(String)` sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. ### `.setMaxAge(number)` sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. ### `.expiryTime([now=Date.now()])` ### `.expiryDate([now=Date.now()])` expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. If Expires (`.expires`) is set, that's returned. Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). ### `.TTL([now=Date.now()])` compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. ### `.canonicalizedDoman()` ### `.cdomain()` return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. ### `.toJSON()` For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). **NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. ### `Cookie.fromJSON(strOrObj)` Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. Returns `null` upon JSON parsing error. ### `.clone()` Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. ### `.validate()` Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: ``` javascript if (cookie.validate() === true) { // it's tasty } else { // yuck! } ``` ## CookieJar Exported via `tough.CookieJar`. ### `CookieJar([store],[options])` Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. The `options` object can be omitted and can have the following properties: * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. ### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). ### `.setCookieSync(cookieOrString, currentUrl, [{options}])` Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookies(currentUrl, [{options},] cb(err,cookies))` Retrieve the list of cookies that can be sent in a Cookie header for the current url. If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). The `.lastAccessed` property of the returned cookies will have been updated. ### `.getCookiesSync(currentUrl, [{options}])` Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookieString(...)` Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. ### `.getCookieStringSync(...)` Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getSetCookieStrings(...)` Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. ### `.getSetCookieStringsSync(...)` Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.serialize(cb(err,serializedObject))` Serialize the Jar if the underlying store supports `.getAllCookies`. **NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. See [Serialization Format]. ### `.serializeSync()` Sync version of .serialize ### `.toJSON()` Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. ### `CookieJar.deserialize(serialized, [store], cb(err,object))` A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. ### `CookieJar.deserializeSync(serialized, [store])` Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. ### `CookieJar.fromJSON(string)` Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. ### `.clone([store,]cb(err,newJar))` Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. ### `.cloneSync([store])` Synchronous version of `.clone`, returning a new `CookieJar` instance. The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. ## Store Base class for CookieJar stores. Available as `tough.Store`. ## Store API The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style All `domain` parameters will have been normalized before calling. The Cookie store must have all of the following methods. ### `store.findCookie(domain, path, key, cb(err,cookie))` Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). ### `store.findCookies(domain, path, cb(err,cookies))` Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. If no cookies are found, the callback MUST be passed an empty array. The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). ### `store.putCookie(cookie, cb(err))` Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. Pass an error if the cookie cannot be stored. ### `store.updateCookie(oldCookie, newCookie, cb(err))` Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. The `newCookie` and `oldCookie` objects MUST NOT be modified. Pass an error if the newCookie cannot be stored. ### `store.removeCookie(domain, path, key, cb(err))` Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. ### `store.removeCookies(domain, path, cb(err))` Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. Pass an error ONLY if removing any existing cookies failed. ### `store.getAllCookies(cb(err, cookies))` Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. Pass an error if retrieval fails. ## MemoryCookieStore Inherits from `Store`. A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. ## Community Cookie Stores These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: - [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases - [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk - [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis - [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk - [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage # Serialization Format **NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. ```js { // The version of tough-cookie that serialized this jar. version: '[email protected]', // add the store type, to make humans happy: storeType: 'MemoryCookieStore', // CookieJar configuration: rejectPublicSuffixes: true, // ... future items go here // Gets filled from jar.store.getAllCookies(): cookies: [ { key: 'string', value: 'string', // ... /* other Cookie.serializableProperties go here */ } ] } ``` # Copyright and License (tl;dr: BSD-3-Clause with some MPL/2.0) ```text Copyright (c) 2015, Salesforce.com, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ``` gauge ===== A nearly stateless terminal based horizontal gauge / progress bar. ```javascript var Gauge = require("gauge") var gauge = new Gauge() gauge.show("test", 0.20) gauge.pulse("this") gauge.hide() ``` ![](gauge-demo.gif) ### CHANGES FROM 1.x Gauge 2.x is breaking release, please see the [changelog] for details on what's changed if you were previously a user of this module. [changelog]: CHANGELOG.md ### THE GAUGE CLASS This is the typical interface to the module– it provides a pretty fire-and-forget interface to displaying your status information. ``` var Gauge = require("gauge") var gauge = new Gauge([stream], [options]) ``` * **stream** – *(optional, default STDERR)* A stream that progress bar updates are to be written to. Gauge honors backpressure and will pause most writing if it is indicated. * **options** – *(optional)* An option object. Constructs a new gauge. Gauges are drawn on a single line, and are not drawn if **stream** isn't a tty and a tty isn't explicitly provided. If **stream** is a terminal or if you pass in **tty** to **options** then we will detect terminal resizes and redraw to fit. We do this by watching for `resize` events on the tty. (To work around a bug in verisons of Node prior to 2.5.0, we watch for them on stdout if the tty is stderr.) Resizes to larger window sizes will be clean, but shrinking the window will always result in some cruft. **IMPORTANT:** If you prevously were passing in a non-tty stream but you still want output (for example, a stream wrapped by the `ansi` module) then you need to pass in the **tty** option below, as `gauge` needs access to the underlying tty in order to do things like terminal resizes and terminal width detection. The **options** object can have the following properties, all of which are optional: * **updateInterval**: How often gauge updates should be drawn, in miliseconds. * **fixedFramerate**: Defaults to false on node 0.8, true on everything else. When this is true a timer is created to trigger once every `updateInterval` ms, when false, updates are printed as soon as they come in but updates more often than `updateInterval` are ignored. The reason 0.8 doesn't have this set to true is that it can't `unref` its timer and so it would stop your program from exiting– if you want to use this feature with 0.8 just make sure you call `gauge.disable()` before you expect your program to exit. * **themes**: A themeset to use when selecting the theme to use. Defaults to `gauge/themes`, see the [themes] documentation for details. * **theme**: Select a theme for use, it can be a: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. * **template**: Describes what you want your gauge to look like. The default is what npm uses. Detailed [documentation] is later in this document. * **hideCursor**: Defaults to true. If true, then the cursor will be hidden while the gauge is displayed. * **tty**: The tty that you're ultimately writing to. Defaults to the same as **stream**. This is used for detecting the width of the terminal and resizes. The width used is `tty.columns - 1`. If no tty is available then a width of `79` is assumed. * **enabled**: Defaults to true if `tty` is a TTY, false otherwise. If true the gauge starts enabled. If disabled then all update commands are ignored and no gauge will be printed until you call `.enable()`. * **Plumbing**: The class to use to actually generate the gauge for printing. This defaults to `require('gauge/plumbing')` and ordinarly you shouldn't need to override this. * **cleanupOnExit**: Defaults to true. Ordinarily we register an exit handler to make sure your cursor is turned back on and the progress bar erased when your process exits, even if you Ctrl-C out or otherwise exit unexpectedly. You can disable this and it won't register the exit handler. [has-unicode]: https://www.npmjs.com/package/has-unicode [themes]: #themes [documentation]: #templates #### `gauge.show(section | status, [completed])` The first argument is either the section, the name of the current thing contributing to progress, or an object with keys like **section**, **subsection** & **completed** (or any others you have types for in a custom template). If you don't want to update or set any of these you can pass `null` and it will be ignored. The second argument is the percent completed as a value between 0 and 1. Without it, completion is just not updated. You'll also note that completion can be passed in as part of a status object as the first argument. If both it and the completed argument are passed in, the completed argument wins. #### `gauge.hide([cb])` Removes the gauge from the terminal. Optionally, callback `cb` after IO has had an opportunity to happen (currently this just means after `setImmediate` has called back.) It turns out this is important when you're pausing the progress bar on one filehandle and printing to another– otherwise (with a big enough print) node can end up printing the "end progress bar" bits to the progress bar filehandle while other stuff is printing to another filehandle. These getting interleaved can cause corruption in some terminals. #### `gauge.pulse([subsection])` * **subsection** – *(optional)* The specific thing that triggered this pulse Spins the spinner in the gauge to show output. If **subsection** is included then it will be combined with the last name passed to `gauge.show`. #### `gauge.disable()` Hides the gauge and ignores further calls to `show` or `pulse`. #### `gauge.enable()` Shows the gauge and resumes updating when `show` or `pulse` is called. #### `gauge.isEnabled()` Returns true if the gauge is enabled. #### `gauge.setThemeset(themes)` Change the themeset to select a theme from. The same as the `themes` option used in the constructor. The theme will be reselected from this themeset. #### `gauge.setTheme(theme)` Change the active theme, will be displayed with the next show or pulse. This can be: * Theme object, in which case the **themes** is not used. * The name of a theme, which will be looked up in the current *themes* object. * A configuration object with any of `hasUnicode`, `hasColor` or `platform` keys, which if wlll be used to override our guesses when making a default theme selection. If no theme is selected then a default is picked using a combination of our best guesses at your OS, color support and unicode support. #### `gauge.setTemplate(template)` Change the active template, will be displayed with the next show or pulse ### Tracking Completion If you have more than one thing going on that you want to track completion of, you may find the related [are-we-there-yet] helpful. It's `change` event can be wired up to the `show` method to get a more traditional progress bar interface. [are-we-there-yet]: https://www.npmjs.com/package/are-we-there-yet ### THEMES ``` var themes = require('gauge/themes') // fetch the default color unicode theme for this platform var ourTheme = themes({hasUnicode: true, hasColor: true}) // fetch the default non-color unicode theme for osx var ourTheme = themes({hasUnicode: true, hasColor: false, platform: 'darwin'}) // create a new theme based on the color ascii theme for this platform // that brackets the progress bar with arrows var ourTheme = themes.newTheme(theme(hasUnicode: false, hasColor: true}), { preProgressbar: '→', postProgressbar: '←' }) ``` The object returned by `gauge/themes` is an instance of the `ThemeSet` class. ``` var ThemeSet = require('gauge/theme-set') var themes = new ThemeSet() // or var themes = require('gauge/themes') var mythemes = themes.newThemeset() // creates a new themeset based on the default themes ``` #### themes(opts) #### themes.getDefault(opts) Theme objects are a function that fetches the default theme based on platform, unicode and color support. Options is an object with the following properties: * **hasUnicode** - If true, fetch a unicode theme, if no unicode theme is available then a non-unicode theme will be used. * **hasColor** - If true, fetch a color theme, if no color theme is available a non-color theme will be used. * **platform** (optional) - Defaults to `process.platform`. If no platform match is available then `fallback` is used instead. If no compatible theme can be found then an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.addTheme(themeName, themeObj) #### themes.addTheme(themeName, [parentTheme], newTheme) Adds a named theme to the themeset. You can pass in either a theme object, as returned by `themes.newTheme` or the arguments you'd pass to `themes.newTheme`. #### themes.getThemeNames() Return a list of all of the names of the themes in this themeset. Suitable for use in `themes.getTheme(…)`. #### themes.getTheme(name) Returns the theme object from this theme set named `name`. If `name` does not exist in this themeset an error will be thrown with a `code` of `EMISSINGTHEME`. #### themes.setDefault([opts], themeName) `opts` is an object with the following properties. * **platform** - Defaults to `'fallback'`. If your theme is platform specific, specify that here with the platform from `process.platform`, eg, `win32`, `darwin`, etc. * **hasUnicode** - Defaults to `false`. If your theme uses unicode you should set this to true. * **hasColor** - Defaults to `false`. If your theme uses color you should set this to true. `themeName` is the name of the theme (as given to `addTheme`) to use for this set of `opts`. #### themes.newTheme([parentTheme,] newTheme) Create a new theme object based on `parentTheme`. If no `parentTheme` is provided then a minimal parentTheme that defines functions for rendering the activity indicator (spinner) and progress bar will be defined. (This fallback parent is defined in `gauge/base-theme`.) newTheme should be a bare object– we'll start by discussing the properties defined by the default themes: * **preProgressbar** - displayed prior to the progress bar, if the progress bar is displayed. * **postProgressbar** - displayed after the progress bar, if the progress bar is displayed. * **progressBarTheme** - The subtheme passed through to the progress bar renderer, it's an object with `complete` and `remaining` properties that are the strings you want repeated for those sections of the progress bar. * **activityIndicatorTheme** - The theme for the activity indicator (spinner), this can either be a string, in which each character is a different step, or an array of strings. * **preSubsection** - Displayed as a separator between the `section` and `subsection` when the latter is printed. More generally, themes can have any value that would be a valid value when rendering templates. The properties in the theme are used when their name matches a type in the template. Their values can be: * **strings & numbers** - They'll be included as is * **function (values, theme, width)** - Should return what you want in your output. *values* is an object with values provided via `gauge.show`, *theme* is the theme specific to this item (see below) or this theme object, and *width* is the number of characters wide your result should be. There are a couple of special prefixes: * **pre** - Is shown prior to the property, if its displayed. * **post** - Is shown after the property, if its displayed. And one special suffix: * **Theme** - Its value is passed to a function-type item as the theme. #### themes.addToAllThemes(theme) This *mixes-in* `theme` into all themes currently defined. It also adds it to the default parent theme for this themeset, so future themes added to this themeset will get the values from `theme` by default. #### themes.newThemeset() Copy the current themeset into a new one. This allows you to easily inherit one themeset from another. ### TEMPLATES A template is an array of objects and strings that, after being evaluated, will be turned into the gauge line. The default template is: ```javascript [ {type: 'progressbar', length: 20}, {type: 'activityIndicator', kerning: 1, length: 1}, {type: 'section', kerning: 1, default: ''}, {type: 'subsection', kerning: 1, default: ''} ] ``` The various template elements can either be **plain strings**, in which case they will be be included verbatum in the output, or objects with the following properties: * *type* can be any of the following plus any keys you pass into `gauge.show` plus any keys you have on a custom theme. * `section` – What big thing you're working on now. * `subsection` – What component of that thing is currently working. * `activityIndicator` – Shows a spinner using the `activityIndicatorTheme` from your active theme. * `progressbar` – A progress bar representing your current `completed` using the `progressbarTheme` from your active theme. * *kerning* – Number of spaces that must be between this item and other items, if this item is displayed at all. * *maxLength* – The maximum length for this element. If its value is longer it will be truncated. * *minLength* – The minimum length for this element. If its value is shorter it will be padded according to the *align* value. * *align* – (Default: left) Possible values "left", "right" and "center". Works as you'd expect from word processors. * *length* – Provides a single value for both *minLength* and *maxLength*. If both *length* and *minLength or *maxLength* are specifed then the latter take precedence. * *value* – A literal value to use for this template item. * *default* – A default value to use for this template item if a value wasn't otherwise passed in. ### PLUMBING This is the super simple, assume nothing, do no magic internals used by gauge to implement its ordinary interface. ``` var Plumbing = require('gauge/plumbing') var gauge = new Plumbing(theme, template, width) ``` * **theme**: The theme to use. * **template**: The template to use. * **width**: How wide your gauge should be #### `gauge.setTheme(theme)` Change the active theme. #### `gauge.setTemplate(template)` Change the active template. #### `gauge.setWidth(width)` Change the width to render at. #### `gauge.hide()` Return the string necessary to hide the progress bar #### `gauge.hideCursor()` Return a string to hide the cursor. #### `gauge.showCursor()` Return a string to show the cursor. #### `gauge.show(status)` Using `status` for values, render the provided template with the theme and return a string that is suitable for printing to update the gauge. Deep Extend =========== Recursive object extending. [![Build Status](https://api.travis-ci.org/unclechu/node-deep-extend.svg?branch=master)](https://travis-ci.org/unclechu/node-deep-extend) [![NPM](https://nodei.co/npm/deep-extend.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/deep-extend/) Install ------- ```bash $ npm install deep-extend ``` Usage ----- ```javascript var deepExtend = require('deep-extend'); var obj1 = { a: 1, b: 2, d: { a: 1, b: [], c: { test1: 123, test2: 321 } }, f: 5, g: 123, i: 321, j: [1, 2] }; var obj2 = { b: 3, c: 5, d: { b: { first: 'one', second: 'two' }, c: { test2: 222 } }, e: { one: 1, two: 2 }, f: [], g: (void 0), h: /abc/g, i: null, j: [3, 4] }; deepExtend(obj1, obj2); console.log(obj1); /* { a: 1, b: 3, d: { a: 1, b: { first: 'one', second: 'two' }, c: { test1: 123, test2: 222 } }, f: [], g: undefined, c: 5, e: { one: 1, two: 2 }, h: /abc/g, i: null, j: [3, 4] } */ ``` Unit testing ------------ ```bash $ npm test ``` Changelog --------- [CHANGELOG.md](./CHANGELOG.md) Any issues? ----------- Please, report about issues [here](https://github.com/unclechu/node-deep-extend/issues). License ------- [MIT](./LICENSE) # Miller-Rabin #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2014. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # memory-fs A simple in-memory filesystem. Holds data in a javascript object. ``` javascript var MemoryFileSystem = require("memory-fs"); var fs = new MemoryFileSystem(); // Optionally pass a javascript object fs.mkdirpSync("/a/test/dir"); fs.writeFileSync("/a/test/dir/file.txt", "Hello World"); fs.readFileSync("/a/test/dir/file.txt"); // returns Buffer("Hello World") // Async variants too fs.unlink("/a/test/dir/file.txt", function(err) { // ... }); fs.readdirSync("/a/test"); // returns ["dir"] fs.statSync("/a/test/dir").isDirectory(); // returns true fs.rmdirSync("/a/test/dir"); fs.mkdirpSync("C:\\use\\windows\\style\\paths"); ``` ## License Copyright (c) 2012-2014 Tobias Koppers MIT (http://www.opensource.org/licenses/mit-license.php) # negotiator [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] An HTTP content negotiator for Node.js ## Installation ```sh $ npm install negotiator ``` ## API ```js var Negotiator = require('negotiator') ``` ### Accept Negotiation ```js availableMediaTypes = ['text/html', 'text/plain', 'application/json'] // The negotiator constructor receives a request object negotiator = new Negotiator(request) // Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' negotiator.mediaTypes() // -> ['text/html', 'image/jpeg', 'application/*'] negotiator.mediaTypes(availableMediaTypes) // -> ['text/html', 'application/json'] negotiator.mediaType(availableMediaTypes) // -> 'text/html' ``` You can check a working example at `examples/accept.js`. #### Methods ##### mediaType() Returns the most preferred media type from the client. ##### mediaType(availableMediaType) Returns the most preferred media type from a list of available media types. ##### mediaTypes() Returns an array of preferred media types ordered by the client preference. ##### mediaTypes(availableMediaTypes) Returns an array of preferred media types ordered by priority from a list of available media types. ### Accept-Language Negotiation ```js negotiator = new Negotiator(request) availableLanguages = ['en', 'es', 'fr'] // Let's say Accept-Language header is 'en;q=0.8, es, pt' negotiator.languages() // -> ['es', 'pt', 'en'] negotiator.languages(availableLanguages) // -> ['es', 'en'] language = negotiator.language(availableLanguages) // -> 'es' ``` You can check a working example at `examples/language.js`. #### Methods ##### language() Returns the most preferred language from the client. ##### language(availableLanguages) Returns the most preferred language from a list of available languages. ##### languages() Returns an array of preferred languages ordered by the client preference. ##### languages(availableLanguages) Returns an array of preferred languages ordered by priority from a list of available languages. ### Accept-Charset Negotiation ```js availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] negotiator = new Negotiator(request) // Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' negotiator.charsets() // -> ['utf-8', 'iso-8859-1', 'utf-7'] negotiator.charsets(availableCharsets) // -> ['utf-8', 'iso-8859-1'] negotiator.charset(availableCharsets) // -> 'utf-8' ``` You can check a working example at `examples/charset.js`. #### Methods ##### charset() Returns the most preferred charset from the client. ##### charset(availableCharsets) Returns the most preferred charset from a list of available charsets. ##### charsets() Returns an array of preferred charsets ordered by the client preference. ##### charsets(availableCharsets) Returns an array of preferred charsets ordered by priority from a list of available charsets. ### Accept-Encoding Negotiation ```js availableEncodings = ['identity', 'gzip'] negotiator = new Negotiator(request) // Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' negotiator.encodings() // -> ['gzip', 'identity', 'compress'] negotiator.encodings(availableEncodings) // -> ['gzip', 'identity'] negotiator.encoding(availableEncodings) // -> 'gzip' ``` You can check a working example at `examples/encoding.js`. #### Methods ##### encoding() Returns the most preferred encoding from the client. ##### encoding(availableEncodings) Returns the most preferred encoding from a list of available encodings. ##### encodings() Returns an array of preferred encodings ordered by the client preference. ##### encodings(availableEncodings) Returns an array of preferred encodings ordered by priority from a list of available encodings. ## See Also The [accepts](https://npmjs.org/package/accepts#readme) module builds on this module and provides an alternative interface, mime type validation, and more. ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/negotiator.svg [npm-url]: https://npmjs.org/package/negotiator [node-version-image]: https://img.shields.io/node/v/negotiator.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg [travis-url]: https://travis-ci.org/jshttp/negotiator [coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master [downloads-image]: https://img.shields.io/npm/dm/negotiator.svg [downloads-url]: https://npmjs.org/package/negotiator # pump pump is a small node module that pipes streams together and destroys all of them if one of them closes. ``` npm install pump ``` [![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) ## What problem does it solve? When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. You are also not able to provide a callback to tell when then pipe has finished. pump does these two things for you ## Usage Simply pass the streams you want to pipe together to pump and add an optional callback ``` js var pump = require('pump') var fs = require('fs') var source = fs.createReadStream('/dev/random') var dest = fs.createWriteStream('/dev/null') pump(source, dest, function(err) { console.log('pipe finished', err) }) setTimeout(function() { dest.destroy() // when dest is closed pump will destroy source }, 1000) ``` You can use pump to pipe more than two streams together as well ``` js var transform = someTransformStream() pump(source, transform, anotherTransform, dest, function(err) { console.log('pipe finished', err) }) ``` If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do: ``` return pump(s1, s2) // returns s2 ``` If you want to return a stream that combines *both* s1 and s2 to a single stream use [pumpify](https://github.com/mafintosh/pumpify) instead. ## License MIT ## Related `pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. # cssesc [![Build status](https://travis-ci.org/mathiasbynens/cssesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/cssesc) [![Code coverage status](https://img.shields.io/codecov/c/github/mathiasbynens/cssesc.svg)](https://codecov.io/gh/mathiasbynens/cssesc) A JavaScript library for escaping CSS strings and identifiers while generating the shortest possible ASCII-only output. This is a JavaScript library for [escaping text for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes) while generating the shortest possible valid ASCII-only output. [Here’s an online demo.](https://mothereff.in/css-escapes) [A polyfill for the CSSOM `CSS.escape()` method is available in a separate repository.](https://mths.be/cssescape) (In comparison, _cssesc_ is much more powerful.) Feel free to fork if you see possible improvements! ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install cssesc ``` In a browser: ```html <script src="cssesc.js"></script> ``` In [Node.js](https://nodejs.org/): ```js const cssesc = require('cssesc'); ``` In Ruby using [the `ruby-cssesc` wrapper gem](https://github.com/borodean/ruby-cssesc): ```bash gem install ruby-cssesc ``` ```ruby require 'ruby-cssesc' CSSEsc.escape('I ♥ Ruby', is_identifier: true) ``` In Sass using [`sassy-escape`](https://github.com/borodean/sassy-escape): ```bash gem install sassy-escape ``` ```scss body { content: escape('I ♥ Sass', $is-identifier: true); } ``` ## API ### `cssesc(value, options)` This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in CSS strings or identifiers](https://mathiasbynens.be/notes/css-escapes). ```js cssesc('Ich ♥ Bücher'); // → 'Ich \\2665 B\\FC cher' cssesc('foo 𝌆 bar'); // → 'foo \\1D306 bar' ``` By default, `cssesc` returns a string that can be used as part of a CSS string. If the target is a CSS identifier rather than a CSS string, use the `isIdentifier: true` setting (see below). The optional `options` argument accepts an object with the following options: #### `isIdentifier` The default value for the `isIdentifier` option is `false`. This means that the input text will be escaped for use in a CSS string literal. If you want to use the result as a CSS identifier instead (in a selector, for example), set this option to `true`. ```js cssesc('123a2b'); // → '123a2b' cssesc('123a2b', { 'isIdentifier': true }); // → '\\31 23a2b' ``` #### `quotes` The default value for the `quotes` option is `'single'`. This means that any occurences of `'` in the input text will be escaped as `\'`, so that the output can be used in a CSS string literal wrapped in single quotes. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.'); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single' }); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' // → "Lorem ipsum \"dolor\" sit \\'amet\\' etc." ``` If you want to use the output as part of a CSS string literal wrapped in double quotes, set the `quotes` option to `'double'`. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double' }); // → 'Lorem ipsum \\"dolor\\" sit \'amet\' etc.' // → "Lorem ipsum \\\"dolor\\\" sit 'amet' etc." ``` #### `wrap` The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output will be a valid CSS string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. ```js cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true }); // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" cssesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true }); // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" ``` #### `escapeEverything` The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output will be escaped, even printable ASCII symbols. ```js cssesc('lolwat"foo\'bar', { 'escapeEverything': true }); // → '\\6C\\6F\\6C\\77\\61\\74\\"\\66\\6F\\6F\\\'\\62\\61\\72' // → "\\6C\\6F\\6C\\77\\61\\74\\\"\\66\\6F\\6F\\'\\62\\61\\72" ``` #### Overriding the default options globally The global default settings can be overridden by modifying the `css.options` object. This saves you from passing in an `options` object for every call to `encode` if you want to use the non-default setting. ```js // Read the global default setting for `escapeEverything`: cssesc.options.escapeEverything; // → `false` by default // Override the global default setting for `escapeEverything`: cssesc.options.escapeEverything = true; // Using the global default setting for `escapeEverything`, which is now `true`: cssesc('foo © bar ≠ baz 𝌆 qux'); // → '\\66\\6F\\6F\\ \\A9\\ \\62\\61\\72\\ \\2260\\ \\62\\61\\7A\\ \\1D306\\ \\71\\75\\78' ``` ### `cssesc.version` A string representing the semantic version number. ### Using the `cssesc` binary To use the `cssesc` binary in your shell, simply install cssesc globally using npm: ```bash npm install -g cssesc ``` After that you will be able to escape text for use in CSS strings or identifiers from the command line: ```bash $ cssesc 'föo ♥ bår 𝌆 baz' f\F6o \2665 b\E5r \1D306 baz ``` If the output needs to be a CSS identifier rather than part of a string literal, use the `-i`/`--identifier` option: ```bash $ cssesc --identifier 'föo ♥ bår 𝌆 baz' f\F6o\ \2665\ b\E5r\ \1D306\ baz ``` See `cssesc --help` for the full list of options. ## Support This library supports the Node.js and browser versions mentioned in [`.babelrc`](https://github.com/mathiasbynens/cssesc/blob/master/.babelrc). For a version that supports a wider variety of legacy browsers and environments out-of-the-box, [see v0.1.0](https://github.com/mathiasbynens/cssesc/releases/tag/v0.1.0). ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License This library is available under the [MIT](https://mths.be/mit) license. # json-schema-traverse Traverse JSON Schema passing each schema object to callback [![Build Status](https://travis-ci.org/epoberezkin/json-schema-traverse.svg?branch=master)](https://travis-ci.org/epoberezkin/json-schema-traverse) [![npm version](https://badge.fury.io/js/json-schema-traverse.svg)](https://www.npmjs.com/package/json-schema-traverse) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/json-schema-traverse/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master) ## Install ``` npm install json-schema-traverse ``` ## Usage ```javascript const traverse = require('json-schema-traverse'); const schema = { properties: { foo: {type: 'string'}, bar: {type: 'integer'} } }; traverse(schema, {cb}); // cb is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // Or: traverse(schema, {cb: {pre, post}}); // pre is called 3 times with: // 1. root schema // 2. {type: 'string'} // 3. {type: 'integer'} // // post is called 3 times with: // 1. {type: 'string'} // 2. {type: 'integer'} // 3. root schema ``` Callback function `cb` is called for each schema object (not including draft-06 boolean schemas), including the root schema, in pre-order traversal. Schema references ($ref) are not resolved, they are passed as is. Alternatively, you can pass a `{pre, post}` object as `cb`, and then `pre` will be called before traversing child elements, and `post` will be called after all child elements have been traversed. Callback is passed these parameters: - _schema_: the current schema object - _JSON pointer_: from the root schema to the current schema object - _root schema_: the schema passed to `traverse` object - _parent JSON pointer_: from the root schema to the parent schema object (see below) - _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.) - _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema - _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'` ## Traverse objects in all unknown keywords ```javascript const traverse = require('json-schema-traverse'); const schema = { mySchema: { minimum: 1, maximum: 2 } }; traverse(schema, {allKeys: true, cb}); // cb is called 2 times with: // 1. root schema // 2. mySchema ``` Without option `allKeys: true` callback will be called only with root schema. ## License [MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE) # define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i define-property --save ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## Related projects * [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object) * [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._ # map-visit [![NPM version](https://img.shields.io/npm/v/map-visit.svg?style=flat)](https://www.npmjs.com/package/map-visit) [![NPM monthly downloads](https://img.shields.io/npm/dm/map-visit.svg?style=flat)](https://npmjs.org/package/map-visit) [![NPM total downloads](https://img.shields.io/npm/dt/map-visit.svg?style=flat)](https://npmjs.org/package/map-visit) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/map-visit.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/map-visit) > Map `visit` over an array of objects. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save map-visit ``` ## Usage ```js var mapVisit = require('map-visit'); ``` ## What does this do? **Assign/Merge/Extend vs. Visit** Let's say you want to add a `set` method to your application that will: * set key-value pairs on a `data` object * extend objects onto the `data` object * extend arrays of objects onto the data object **Example using `extend`** Here is one way to accomplish this using Lo-Dash's `extend` (comparable to `Object.assign`): ```js var _ = require('lodash'); var obj = { data: {}, set: function (key, value) { if (Array.isArray(key)) { _.extend.apply(_, [obj.data].concat(key)); } else if (typeof key === 'object') { _.extend(obj.data, key); } else { obj.data[key] = value; } } }; obj.set('a', 'a'); obj.set([{b: 'b'}, {c: 'c'}]); obj.set({d: {e: 'f'}}); console.log(obj.data); //=> {a: 'a', b: 'b', c: 'c', d: { e: 'f' }} ``` The above approach works fine for most use cases. However, **if you also want to emit an event** each time a property is added to the `data` object, or you want more control over what happens as the object is extended, a better approach would be to use `visit`. **Example using `visit`** In this approach: * when an array is passed to `set`, the `mapVisit` library calls the `set` method on each object in the array. * when an object is passed, `visit` calls `set` on each property in the object. As a result, the `data` event will be emitted every time a property is added to `data` (events are just an example, you can use this approach to perform any necessary logic every time the method is called). ```js var mapVisit = require('map-visit'); var visit = require('object-visit'); var obj = { data: {}, set: function (key, value) { if (Array.isArray(key)) { mapVisit(obj, 'set', key); } else if (typeof key === 'object') { visit(obj, 'set', key); } else { // simulate an event-emitter console.log('emit', key, value); obj.data[key] = value; } } }; obj.set('a', 'a'); obj.set([{b: 'b'}, {c: 'c'}]); obj.set({d: {e: 'f'}}); obj.set({g: 'h', i: 'j', k: 'l'}); console.log(obj.data); //=> {a: 'a', b: 'b', c: 'c', d: { e: 'f' }, g: 'h', i: 'j', k: 'l'} // events would look something like: // emit a a // emit b b // emit c c // emit d { e: 'f' } // emit g h // emit i j // emit k l ``` ## About ### Related projects * [collection-visit](https://www.npmjs.com/package/collection-visit): Visit a method over the items in an object, or map visit over the objects… [more](https://github.com/jonschlinkert/collection-visit) | [homepage](https://github.com/jonschlinkert/collection-visit "Visit a method over the items in an object, or map visit over the objects in an array.") * [object-visit](https://www.npmjs.com/package/object-visit): Call a specified method on each value in the given object. | [homepage](https://github.com/jonschlinkert/object-visit "Call a specified method on each value in the given object.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 15 | [jonschlinkert](https://github.com/jonschlinkert) | | 7 | [doowb](https://github.com/doowb) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 09, 2017._ # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` <!-- -- This file is auto-generated from README_js.md. Changes should be made there. --> # uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. Features: * Support for version 1, 3, 4 and 5 UUIDs * Cross-platform * Uses cryptographically-strong random number APIs (when available) * Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883)) [**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.] ## Quickstart - CommonJS (Recommended) ```shell npm install uuid ``` Then generate your uuid version of choice ... Version 1 (timestamp): ```javascript const uuidv1 = require('uuid/v1'); uuidv1(); // ⇨ '45745c60-7b1a-11e8-9c9c-2d42b21b1a3e' ``` Version 3 (namespace): ```javascript const uuidv3 = require('uuid/v3'); // ... using predefined DNS namespace (for domain names) uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6' // ... using predefined URL namespace (for, well, URLs) uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138' // ... using a custom namespace // // Note: Custom namespaces should be a UUID string specific to your application! // E.g. the one here was generated using this modules `uuid` CLI. const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686' ``` Version 4 (random): ```javascript const uuidv4 = require('uuid/v4'); uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a' ``` Version 5 (namespace): ```javascript const uuidv5 = require('uuid/v5'); // ... using predefined DNS namespace (for domain names) uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec' // ... using predefined URL namespace (for, well, URLs) uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1' // ... using a custom namespace // // Note: Custom namespaces should be a UUID string specific to your application! // E.g. the one here was generated using this modules `uuid` CLI. const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' ``` ## Quickstart - Browser-ready Versions Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in). For version 1 uuids: ```html <script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script> <script> uuidv1(); // -> v1 UUID </script> ``` For version 3 uuids: ```html <script src="http://wzrd.in/standalone/uuid%2Fv3@latest"></script> <script> uuidv3('http://example.com/hello', uuidv3.URL); // -> v3 UUID </script> ``` For version 4 uuids: ```html <script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script> <script> uuidv4(); // -> v4 UUID </script> ``` For version 5 uuids: ```html <script src="http://wzrd.in/standalone/uuid%2Fv5@latest"></script> <script> uuidv5('http://example.com/hello', uuidv5.URL); // -> v5 UUID </script> ``` ## API ### Version 1 ```javascript const uuidv1 = require('uuid/v1'); // Incantations uuidv1(); uuidv1(options); uuidv1(options, buffer, offset); ``` Generate and return a RFC4122 v1 (timestamp-based) UUID. * `options` - (Object) Optional uuid state to apply. Properties may include: * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. * `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. * `offset` - (Number) Starting index in `buffer` at which to begin writing. Returns `buffer`, if specified, otherwise the string form of the UUID Note: The <node> id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) Example: Generate string UUID with fully-specified options ```javascript const v1options = { node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], clockseq: 0x1234, msecs: new Date('2011-11-01').getTime(), nsecs: 5678 }; uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' ``` Example: In-place generation of two binary IDs ```javascript // Generate two ids in an array const arr = new Array(); uuidv1(null, arr, 0); // ⇨ [ 69, 117, 109, 208, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62 ] uuidv1(null, arr, 16); // ⇨ [ 69, 117, 109, 208, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62, 69, 117, 109, 209, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62 ] ``` ### Version 3 ```javascript const uuidv3 = require('uuid/v3'); // Incantations uuidv3(name, namespace); uuidv3(name, namespace, buffer); uuidv3(name, namespace, buffer, offset); ``` Generate and return a RFC4122 v3 UUID. * `name` - (String | Array[]) "name" to create UUID with * `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 Returns `buffer`, if specified, otherwise the string form of the UUID Example: ```javascript uuidv3('hello world', MY_NAMESPACE); // ⇨ '042ffd34-d989-321c-ad06-f60826172424' ``` ### Version 4 ```javascript const uuidv4 = require('uuid/v4') // Incantations uuidv4(); uuidv4(options); uuidv4(options, buffer, offset); ``` Generate and return a RFC4122 v4 UUID. * `options` - (Object) Optional uuid state to apply. Properties may include: * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values * `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255) * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. * `offset` - (Number) Starting index in `buffer` at which to begin writing. Returns `buffer`, if specified, otherwise the string form of the UUID Example: Generate string UUID with predefined `random` values ```javascript const v4options = { random: [ 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 ] }; uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' ``` Example: Generate two IDs in a single buffer ```javascript const buffer = new Array(); uuidv4(null, buffer, 0); // ⇨ [ 54, 122, 218, 70, 45, 70, 65, 24, 171, 53, 95, 130, 83, 195, 242, 45 ] uuidv4(null, buffer, 16); // ⇨ [ 54, 122, 218, 70, 45, 70, 65, 24, 171, 53, 95, 130, 83, 195, 242, 45, 108, 204, 255, 103, 171, 86, 76, 94, 178, 225, 188, 236, 150, 20, 151, 87 ] ``` ### Version 5 ```javascript const uuidv5 = require('uuid/v5'); // Incantations uuidv5(name, namespace); uuidv5(name, namespace, buffer); uuidv5(name, namespace, buffer, offset); ``` Generate and return a RFC4122 v5 UUID. * `name` - (String | Array[]) "name" to create UUID with * `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values * `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. * `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 Returns `buffer`, if specified, otherwise the string form of the UUID Example: ```javascript uuidv5('hello world', MY_NAMESPACE); // ⇨ '9f282611-e0fd-5650-8953-89c8e342da0b' ``` ## Command Line UUIDs can be generated from the command line with the `uuid` command. ```shell $ uuid ddeb27fb-d9a0-4624-be4d-4615062daed4 $ uuid v1 02d37060-d446-11e7-a9fa-7bdae751ebe1 ``` Type `uuid --help` for usage details ## Testing ```shell npm test ``` ---- Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) # posix-character-classes [![NPM version](https://img.shields.io/npm/v/posix-character-classes.svg?style=flat)](https://www.npmjs.com/package/posix-character-classes) [![NPM monthly downloads](https://img.shields.io/npm/dm/posix-character-classes.svg?style=flat)](https://npmjs.org/package/posix-character-classes) [![NPM total downloads](https://img.shields.io/npm/dt/posix-character-classes.svg?style=flat)](https://npmjs.org/package/posix-character-classes) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/posix-character-classes.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/posix-character-classes) > POSIX character classes for creating regular expressions. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save posix-character-classes ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add posix-character-classes ``` ## Usage ```js var posix = require('posix-character-classes'); console.log(posix.alpha); //=> 'A-Za-z' ``` ## POSIX Character classes The POSIX standard supports the following classes or categories of charactersh (note that classes must be defined within brackets)<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup>: | **POSIX class** | **Equivalent to** | **Matches** | | --- | --- | --- | | `[:alnum:]` | `[A-Za-z0-9]` | digits, uppercase and lowercase letters | | `[:alpha:]` | `[A-Za-z]` | upper- and lowercase letters | | `[:ascii:]` | `[\x00-\x7F]` | ASCII characters | | `[:blank:]` | `[ \t]` | space and TAB characters only | | `[:cntrl:]` | `[\x00-\x1F\x7F]` | Control characters | | `[:digit:]` | `[0-9]` | digits | | `[:graph:]` | `[^[:cntrl:]]` | graphic characters (all characters which have graphic representation) | | `[:lower:]` | `[a-z]` | lowercase letters | | `[:print:]` | `[[:graph] ]` | graphic characters and space | | `[:punct:]` | ``[-!"#$%&'()*+,./:;<=>?@[]^_`{ | }~]`` | all punctuation characters (all graphic characters except letters and digits) | | `[:space:]` | `[ \t\n\r\f\v]` | all blank (whitespace) characters, including spaces, tabs, new lines, carriage returns, form feeds, and vertical tabs | | `[:upper:]` | `[A-Z]` | uppercase letters | | `[:word:]` | `[A-Za-z0-9_]` | word characters | | `[:xdigit:]` | `[0-9A-Fa-f]` | hexadecimal digits | ## Examples * `a[[:digit:]]b` matches `a0b`, `a1b`, ..., `a9b`. * `a[:digit:]b` is invalid, character classes must be enclosed in brackets * `[[:digit:]abc]` matches any digit, as well as `a`, `b`, and `c`. * `[abc[:digit:]]` is the same as the previous, matching any digit, as well as `a`, `b`, and `c` * `[^ABZ[:lower:]]` matches any character except lowercase letters, `A`, `B`, and `Z`. ## About ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 20, 2017._ <hr class="footnotes-sep"> <section class="footnotes"> <ol class="footnotes-list"> <li id="fn1" class="footnote-item">table and examples are based on the WikiBooks page for [Regular Expressions/POSIX Basic Regular Expressions](https://en.wikibooks.org/wiki/Regular_Expressions/POSIX_Basic_Regular_Expressions), which is available under the [Creative Commons Attribution-ShareAlike License](https://creativecommons.org/licenses/by-sa/3.0/). <a href="#fnref1" class="footnote-backref">↩</a> </li> </ol> </section> # extglob [![NPM version](https://img.shields.io/npm/v/extglob.svg?style=flat)](https://www.npmjs.com/package/extglob) [![NPM monthly downloads](https://img.shields.io/npm/dm/extglob.svg?style=flat)](https://npmjs.org/package/extglob) [![NPM total downloads](https://img.shields.io/npm/dt/extglob.svg?style=flat)](https://npmjs.org/package/extglob) [![Linux Build Status](https://img.shields.io/travis/micromatch/extglob.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/extglob) [![Windows Build Status](https://img.shields.io/appveyor/ci/micromatch/extglob.svg?style=flat&label=AppVeyor)](https://ci.appveyor.com/project/micromatch/extglob) > Extended glob support for JavaScript. Adds (almost) the expressive power of regular expressions to glob patterns. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save extglob ``` * Convert an extglob string to a regex-compatible string. * More complete (and correct) support than [minimatch](https://github.com/isaacs/minimatch) (minimatch fails a large percentage of the extglob tests) * Handles [negation patterns](#extglob-patterns) * Handles [nested patterns](#extglob-patterns) * Organized code base, easy to maintain and make changes when edge cases arise * As you can see by the [benchmarks](#benchmarks), extglob doesn't pay with speed for it's completeness, accuracy and quality. **Heads up!**: This library only supports extglobs, to handle full glob patterns and other extended globbing features use [micromatch](https://github.com/jonschlinkert/micromatch) instead. ## Usage The main export is a function that takes a string and options, and returns an object with the parsed AST and the compiled `.output`, which is a regex-compatible string that can be used for matching. ```js var extglob = require('extglob'); console.log(extglob('!(xyz)*.js')); ``` ## Extglob cheatsheet Extended globbing patterns can be defined as follows (as described by the [bash man page](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)): | **pattern** | **regex equivalent** | **description** | | --- | --- | --- | | `?(pattern-list)` | `(...|...)?` | Matches zero or one occurrence of the given pattern(s) | | `*(pattern-list)` | `(...|...)*` | Matches zero or more occurrences of the given pattern(s) | | `+(pattern-list)` | `(...|...)+` | Matches one or more occurrences of the given pattern(s) | | `@(pattern-list)` | `(...|...)` <sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> | Matches one of the given pattern(s) | | `!(pattern-list)` | N/A | Matches anything except one of the given pattern(s) | ## API ### [extglob](index.js#L36) Convert the given `extglob` pattern into a regex-compatible string. Returns an object with the compiled result and the parsed AST. **Params** * `pattern` **{String}** * `options` **{Object}** * `returns` **{String}** **Example** ```js var extglob = require('extglob'); console.log(extglob('*.!(*a)')); //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' ``` ### [.match](index.js#L56) Takes an array of strings and an extglob pattern and returns a new array that contains only the strings that match the pattern. **Params** * `list` **{Array}**: Array of strings to match * `pattern` **{String}**: Extglob pattern * `options` **{Object}** * `returns` **{Array}**: Returns an array of matches **Example** ```js var extglob = require('extglob'); console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)')); //=> ['a.b', 'a.c'] ``` ### [.isMatch](index.js#L111) Returns true if the specified `string` matches the given extglob `pattern`. **Params** * `string` **{String}**: String to match * `pattern` **{String}**: Extglob pattern * `options` **{String}** * `returns` **{Boolean}** **Example** ```js var extglob = require('extglob'); console.log(extglob.isMatch('a.a', '*.!(*a)')); //=> false console.log(extglob.isMatch('a.b', '*.!(*a)')); //=> true ``` ### [.contains](index.js#L150) Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but the pattern can match any part of the string. **Params** * `str` **{String}**: The string to match. * `pattern` **{String}**: Glob pattern to use for matching. * `options` **{Object}** * `returns` **{Boolean}**: Returns true if the patter matches any part of `str`. **Example** ```js var extglob = require('extglob'); console.log(extglob.contains('aa/bb/cc', '*b')); //=> true console.log(extglob.contains('aa/bb/cc', '*d')); //=> false ``` ### [.matcher](index.js#L184) Takes an extglob pattern and returns a matcher function. The returned function takes the string to match as its only argument. **Params** * `pattern` **{String}**: Extglob pattern * `options` **{String}** * `returns` **{Boolean}** **Example** ```js var extglob = require('extglob'); var isMatch = extglob.matcher('*.!(*a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` ### [.create](index.js#L214) Convert the given `extglob` pattern into a regex-compatible string. Returns an object with the compiled result and the parsed AST. **Params** * `str` **{String}** * `options` **{Object}** * `returns` **{String}** **Example** ```js var extglob = require('extglob'); console.log(extglob.create('*.!(*a)').output); //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?' ``` ### [.capture](index.js#L248) Returns an array of matches captured by `pattern` in `string`, or `null` if the pattern did not match. **Params** * `pattern` **{String}**: Glob pattern to use for matching. * `string` **{String}**: String to match * `options` **{Object}**: See available [options](#options) for changing how matches are performed * `returns` **{Boolean}**: Returns an array of captures if the string matches the glob pattern, otherwise `null`. **Example** ```js var extglob = require('extglob'); extglob.capture(pattern, string[, options]); console.log(extglob.capture('test/*.js', 'test/foo.js')); //=> ['foo'] console.log(extglob.capture('test/*.js', 'foo/bar.css')); //=> null ``` ### [.makeRe](index.js#L281) Create a regular expression from the given `pattern` and `options`. **Params** * `pattern` **{String}**: The pattern to convert to regex. * `options` **{Object}** * `returns` **{RegExp}** **Example** ```js var extglob = require('extglob'); var re = extglob.makeRe('*.!(*a)'); console.log(re); //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/ ``` ## Options Available options are based on the options from Bash (and the option names used in bash). ### options.nullglob **Type**: `boolean` **Default**: `undefined` When enabled, the pattern itself will be returned when no matches are found. ### options.nonull Alias for [options.nullglob](#optionsnullglob), included for parity with minimatch. ### options.cache **Type**: `boolean` **Default**: `undefined` Functions are memoized based on the given glob patterns and options. Disable memoization by setting `options.cache` to false. ### options.failglob **Type**: `boolean` **Default**: `undefined` Throw an error is no matches are found. ## Benchmarks Last run on December 21, 2017 ```sh # negation-nested (49 bytes) extglob x 2,228,255 ops/sec ±0.98% (89 runs sampled) minimatch x 207,875 ops/sec ±0.61% (91 runs sampled) fastest is extglob (by 1072% avg) # negation-simple (43 bytes) extglob x 2,205,668 ops/sec ±1.00% (91 runs sampled) minimatch x 311,923 ops/sec ±1.25% (91 runs sampled) fastest is extglob (by 707% avg) # range-false (57 bytes) extglob x 2,263,877 ops/sec ±0.40% (94 runs sampled) minimatch x 271,372 ops/sec ±1.02% (91 runs sampled) fastest is extglob (by 834% avg) # range-true (56 bytes) extglob x 2,161,891 ops/sec ±0.41% (92 runs sampled) minimatch x 268,265 ops/sec ±1.17% (91 runs sampled) fastest is extglob (by 806% avg) # star-simple (46 bytes) extglob x 2,211,081 ops/sec ±0.49% (92 runs sampled) minimatch x 343,319 ops/sec ±0.59% (91 runs sampled) fastest is extglob (by 644% avg) ``` ## Differences from Bash This library has complete parity with Bash 4.3 with only a couple of minor differences. * In some cases Bash returns true if the given string "contains" the pattern, whereas this library returns true if the string is an exact match for the pattern. You can relax this by setting `options.contains` to true. * This library is more accurate than Bash and thus does not fail some of the tests that Bash 4.3 still lists as failing in their unit tests ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [braces](https://www.npmjs.com/package/braces): Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support… [more](https://github.com/micromatch/braces) | [homepage](https://github.com/micromatch/braces "Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. Used by [micromatch].") * [fill-range](https://www.npmjs.com/package/fill-range): Fill in a range of numbers or letters, optionally passing an increment or `step` to… [more](https://github.com/jonschlinkert/fill-range) | [homepage](https://github.com/jonschlinkert/fill-range "Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex`") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/micromatch/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 49 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [isiahmeadows](https://github.com/isiahmeadows) | | 1 | [doowb](https://github.com/doowb) | | 1 | [devongovett](https://github.com/devongovett) | | 1 | [mjbvz](https://github.com/mjbvz) | | 1 | [shinnn](https://github.com/shinnn) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on December 21, 2017._ <hr class="footnotes-sep"> <section class="footnotes"> <ol class="footnotes-list"> <li id="fn1" class="footnote-item">`@` isn "'t a RegEx character." <a href="#fnref1" class="footnote-backref">↩</a> </li> </ol> </section> Port of the OpenBSD `bcrypt_pbkdf` function to pure Javascript. `npm`-ified version of [Devi Mandiri's port](https://github.com/devi/tmp/blob/master/js/bcrypt_pbkdf.js), with some minor performance improvements. The code is copied verbatim (and un-styled) from Devi's work. This product includes software developed by Niels Provos. ## API ### `bcrypt_pbkdf.pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds)` Derive a cryptographic key of arbitrary length from a given password and salt, using the OpenBSD `bcrypt_pbkdf` function. This is a combination of Blowfish and SHA-512. See [this article](http://www.tedunangst.com/flak/post/bcrypt-pbkdf) for further information. Parameters: * `pass`, a Uint8Array of length `passlen` * `passlen`, an integer Number * `salt`, a Uint8Array of length `saltlen` * `saltlen`, an integer Number * `key`, a Uint8Array of length `keylen`, will be filled with output * `keylen`, an integer Number * `rounds`, an integer Number, number of rounds of the PBKDF to run ### `bcrypt_pbkdf.hash(sha2pass, sha2salt, out)` Calculate a Blowfish hash, given SHA2-512 output of a password and salt. Used as part of the inner round function in the PBKDF. Parameters: * `sha2pass`, a Uint8Array of length 64 * `sha2salt`, a Uint8Array of length 64 * `out`, a Uint8Array of length 32, will be filled with output ## License This source form is a 1:1 port from the OpenBSD `blowfish.c` and `bcrypt_pbkdf.c`. As a result, it retains the original copyright and license. The two files are under slightly different (but compatible) licenses, and are here combined in one file. For each of the full license texts see `LICENSE`. # origin(al) [![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](http://img.shields.io/npm/v/original.svg?style=flat-square)](http://browsenpm.org/package/original)[![Build Status](http://img.shields.io/travis/unshiftio/original/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/original)[![Dependencies](https://img.shields.io/david/unshiftio/original.svg?style=flat-square)](https://david-dm.org/unshiftio/original)[![Coverage Status](http://img.shields.io/coveralls/unshiftio/original/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/original?branch=master)[![IRC channel](http://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](http://webchat.freenode.net/?channels=unshift) Original generates the origin URL for a given URL or URL object. In addition to that it also comes with a simple `same` function to check if two URL's have the same origin. ## Install This module is browserify and node compatible and is therefor release in the npm registry and can be installed using: ``` npm install --save original ``` ## Usage In all the examples we assume that the module is loaded using: ```js 'use strict'; var origin = require('original'); ``` To get the origin of a given URL simply call `origin` function with any given URL to get origin. ```js var o = origin('https://google.com/foo/bar?path'); // o = https://google.com ``` To compare if two URL's share the same origin you can call the `same` method. ```js if (origin.same('https://google.com/foo', 'https://primus.io')) { console.log('same'); } else { console.log('guess what, google.com and primus.io are not the same origin'); } ``` And that's it. ## License MIT # xtend [![browser support][3]][4] [![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) Extend like a boss xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. ## Examples ```js var extend = require("xtend") // extend returns a new object. Does not mutate arguments var combination = extend({ a: "a", b: 'c' }, { b: "b" }) // { a: "a", b: "b" } ``` ## Stability status: Locked ## MIT Licenced [3]: http://ci.testling.com/Raynos/xtend.png [4]: http://ci.testling.com/Raynos/xtend # json-stringify-safe Like JSON.stringify, but doesn't throw on circular references. ## Usage Takes the same arguments as `JSON.stringify`. ```javascript var stringify = require('json-stringify-safe'); var circularObj = {}; circularObj.circularRef = circularObj; circularObj.list = [ circularObj, circularObj ]; console.log(stringify(circularObj, null, 2)); ``` Output: ```json { "circularRef": "[Circular]", "list": [ "[Circular]", "[Circular]" ] } ``` ## Details ``` stringify(obj, serializer, indent, decycler) ``` The first three arguments are the same as to JSON.stringify. The last is an argument that's only used when the object has been seen already. The default `decycler` function returns the string `'[Circular]'`. If, for example, you pass in `function(k,v){}` (return nothing) then it will prune cycles. If you pass in `function(k,v){ return {foo: 'bar'}}`, then cyclical objects will always be represented as `{"foo":"bar"}` in the result. ``` stringify.getSerialize(serializer, decycler) ``` Returns a serializer that can be used elsewhere. This is the actual function that's passed to JSON.stringify. **Note** that the function returned from `getSerialize` is stateful for now, so do **not** use it more than once. Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # Async.js [![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) [![NPM version](http://img.shields.io/npm/v/async.svg)](https://www.npmjs.org/package/async) [![Coverage Status](https://coveralls.io/repos/caolan/async/badge.svg?branch=master)](https://coveralls.io/r/caolan/async?branch=master) [![Join the chat at https://gitter.im/caolan/async](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/caolan/async?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with [Node.js](http://nodejs.org) and installable via `npm install async`, it can also be used directly in the browser. Async is also installable via: - [bower](http://bower.io/): `bower install async` - [component](https://github.com/component/component): `component install caolan/async` - [jam](http://jamjs.org/): `jam install async` - [spm](http://spmjs.io/): `spm install async` Async provides around 20 functions that include the usual 'functional' suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these functions assume you follow the Node.js convention of providing a single callback as the last argument of your `async` function. ## Quick Examples ```javascript async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); async.filter(['file1','file2','file3'], fs.exists, function(results){ // results now equals an array of the existing files }); async.parallel([ function(){ ... }, function(){ ... } ], callback); async.series([ function(){ ... }, function(){ ... } ]); ``` There are many more functions available so take a look at the docs below for a full list. This module aims to be comprehensive, so if you feel anything is missing please create a GitHub issue for it. ## Common Pitfalls <sub>[(StackOverflow)](http://stackoverflow.com/questions/tagged/async.js)</sub> ### Synchronous iteration functions If you get an error like `RangeError: Maximum call stack size exceeded.` or other stack overflow issues when using async, you are likely using a synchronous iterator. By *synchronous* we mean a function that calls its callback on the same tick in the javascript event loop, without doing any I/O or using any timers. Calling many callbacks iteratively will quickly overflow the stack. If you run into this issue, just defer your callback with `async.setImmediate` to start a new call stack on the next tick of the event loop. This can also arise by accident if you callback early in certain cases: ```js async.eachSeries(hugeArray, function iterator(item, callback) { if (inCache(item)) { callback(null, cache[item]); // if many items are cached, you'll overflow } else { doSomeIO(item, callback); } }, function done() { //... }); ``` Just change it to: ```js async.eachSeries(hugeArray, function iterator(item, callback) { if (inCache(item)) { async.setImmediate(function () { callback(null, cache[item]); }); } else { doSomeIO(item, callback); //... ``` Async guards against synchronous functions in some, but not all, cases. If you are still running into stack overflows, you can defer as suggested above, or wrap functions with [`async.ensureAsync`](#ensureAsync) Functions that are asynchronous by their nature do not have this problem and don't need the extra callback deferral. If JavaScript's event loop is still a bit nebulous, check out [this article](http://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/) or [this talk](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html) for more detailed information about how it works. ### Multiple callbacks Make sure to always `return` when calling a callback early, otherwise you will cause multiple callbacks and unpredictable behavior in many cases. ```js async.waterfall([ function (callback) { getSomething(options, function (err, result) { if (err) { callback(new Error("failed getting something:" + err.message)); // we should return here } // since we did not return, this callback still will be called and // `processData` will be called twice callback(null, result); }); }, processData ], done) ``` It is always good practice to `return callback(err, result)` whenever a callback call is not the last statement of a function. ### Binding a context to an iterator This section is really about `bind`, not about `async`. If you are wondering how to make `async` execute your iterators in a given context, or are confused as to why a method of another library isn't working as an iterator, study this example: ```js // Here is a simple object with an (unnecessarily roundabout) squaring method var AsyncSquaringLibrary = { squareExponent: 2, square: function(number, callback){ var result = Math.pow(number, this.squareExponent); setTimeout(function(){ callback(null, result); }, 200); } }; async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ // result is [NaN, NaN, NaN] // This fails because the `this.squareExponent` expression in the square // function is not evaluated in the context of AsyncSquaringLibrary, and is // therefore undefined. }); async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ // result is [1, 4, 9] // With the help of bind we can attach a context to the iterator before // passing it to async. Now the square function will be executed in its // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` // will be as expected. }); ``` ## Download The source is available for download from [GitHub](https://github.com/caolan/async/blob/master/lib/async.js). Alternatively, you can install using Node Package Manager (`npm`): npm install async As well as using Bower: bower install async __Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed ## In the Browser So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage: ```html <script type="text/javascript" src="async.js"></script> <script type="text/javascript"> async.map(data, asyncProcess, function(err, results){ alert(results); }); </script> ``` ## Documentation Some functions are also available in the following forms: * `<name>Series` - the same as `<name>` but runs only a single async operation at a time * `<name>Limit` - the same as `<name>` but runs a maximum of `limit` async operations at a time ### Collections * [`each`](#each), `eachSeries`, `eachLimit` * [`forEachOf`](#forEachOf), `forEachOfSeries`, `forEachOfLimit` * [`map`](#map), `mapSeries`, `mapLimit` * [`filter`](#filter), `filterSeries`, `filterLimit` * [`reject`](#reject), `rejectSeries`, `rejectLimit` * [`reduce`](#reduce), [`reduceRight`](#reduceRight) * [`detect`](#detect), `detectSeries`, `detectLimit` * [`sortBy`](#sortBy) * [`some`](#some), `someLimit` * [`every`](#every), `everyLimit` * [`concat`](#concat), `concatSeries` ### Control Flow * [`series`](#seriestasks-callback) * [`parallel`](#parallel), `parallelLimit` * [`whilst`](#whilst), [`doWhilst`](#doWhilst) * [`until`](#until), [`doUntil`](#doUntil) * [`during`](#during), [`doDuring`](#doDuring) * [`forever`](#forever) * [`waterfall`](#waterfall) * [`compose`](#compose) * [`seq`](#seq) * [`applyEach`](#applyEach), `applyEachSeries` * [`queue`](#queue), [`priorityQueue`](#priorityQueue) * [`cargo`](#cargo) * [`auto`](#auto) * [`retry`](#retry) * [`iterator`](#iterator) * [`times`](#times), `timesSeries`, `timesLimit` ### Utils * [`apply`](#apply) * [`nextTick`](#nextTick) * [`memoize`](#memoize) * [`unmemoize`](#unmemoize) * [`ensureAsync`](#ensureAsync) * [`constant`](#constant) * [`asyncify`](#asyncify) * [`wrapSync`](#wrapSync) * [`log`](#log) * [`dir`](#dir) * [`noConflict`](#noConflict) ## Collections <a name="forEach" /> <a name="each" /> ### each(arr, iterator, [callback]) Applies the function `iterator` to each item in `arr`, in parallel. The `iterator` is called with an item from the list, and a callback for when it has finished. If the `iterator` passes an error to its `callback`, the main `callback` (for the `each` function) is immediately called with the error. Note, that since this function applies `iterator` to each item in parallel, there is no guarantee that the iterator functions will complete in order. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A function to apply to each item in `arr`. The iterator is passed a `callback(err)` which must be called once it has completed. If no error has occurred, the `callback` should be run without arguments or with an explicit `null` argument. The array index is not passed to the iterator. If you need the index, use [`forEachOf`](#forEachOf). * `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. __Examples__ ```js // assuming openFiles is an array of file names and saveFile is a function // to save the modified contents of that file: async.each(openFiles, saveFile, function(err){ // if any of the saves produced an error, err would equal that error }); ``` ```js // assuming openFiles is an array of file names async.each(openFiles, function(file, callback) { // Perform operation on file here. console.log('Processing file ' + file); if( file.length > 32 ) { console.log('This file name is too long'); callback('File name too long'); } else { // Do work to process file here console.log('File processed'); callback(); } }, function(err){ // if any of the file processing produced an error, err would equal that error if( err ) { // One of the iterations produced an error. // All processing will now stop. console.log('A file failed to process'); } else { console.log('All files have been processed successfully'); } }); ``` __Related__ * eachSeries(arr, iterator, [callback]) * eachLimit(arr, limit, iterator, [callback]) --------------------------------------- <a name="forEachOf" /> <a name="eachOf" /> ### forEachOf(obj, iterator, [callback]) Like `each`, except that it iterates over objects, and passes the key as the second argument to the iterator. __Arguments__ * `obj` - An object or array to iterate over. * `iterator(item, key, callback)` - A function to apply to each item in `obj`. The `key` is the item's key, or index in the case of an array. The iterator is passed a `callback(err)` which must be called once it has completed. If no error has occurred, the callback should be run without arguments or with an explicit `null` argument. * `callback(err)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. __Example__ ```js var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; var configs = {}; async.forEachOf(obj, function (value, key, callback) { fs.readFile(__dirname + value, "utf8", function (err, data) { if (err) return callback(err); try { configs[key] = JSON.parse(data); } catch (e) { return callback(e); } callback(); }) }, function (err) { if (err) console.error(err.message); // configs is now a map of JSON data doSomethingWith(configs); }) ``` __Related__ * forEachOfSeries(obj, iterator, [callback]) * forEachOfLimit(obj, limit, iterator, [callback]) --------------------------------------- <a name="map" /> ### map(arr, iterator, [callback]) Produces a new array of values by mapping each value in `arr` through the `iterator` function. The `iterator` is called with an item from `arr` and a callback for when it has finished processing. Each of these callback takes 2 arguments: an `error`, and the transformed item from `arr`. If `iterator` passes an error to its callback, the main `callback` (for the `map` function) is immediately called with the error. Note, that since this function applies the `iterator` to each item in parallel, there is no guarantee that the `iterator` functions will complete in order. However, the results array will be in the same order as the original `arr`. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A function to apply to each item in `arr`. The iterator is passed a `callback(err, transformed)` which must be called once it has completed with an error (which can be `null`) and a transformed item. * `callback(err, results)` - *Optional* A callback which is called when all `iterator` functions have finished, or an error occurs. Results is an array of the transformed items from the `arr`. __Example__ ```js async.map(['file1','file2','file3'], fs.stat, function(err, results){ // results is now an array of stats for each file }); ``` __Related__ * mapSeries(arr, iterator, [callback]) * mapLimit(arr, limit, iterator, [callback]) --------------------------------------- <a name="select" /> <a name="filter" /> ### filter(arr, iterator, [callback]) __Alias:__ `select` Returns a new array of all the values in `arr` which pass an async truth test. _The callback for each `iterator` call only accepts a single argument of `true` or `false`; it does not accept an error argument first!_ This is in-line with the way node libraries work with truth tests like `fs.exists`. This operation is performed in parallel, but the results array will be in the same order as the original. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A truth test to apply to each item in `arr`. The `iterator` is passed a `callback(truthValue)`, which must be called with a boolean argument once it has completed. * `callback(results)` - *Optional* A callback which is called after all the `iterator` functions have finished. __Example__ ```js async.filter(['file1','file2','file3'], fs.exists, function(results){ // results now equals an array of the existing files }); ``` __Related__ * filterSeries(arr, iterator, [callback]) * filterLimit(arr, limit, iterator, [callback]) --------------------------------------- <a name="reject" /> ### reject(arr, iterator, [callback]) The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. __Related__ * rejectSeries(arr, iterator, [callback]) * rejectLimit(arr, limit, iterator, [callback]) --------------------------------------- <a name="reduce" /> ### reduce(arr, memo, iterator, [callback]) __Aliases:__ `inject`, `foldl` Reduces `arr` into a single value using an async `iterator` to return each successive step. `memo` is the initial state of the reduction. This function only operates in series. For performance reasons, it may make sense to split a call to this function into a parallel map, and then use the normal `Array.prototype.reduce` on the results. This function is for situations where each step in the reduction needs to be async; if you can get the data before reducing it, then it's probably a good idea to do so. __Arguments__ * `arr` - An array to iterate over. * `memo` - The initial state of the reduction. * `iterator(memo, item, callback)` - A function applied to each item in the array to produce the next step in the reduction. The `iterator` is passed a `callback(err, reduction)` which accepts an optional error as its first argument, and the state of the reduction as the second. If an error is passed to the callback, the reduction is stopped and the main `callback` is immediately called with the error. * `callback(err, result)` - *Optional* A callback which is called after all the `iterator` functions have finished. Result is the reduced value. __Example__ ```js async.reduce([1,2,3], 0, function(memo, item, callback){ // pointless async: process.nextTick(function(){ callback(null, memo + item) }); }, function(err, result){ // result is now equal to the last value of memo, which is 6 }); ``` --------------------------------------- <a name="reduceRight" /> ### reduceRight(arr, memo, iterator, [callback]) __Alias:__ `foldr` Same as [`reduce`](#reduce), only operates on `arr` in reverse order. --------------------------------------- <a name="detect" /> ### detect(arr, iterator, [callback]) Returns the first value in `arr` that passes an async truth test. The `iterator` is applied in parallel, meaning the first iterator to return `true` will fire the detect `callback` with that result. That means the result might not be the first item in the original `arr` (in terms of order) that passes the test. If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A truth test to apply to each item in `arr`. The iterator is passed a `callback(truthValue)` which must be called with a boolean argument once it has completed. **Note: this callback does not take an error as its first argument.** * `callback(result)` - *Optional* A callback which is called as soon as any iterator returns `true`, or after all the `iterator` functions have finished. Result will be the first item in the array that passes the truth test (iterator) or the value `undefined` if none passed. **Note: this callback does not take an error as its first argument.** __Example__ ```js async.detect(['file1','file2','file3'], fs.exists, function(result){ // result now equals the first file in the list that exists }); ``` __Related__ * detectSeries(arr, iterator, [callback]) * detectLimit(arr, limit, iterator, [callback]) --------------------------------------- <a name="sortBy" /> ### sortBy(arr, iterator, [callback]) Sorts a list by the results of running each `arr` value through an async `iterator`. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A function to apply to each item in `arr`. The iterator is passed a `callback(err, sortValue)` which must be called once it has completed with an error (which can be `null`) and a value to use as the sort criteria. * `callback(err, results)` - *Optional* A callback which is called after all the `iterator` functions have finished, or an error occurs. Results is the items from the original `arr` sorted by the values returned by the `iterator` calls. __Example__ ```js async.sortBy(['file1','file2','file3'], function(file, callback){ fs.stat(file, function(err, stats){ callback(err, stats.mtime); }); }, function(err, results){ // results is now the original array of files sorted by // modified date }); ``` __Sort Order__ By modifying the callback parameter the sorting order can be influenced: ```js //ascending order async.sortBy([1,9,3,5], function(x, callback){ callback(null, x); }, function(err,result){ //result callback } ); //descending order async.sortBy([1,9,3,5], function(x, callback){ callback(null, x*-1); //<- x*-1 instead of x, turns the order around }, function(err,result){ //result callback } ); ``` --------------------------------------- <a name="some" /> ### some(arr, iterator, [callback]) __Alias:__ `any` Returns `true` if at least one element in the `arr` satisfies an async test. _The callback for each iterator call only accepts a single argument of `true` or `false`; it does not accept an error argument first!_ This is in-line with the way node libraries work with truth tests like `fs.exists`. Once any iterator call returns `true`, the main `callback` is immediately called. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A truth test to apply to each item in the array in parallel. The iterator is passed a `callback(truthValue)`` which must be called with a boolean argument once it has completed. * `callback(result)` - *Optional* A callback which is called as soon as any iterator returns `true`, or after all the iterator functions have finished. Result will be either `true` or `false` depending on the values of the async tests. **Note: the callbacks do not take an error as their first argument.** __Example__ ```js async.some(['file1','file2','file3'], fs.exists, function(result){ // if result is true then at least one of the files exists }); ``` __Related__ * someLimit(arr, limit, iterator, callback) --------------------------------------- <a name="every" /> ### every(arr, iterator, [callback]) __Alias:__ `all` Returns `true` if every element in `arr` satisfies an async test. _The callback for each `iterator` call only accepts a single argument of `true` or `false`; it does not accept an error argument first!_ This is in-line with the way node libraries work with truth tests like `fs.exists`. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A truth test to apply to each item in the array in parallel. The iterator is passed a `callback(truthValue)` which must be called with a boolean argument once it has completed. * `callback(result)` - *Optional* A callback which is called as soon as any iterator returns `false`, or after all the iterator functions have finished. Result will be either `true` or `false` depending on the values of the async tests. **Note: the callbacks do not take an error as their first argument.** __Example__ ```js async.every(['file1','file2','file3'], fs.exists, function(result){ // if result is true then every file exists }); ``` __Related__ * everyLimit(arr, limit, iterator, callback) --------------------------------------- <a name="concat" /> ### concat(arr, iterator, [callback]) Applies `iterator` to each item in `arr`, concatenating the results. Returns the concatenated list. The `iterator`s are called in parallel, and the results are concatenated as they return. There is no guarantee that the results array will be returned in the original order of `arr` passed to the `iterator` function. __Arguments__ * `arr` - An array to iterate over. * `iterator(item, callback)` - A function to apply to each item in `arr`. The iterator is passed a `callback(err, results)` which must be called once it has completed with an error (which can be `null`) and an array of results. * `callback(err, results)` - *Optional* A callback which is called after all the `iterator` functions have finished, or an error occurs. Results is an array containing the concatenated results of the `iterator` function. __Example__ ```js async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ // files is now a list of filenames that exist in the 3 directories }); ``` __Related__ * concatSeries(arr, iterator, [callback]) ## Control Flow <a name="series" /> ### series(tasks, [callback]) Run the functions in the `tasks` array in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run, and `callback` is immediately called with the value of the error. Otherwise, `callback` receives an array of results when `tasks` have completed. It is also possible to use an object instead of an array. Each property will be run as a function, and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling results from [`series`](#series). **Note** that while many implementations preserve the order of object properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) explicitly states that > The mechanics and order of enumerating the properties is not specified. So if you rely on the order in which your series of functions are executed, and want this to work on all platforms, consider using an array. __Arguments__ * `tasks` - An array or object containing functions to run, each function is passed a `callback(err, result)` it must call on completion with an error `err` (which can be `null`) and an optional `result` value. * `callback(err, results)` - An optional callback to run once all the functions have completed. This function gets a results array (or object) containing all the result arguments passed to the `task` callbacks. __Example__ ```js async.series([ function(callback){ // do some stuff ... callback(null, 'one'); }, function(callback){ // do some more stuff ... callback(null, 'two'); } ], // optional callback function(err, results){ // results is now equal to ['one', 'two'] }); // an example using an object instead of an array async.series({ one: function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } }, function(err, results) { // results is now equal to: {one: 1, two: 2} }); ``` --------------------------------------- <a name="parallel" /> ### parallel(tasks, [callback]) Run the `tasks` array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main `callback` is immediately called with the value of the error. Once the `tasks` have completed, the results are passed to the final `callback` as an array. **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded. It is also possible to use an object instead of an array. Each property will be run as a function and the results will be passed to the final `callback` as an object instead of an array. This can be a more readable way of handling results from [`parallel`](#parallel). __Arguments__ * `tasks` - An array or object containing functions to run. Each function is passed a `callback(err, result)` which it must call on completion with an error `err` (which can be `null`) and an optional `result` value. * `callback(err, results)` - An optional callback to run once all the functions have completed successfully. This function gets a results array (or object) containing all the result arguments passed to the task callbacks. __Example__ ```js async.parallel([ function(callback){ setTimeout(function(){ callback(null, 'one'); }, 200); }, function(callback){ setTimeout(function(){ callback(null, 'two'); }, 100); } ], // optional callback function(err, results){ // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }); // an example using an object instead of an array async.parallel({ one: function(callback){ setTimeout(function(){ callback(null, 1); }, 200); }, two: function(callback){ setTimeout(function(){ callback(null, 2); }, 100); } }, function(err, results) { // results is now equals to: {one: 1, two: 2} }); ``` __Related__ * parallelLimit(tasks, limit, [callback]) --------------------------------------- <a name="whilst" /> ### whilst(test, fn, callback) Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, or an error occurs. __Arguments__ * `test()` - synchronous truth test to perform before each execution of `fn`. * `fn(callback)` - A function which is called each time `test` passes. The function is passed a `callback(err)`, which must be called once it has completed with an optional `err` argument. * `callback(err, [results])` - A callback which is called after the test function has failed and repeated execution of `fn` has stopped. `callback` will be passed an error and any arguments passed to the final `fn`'s callback. __Example__ ```js var count = 0; async.whilst( function () { return count < 5; }, function (callback) { count++; setTimeout(function () { callback(null, count); }, 1000); }, function (err, n) { // 5 seconds have passed, n = 5 } ); ``` --------------------------------------- <a name="doWhilst" /> ### doWhilst(fn, test, callback) The post-check version of [`whilst`](#whilst). To reflect the difference in the order of operations, the arguments `test` and `fn` are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. --------------------------------------- <a name="until" /> ### until(test, fn, callback) Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, or an error occurs. `callback` will be passed an error and any arguments passed to the final `fn`'s callback. The inverse of [`whilst`](#whilst). --------------------------------------- <a name="doUntil" /> ### doUntil(fn, test, callback) Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. --------------------------------------- <a name="during" /> ### during(test, fn, callback) Like [`whilst`](#whilst), except the `test` is an asynchronous function that is passed a callback in the form of `function (err, truth)`. If error is passed to `test` or `fn`, the main callback is immediately called with the value of the error. __Example__ ```js var count = 0; async.during( function (callback) { return callback(null, count < 5); }, function (callback) { count++; setTimeout(callback, 1000); }, function (err) { // 5 seconds have passed } ); ``` --------------------------------------- <a name="doDuring" /> ### doDuring(fn, test, callback) The post-check version of [`during`](#during). To reflect the difference in the order of operations, the arguments `test` and `fn` are switched. Also a version of [`doWhilst`](#doWhilst) with asynchronous `test` function. --------------------------------------- <a name="forever" /> ### forever(fn, [errback]) Calls the asynchronous function `fn` with a callback parameter that allows it to call itself again, in series, indefinitely. If an error is passed to the callback then `errback` is called with the error, and execution stops, otherwise it will never be called. ```js async.forever( function(next) { // next is suitable for passing to things that need a callback(err [, whatever]); // it will result in this function being called again. }, function(err) { // if next is called with a value in its first parameter, it will appear // in here as 'err', and execution will stop. } ); ``` --------------------------------------- <a name="waterfall" /> ### waterfall(tasks, [callback]) Runs the `tasks` array of functions in series, each passing their results to the next in the array. However, if any of the `tasks` pass an error to their own callback, the next function is not executed, and the main `callback` is immediately called with the error. __Arguments__ * `tasks` - An array of functions to run, each function is passed a `callback(err, result1, result2, ...)` it must call on completion. The first argument is an error (which can be `null`) and any further arguments will be passed as arguments in order to the next task. * `callback(err, [results])` - An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback. __Example__ ```js async.waterfall([ function(callback) { callback(null, 'one', 'two'); }, function(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); }, function(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ], function (err, result) { // result now equals 'done' }); ``` Or, with named functions: ```js async.waterfall([ myFirstFunction, mySecondFunction, myLastFunction, ], function (err, result) { // result now equals 'done' }); function myFirstFunction(callback) { callback(null, 'one', 'two'); } function mySecondFunction(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); } function myLastFunction(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ``` Or, if you need to pass any argument to the first function: ```js async.waterfall([ async.apply(myFirstFunction, 'zero'), mySecondFunction, myLastFunction, ], function (err, result) { // result now equals 'done' }); function myFirstFunction(arg1, callback) { // arg1 now equals 'zero' callback(null, 'one', 'two'); } function mySecondFunction(arg1, arg2, callback) { // arg1 now equals 'one' and arg2 now equals 'two' callback(null, 'three'); } function myLastFunction(arg1, callback) { // arg1 now equals 'three' callback(null, 'done'); } ``` --------------------------------------- <a name="compose" /> ### compose(fn1, fn2...) Creates a function which is a composition of the passed asynchronous functions. Each function consumes the return value of the function that follows. Composing functions `f()`, `g()`, and `h()` would produce the result of `f(g(h()))`, only this version uses callbacks to obtain the return values. Each function is executed with the `this` binding of the composed function. __Arguments__ * `functions...` - the asynchronous functions to compose __Example__ ```js function add1(n, callback) { setTimeout(function () { callback(null, n + 1); }, 10); } function mul3(n, callback) { setTimeout(function () { callback(null, n * 3); }, 10); } var add1mul3 = async.compose(mul3, add1); add1mul3(4, function (err, result) { // result now equals 15 }); ``` --------------------------------------- <a name="seq" /> ### seq(fn1, fn2...) Version of the compose function that is more natural to read. Each function consumes the return value of the previous function. It is the equivalent of [`compose`](#compose) with the arguments reversed. Each function is executed with the `this` binding of the composed function. __Arguments__ * `functions...` - the asynchronous functions to compose __Example__ ```js // Requires lodash (or underscore), express3 and dresende's orm2. // Part of an app, that fetches cats of the logged user. // This example uses `seq` function to avoid overnesting and error // handling clutter. app.get('/cats', function(request, response) { var User = request.models.User; async.seq( _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) function(user, fn) { user.getCats(fn); // 'getCats' has signature (callback(err, data)) } )(req.session.user_id, function (err, cats) { if (err) { console.error(err); response.json({ status: 'error', message: err.message }); } else { response.json({ status: 'ok', message: 'Cats found', data: cats }); } }); }); ``` --------------------------------------- <a name="applyEach" /> ### applyEach(fns, args..., callback) Applies the provided arguments to each function in the array, calling `callback` after all functions have completed. If you only provide the first argument, then it will return a function which lets you pass in the arguments as if it were a single function call. __Arguments__ * `fns` - the asynchronous functions to all call with the same arguments * `args...` - any number of separate arguments to pass to the function * `callback` - the final argument should be the callback, called when all functions have completed processing __Example__ ```js async.applyEach([enableSearch, updateSchema], 'bucket', callback); // partial application example: async.each( buckets, async.applyEach([enableSearch, updateSchema]), callback ); ``` __Related__ * applyEachSeries(tasks, args..., [callback]) --------------------------------------- <a name="queue" /> ### queue(worker, [concurrency]) Creates a `queue` object with the specified `concurrency`. Tasks added to the `queue` are processed in parallel (up to the `concurrency` limit). If all `worker`s are in progress, the task is queued until one becomes available. Once a `worker` completes a `task`, that `task`'s callback is called. __Arguments__ * `worker(task, callback)` - An asynchronous function for processing a queued task, which must call its `callback(err)` argument when finished, with an optional `error` as an argument. If you want to handle errors from an individual task, pass a callback to `q.push()`. * `concurrency` - An `integer` for determining how many `worker` functions should be run in parallel. If omitted, the concurrency defaults to `1`. If the concurrency is `0`, an error is thrown. __Queue objects__ The `queue` object returned by this function has the following properties and methods: * `length()` - a function returning the number of items waiting to be processed. * `started` - a function returning whether or not any items have been pushed and processed by the queue * `running()` - a function returning the number of items currently being processed. * `workersList()` - a function returning the array of items currently being processed. * `idle()` - a function returning false if there are items waiting or being processed, or true if not. * `concurrency` - an integer for determining how many `worker` functions should be run in parallel. This property can be changed after a `queue` is created to alter the concurrency on-the-fly. * `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once the `worker` has finished processing the task. Instead of a single task, a `tasks` array can be submitted. The respective callback is used for every task in the list. * `unshift(task, [callback])` - add a new task to the front of the `queue`. * `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, and further tasks will be queued. * `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. * `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. * `paused` - a boolean for determining whether the queue is in a paused state * `pause()` - a function that pauses the processing of tasks until `resume()` is called. * `resume()` - a function that resumes the processing of queued tasks when the queue is paused. * `kill()` - a function that removes the `drain` callback and empties remaining tasks from the queue forcing it to go idle. __Example__ ```js // create a queue object with concurrency 2 var q = async.queue(function (task, callback) { console.log('hello ' + task.name); callback(); }, 2); // assign a callback q.drain = function() { console.log('all items have been processed'); } // add some items to the queue q.push({name: 'foo'}, function (err) { console.log('finished processing foo'); }); q.push({name: 'bar'}, function (err) { console.log('finished processing bar'); }); // add some items to the queue (batch-wise) q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { console.log('finished processing item'); }); // add some items to the front of the queue q.unshift({name: 'bar'}, function (err) { console.log('finished processing bar'); }); ``` --------------------------------------- <a name="priorityQueue" /> ### priorityQueue(worker, concurrency) The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: * `push(task, priority, [callback])` - `priority` should be a number. If an array of `tasks` is given, all tasks will be assigned the same priority. * The `unshift` method was removed. --------------------------------------- <a name="cargo" /> ### cargo(worker, [payload]) Creates a `cargo` object with the specified payload. Tasks added to the cargo will be processed altogether (up to the `payload` limit). If the `worker` is in progress, the task is queued until it becomes available. Once the `worker` has completed some tasks, each callback of those tasks is called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) for how `cargo` and `queue` work. While [queue](#queue) passes only one task to one of a group of workers at a time, cargo passes an array of tasks to a single worker, repeating when the worker is finished. __Arguments__ * `worker(tasks, callback)` - An asynchronous function for processing an array of queued tasks, which must call its `callback(err)` argument when finished, with an optional `err` argument. * `payload` - An optional `integer` for determining how many tasks should be processed per round; if omitted, the default is unlimited. __Cargo objects__ The `cargo` object returned by this function has the following properties and methods: * `length()` - A function returning the number of items waiting to be processed. * `payload` - An `integer` for determining how many tasks should be process per round. This property can be changed after a `cargo` is created to alter the payload on-the-fly. * `push(task, [callback])` - Adds `task` to the `queue`. The callback is called once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` can be submitted. The respective callback is used for every task in the list. * `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. * `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. * `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. * `idle()`, `pause()`, `resume()`, `kill()` - cargo inherits all of the same methods and event calbacks as [`queue`](#queue) __Example__ ```js // create a cargo object with payload 2 var cargo = async.cargo(function (tasks, callback) { for(var i=0; i<tasks.length; i++){ console.log('hello ' + tasks[i].name); } callback(); }, 2); // add some items cargo.push({name: 'foo'}, function (err) { console.log('finished processing foo'); }); cargo.push({name: 'bar'}, function (err) { console.log('finished processing bar'); }); cargo.push({name: 'baz'}, function (err) { console.log('finished processing baz'); }); ``` --------------------------------------- <a name="auto" /> ### auto(tasks, [concurrency], [callback]) Determines the best order for running the functions in `tasks`, based on their requirements. Each function can optionally depend on other functions being completed first, and each function is run as soon as its requirements are satisfied. If any of the functions pass an error to their callback, the `auto` sequence will stop. Further tasks will not execute (so any other functions depending on it will not run), and the main `callback` is immediately called with the error. Functions also receive an object containing the results of functions which have completed so far. Note, all functions are called with a `results` object as a second argument, so it is unsafe to pass functions in the `tasks` object which cannot handle the extra argument. For example, this snippet of code: ```js async.auto({ readData: async.apply(fs.readFile, 'data.txt', 'utf-8') }, callback); ``` will have the effect of calling `readFile` with the results object as the last argument, which will fail: ```js fs.readFile('data.txt', 'utf-8', cb, {}); ``` Instead, wrap the call to `readFile` in a function which does not forward the `results` object: ```js async.auto({ readData: function(cb, results){ fs.readFile('data.txt', 'utf-8', cb); } }, callback); ``` __Arguments__ * `tasks` - An object. Each of its properties is either a function or an array of requirements, with the function itself the last item in the array. The object's key of a property serves as the name of the task defined by that property, i.e. can be used when specifying requirements for other tasks. The function receives two arguments: (1) a `callback(err, result)` which must be called when finished, passing an `error` (which can be `null`) and the result of the function's execution, and (2) a `results` object, containing the results of the previously executed functions. * `concurrency` - An optional `integer` for determining the maximum number of tasks that can be run in parallel. By default, as many as possible. * `callback(err, results)` - An optional callback which is called when all the tasks have been completed. It receives the `err` argument if any `tasks` pass an error to their callback. Results are always returned; however, if an error occurs, no further `tasks` will be performed, and the results object will only contain partial results. __Example__ ```js async.auto({ get_data: function(callback){ console.log('in get_data'); // async code to get some data callback(null, 'data', 'converted to array'); }, make_folder: function(callback){ console.log('in make_folder'); // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); }, write_file: ['get_data', 'make_folder', function(callback, results){ console.log('in write_file', JSON.stringify(results)); // once there is some data and the directory exists, // write the data to a file in the directory callback(null, 'filename'); }], email_link: ['write_file', function(callback, results){ console.log('in email_link', JSON.stringify(results)); // once the file is written let's email a link to it... // results.write_file contains the filename returned by write_file. callback(null, {'file':results.write_file, 'email':'[email protected]'}); }] }, function(err, results) { console.log('err = ', err); console.log('results = ', results); }); ``` This is a fairly trivial example, but to do this using the basic parallel and series functions would look like this: ```js async.parallel([ function(callback){ console.log('in get_data'); // async code to get some data callback(null, 'data', 'converted to array'); }, function(callback){ console.log('in make_folder'); // async code to create a directory to store a file in // this is run at the same time as getting the data callback(null, 'folder'); } ], function(err, results){ async.series([ function(callback){ console.log('in write_file', JSON.stringify(results)); // once there is some data and the directory exists, // write the data to a file in the directory results.push('filename'); callback(null); }, function(callback){ console.log('in email_link', JSON.stringify(results)); // once the file is written let's email a link to it... callback(null, {'file':results.pop(), 'email':'[email protected]'}); } ]); }); ``` For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding new tasks much easier (and the code more readable). --------------------------------------- <a name="retry" /> ### retry([opts = {times: 5, interval: 0}| 5], task, [callback]) Attempts to get a successful response from `task` no more than `times` times before returning an error. If the task is successful, the `callback` will be passed the result of the successful task. If all attempts fail, the callback will be passed the error and result (if any) of the final attempt. __Arguments__ * `opts` - Can be either an object with `times` and `interval` or a number. * `times` - The number of attempts to make before giving up. The default is `5`. * `interval` - The time to wait between retries, in milliseconds. The default is `0`. * If `opts` is a number, the number specifies the number of times to retry, with the default interval of `0`. * `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` which must be called when finished, passing `err` (which can be `null`) and the `result` of the function's execution, and (2) a `results` object, containing the results of the previously executed functions (if nested inside another control flow). * `callback(err, results)` - An optional callback which is called when the task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. The [`retry`](#retry) function can be used as a stand-alone control flow by passing a callback, as shown below: ```js // try calling apiMethod 3 times async.retry(3, apiMethod, function(err, result) { // do something with the result }); ``` ```js // try calling apiMethod 3 times, waiting 200 ms between each retry async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { // do something with the result }); ``` ```js // try calling apiMethod the default 5 times no delay between each retry async.retry(apiMethod, function(err, result) { // do something with the result }); ``` It can also be embedded within other control flow functions to retry individual methods that are not as reliable, like this: ```js async.auto({ users: api.getUsers.bind(api), payments: async.retry(3, api.getPayments.bind(api)) }, function(err, results) { // do something with the results }); ``` --------------------------------------- <a name="iterator" /> ### iterator(tasks) Creates an iterator function which calls the next function in the `tasks` array, returning a continuation to call the next one after that. It's also possible to “peek” at the next iterator with `iterator.next()`. This function is used internally by the `async` module, but can be useful when you want to manually control the flow of functions in series. __Arguments__ * `tasks` - An array of functions to run. __Example__ ```js var iterator = async.iterator([ function(){ sys.p('one'); }, function(){ sys.p('two'); }, function(){ sys.p('three'); } ]); node> var iterator2 = iterator(); 'one' node> var iterator3 = iterator2(); 'two' node> iterator3(); 'three' node> var nextfn = iterator2.next(); node> nextfn(); 'three' ``` --------------------------------------- <a name="apply" /> ### apply(function, arguments..) Creates a continuation function with some arguments already applied. Useful as a shorthand when combined with other control flow functions. Any arguments passed to the returned function are added to the arguments originally passed to apply. __Arguments__ * `function` - The function you want to eventually apply all arguments to. * `arguments...` - Any number of arguments to automatically apply when the continuation is called. __Example__ ```js // using apply async.parallel([ async.apply(fs.writeFile, 'testfile1', 'test1'), async.apply(fs.writeFile, 'testfile2', 'test2'), ]); // the same process without using apply async.parallel([ function(callback){ fs.writeFile('testfile1', 'test1', callback); }, function(callback){ fs.writeFile('testfile2', 'test2', callback); } ]); ``` It's possible to pass any number of additional arguments when calling the continuation: ```js node> var fn = async.apply(sys.puts, 'one'); node> fn('two', 'three'); one two three ``` --------------------------------------- <a name="nextTick" /> ### nextTick(callback), setImmediate(callback) Calls `callback` on a later loop around the event loop. In Node.js this just calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` if available, otherwise `setTimeout(callback, 0)`, which means other higher priority events may precede the execution of `callback`. This is used internally for browser-compatibility purposes. __Arguments__ * `callback` - The function to call on a later loop around the event loop. __Example__ ```js var call_order = []; async.nextTick(function(){ call_order.push('two'); // call_order now equals ['one','two'] }); call_order.push('one') ``` <a name="times" /> ### times(n, iterator, [callback]) Calls the `iterator` function `n` times, and accumulates results in the same manner you would use with [`map`](#map). __Arguments__ * `n` - The number of times to run the function. * `iterator` - The function to call `n` times. * `callback` - see [`map`](#map) __Example__ ```js // Pretend this is some complicated async factory var createUser = function(id, callback) { callback(null, { id: 'user' + id }) } // generate 5 users async.times(5, function(n, next){ createUser(n, function(err, user) { next(err, user) }) }, function(err, users) { // we should now have 5 users }); ``` __Related__ * timesSeries(n, iterator, [callback]) * timesLimit(n, limit, iterator, [callback]) ## Utils <a name="memoize" /> ### memoize(fn, [hasher]) Caches the results of an `async` function. When creating a hash to store function results against, the callback is omitted from the hash and an optional hash function can be used. If no hash function is specified, the first argument is used as a hash key, which may work reasonably if it is a string or a data type that converts to a distinct string. Note that objects and arrays will not behave reasonably. Neither will cases where the other arguments are significant. In such cases, specify your own hash function. The cache of results is exposed as the `memo` property of the function returned by `memoize`. __Arguments__ * `fn` - The function to proxy and cache results from. * `hasher` - An optional function for generating a custom hash for storing results. It has all the arguments applied to it apart from the callback, and must be synchronous. __Example__ ```js var slow_fn = function (name, callback) { // do something callback(null, result); }; var fn = async.memoize(slow_fn); // fn can now be used as if it were slow_fn fn('some name', function () { // callback }); ``` <a name="unmemoize" /> ### unmemoize(fn) Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized form. Handy for testing. __Arguments__ * `fn` - the memoized function --------------------------------------- <a name="ensureAsync" /> ### ensureAsync(fn) Wrap an async function and ensure it calls its callback on a later tick of the event loop. If the function already calls its callback on a next tick, no extra deferral is added. This is useful for preventing stack overflows (`RangeError: Maximum call stack size exceeded`) and generally keeping [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) contained. __Arguments__ * `fn` - an async function, one that expects a node-style callback as its last argument Returns a wrapped function with the exact same call signature as the function passed in. __Example__ ```js function sometimesAsync(arg, callback) { if (cache[arg]) { return callback(null, cache[arg]); // this would be synchronous!! } else { doSomeIO(arg, callback); // this IO would be asynchronous } } // this has a risk of stack overflows if many results are cached in a row async.mapSeries(args, sometimesAsync, done); // this will defer sometimesAsync's callback if necessary, // preventing stack overflows async.mapSeries(args, async.ensureAsync(sometimesAsync), done); ``` --------------------------------------- <a name="constant"> ### constant(values...) Returns a function that when called, calls-back with the values provided. Useful as the first function in a `waterfall`, or for plugging values in to `auto`. __Example__ ```js async.waterfall([ async.constant(42), function (value, next) { // value === 42 }, //... ], callback); async.waterfall([ async.constant(filename, "utf8"), fs.readFile, function (fileData, next) { //... } //... ], callback); async.auto({ hostname: async.constant("https://server.net/"), port: findFreePort, launchServer: ["hostname", "port", function (cb, options) { startServer(options, cb); }], //... }, callback); ``` --------------------------------------- <a name="asyncify"> <a name="wrapSync"> ### asyncify(func) __Alias:__ `wrapSync` Take a sync function and make it async, passing its return value to a callback. This is useful for plugging sync functions into a waterfall, series, or other async functions. Any arguments passed to the generated function will be passed to the wrapped function (except for the final callback argument). Errors thrown will be passed to the callback. __Example__ ```js async.waterfall([ async.apply(fs.readFile, filename, "utf8"), async.asyncify(JSON.parse), function (data, next) { // data is the result of parsing the text. // If there was a parsing error, it would have been caught. } ], callback) ``` If the function passed to `asyncify` returns a Promise, that promises's resolved/rejected state will be used to call the callback, rather than simply the synchronous return value. Example: ```js async.waterfall([ async.apply(fs.readFile, filename, "utf8"), async.asyncify(function (contents) { return db.model.create(contents); }), function (model, next) { // `model` is the instantiated model object. // If there was an error, this function would be skipped. } ], callback) ``` This also means you can asyncify ES2016 `async` functions. ```js var q = async.queue(async.asyncify(async function (file) { var intermediateStep = await processFile(file); return await somePromise(intermediateStep) })); q.push(files); ``` --------------------------------------- <a name="log" /> ### log(function, arguments) Logs the result of an `async` function to the `console`. Only works in Node.js or in browsers that support `console.log` and `console.error` (such as FF and Chrome). If multiple arguments are returned from the async function, `console.log` is called on each argument in order. __Arguments__ * `function` - The function you want to eventually apply all arguments to. * `arguments...` - Any number of arguments to apply to the function. __Example__ ```js var hello = function(name, callback){ setTimeout(function(){ callback(null, 'hello ' + name); }, 1000); }; ``` ```js node> async.log(hello, 'world'); 'hello world' ``` --------------------------------------- <a name="dir" /> ### dir(function, arguments) Logs the result of an `async` function to the `console` using `console.dir` to display the properties of the resulting object. Only works in Node.js or in browsers that support `console.dir` and `console.error` (such as FF and Chrome). If multiple arguments are returned from the async function, `console.dir` is called on each argument in order. __Arguments__ * `function` - The function you want to eventually apply all arguments to. * `arguments...` - Any number of arguments to apply to the function. __Example__ ```js var hello = function(name, callback){ setTimeout(function(){ callback(null, {hello: name}); }, 1000); }; ``` ```js node> async.dir(hello, 'world'); {hello: 'world'} ``` --------------------------------------- <a name="noConflict" /> ### noConflict() Changes the value of `async` back to its original value, returning a reference to the `async` object. ## Follow Redirects Drop-in replacement for Nodes `http` and `https` that automatically follows redirects. [![npm version](https://img.shields.io/npm/v/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) [![Build Status](https://travis-ci.org/follow-redirects/follow-redirects.svg?branch=master)](https://travis-ci.org/follow-redirects/follow-redirects) [![Coverage Status](https://coveralls.io/repos/follow-redirects/follow-redirects/badge.svg?branch=master)](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master) [![Dependency Status](https://david-dm.org/follow-redirects/follow-redirects.svg)](https://david-dm.org/follow-redirects/follow-redirects) [![npm downloads](https://img.shields.io/npm/dm/follow-redirects.svg)](https://www.npmjs.com/package/follow-redirects) `follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback) methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback) modules, with the exception that they will seamlessly follow redirects. ```javascript var http = require('follow-redirects').http; var https = require('follow-redirects').https; http.get('http://bit.ly/900913', function (response) { response.on('data', function (chunk) { console.log(chunk); }); }).on('error', function (err) { console.error(err); }); ``` You can inspect the final redirected URL through the `responseUrl` property on the `response`. If no redirection happened, `responseUrl` is the original request URL. ```javascript https.request({ host: 'bitly.com', path: '/UHfDGO', }, function (response) { console.log(response.responseUrl); // 'http://duckduckgo.com/robots.txt' }); ``` ## Options ### Global options Global options are set directly on the `follow-redirects` module: ```javascript var followRedirects = require('follow-redirects'); followRedirects.maxRedirects = 10; followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB ``` The following global options are supported: - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. ### Per-request options Per-request options are set by passing an `options` object: ```javascript var url = require('url'); var followRedirects = require('follow-redirects'); var options = url.parse('http://bit.ly/900913'); options.maxRedirects = 10; http.request(options); ``` In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback), the following per-request options are supported: - `followRedirects` (default: `true`) – whether redirects should be followed. - `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted. - `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted. - `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }` - `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object. ### Advanced usage By default, `follow-redirects` will use the Node.js default implementations of [`http`](https://nodejs.org/api/http.html) and [`https`](https://nodejs.org/api/https.html). To enable features such as caching and/or intermediate request tracking, you might instead want to wrap `follow-redirects` around custom protocol implementations: ```javascript var followRedirects = require('follow-redirects').wrap({ http: require('your-custom-http'), https: require('your-custom-https'), }); ``` Such custom protocols only need an implementation of the `request` method. ## Browser Usage Due to the way the browser works, the `http` and `https` browser equivalents perform redirects by default. By requiring `follow-redirects` this way: ```javascript var http = require('follow-redirects/http'); var https = require('follow-redirects/https'); ``` you can easily tell webpack and friends to replace `follow-redirect` by the built-in versions: ```json { "follow-redirects/http" : "http", "follow-redirects/https" : "https" } ``` ## Contributing Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues) detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied by tests. You can run the test suite locally with a simple `npm test` command. ## Debug Logging `follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well. ## Authors - Olivier Lalonde ([email protected]) - James Talmage ([email protected]) - [Ruben Verborgh](https://ruben.verborgh.org/) ## License [MIT License](https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE) wide-align ---------- A wide-character aware text alignment function for use in terminals / on the console. ### Usage ``` var align = require('wide-align') // Note that if you view this on a unicode console, all of the slashes are // aligned. This is because on a console, all narrow characters are // an en wide and all wide characters are an em. In browsers, this isn't // held to and wide characters like "古" can be less than two narrow // characters even with a fixed width font. console.log(align.center('abc', 10)) // ' abc ' console.log(align.center('古古古', 10)) // ' 古古古 ' console.log(align.left('abc', 10)) // 'abc ' console.log(align.left('古古古', 10)) // '古古古 ' console.log(align.right('abc', 10)) // ' abc' console.log(align.right('古古古', 10)) // ' 古古古' ``` ### Functions #### `align.center(str, length)` → `str` Returns *str* with spaces added to both sides such that that it is *length* chars long and centered in the spaces. #### `align.left(str, length)` → `str` Returns *str* with spaces to the right such that it is *length* chars long. ### `align.right(str, length)` → `str` Returns *str* with spaces to the left such that it is *length* chars long. ### Origins These functions were originally taken from [cliui](https://npmjs.com/package/cliui). Changes include switching to the MUCH faster pad generation function from [lodash](https://npmjs.com/package/lodash), making center alignment pad both sides and adding left alignment. An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` # repeat-string [![NPM version](https://img.shields.io/npm/v/repeat-string.svg?style=flat)](https://www.npmjs.com/package/repeat-string) [![NPM monthly downloads](https://img.shields.io/npm/dm/repeat-string.svg?style=flat)](https://npmjs.org/package/repeat-string) [![NPM total downloads](https://img.shields.io/npm/dt/repeat-string.svg?style=flat)](https://npmjs.org/package/repeat-string) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/repeat-string.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/repeat-string) > Repeat the given string n times. Fastest implementation for repeating a string. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save repeat-string ``` ## Usage ### [repeat](index.js#L41) Repeat the given `string` the specified `number` of times. **Example:** **Example** ```js var repeat = require('repeat-string'); repeat('A', 5); //=> AAAAA ``` **Params** * `string` **{String}**: The string to repeat * `number` **{Number}**: The number of times to repeat the string * `returns` **{String}**: Repeated string ## Benchmarks Repeat string is significantly faster than the native method (which is itself faster than [repeating](https://github.com/sindresorhus/repeating)): ```sh # 2x repeat-string █████████████████████████ (26,953,977 ops/sec) repeating █████████ (9,855,695 ops/sec) native ██████████████████ (19,453,895 ops/sec) # 3x repeat-string █████████████████████████ (19,445,252 ops/sec) repeating ███████████ (8,661,565 ops/sec) native ████████████████████ (16,020,598 ops/sec) # 10x repeat-string █████████████████████████ (23,792,521 ops/sec) repeating █████████ (8,571,332 ops/sec) native ███████████████ (14,582,955 ops/sec) # 50x repeat-string █████████████████████████ (23,640,179 ops/sec) repeating █████ (5,505,509 ops/sec) native ██████████ (10,085,557 ops/sec) # 250x repeat-string █████████████████████████ (23,489,618 ops/sec) repeating ████ (3,962,937 ops/sec) native ████████ (7,724,892 ops/sec) # 2000x repeat-string █████████████████████████ (20,315,172 ops/sec) repeating ████ (3,297,079 ops/sec) native ███████ (6,203,331 ops/sec) # 20000x repeat-string █████████████████████████ (23,382,915 ops/sec) repeating ███ (2,980,058 ops/sec) native █████ (5,578,808 ops/sec) ``` **Run the benchmarks** Install dev dependencies: ```sh npm i -d && node benchmark ``` ## About ### Related projects [repeat-element](https://www.npmjs.com/package/repeat-element): Create an array by repeating the given value n times. | [homepage](https://github.com/jonschlinkert/repeat-element "Create an array by repeating the given value n times.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor**<br/> | | --- | --- | | 51 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [LinusU](https://github.com/LinusU) | | 2 | [tbusser](https://github.com/tbusser) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wooorm](https://github.com/wooorm) | ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](http://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/repeat-string/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 23, 2016._ <p align="center"> <a href="https://github.com/node-base/base"> <img height="250" width="250" src="https://raw.githubusercontent.com/node-base/base/master/docs/logo.png"> </a> </p> # base [![NPM version](https://img.shields.io/npm/v/base.svg?style=flat)](https://www.npmjs.com/package/base) [![NPM monthly downloads](https://img.shields.io/npm/dm/base.svg?style=flat)](https://npmjs.org/package/base) [![NPM total downloads](https://img.shields.io/npm/dt/base.svg?style=flat)](https://npmjs.org/package/base) [![Linux Build Status](https://img.shields.io/travis/node-base/base.svg?style=flat&label=Travis)](https://travis-ci.org/node-base/base) > base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save base ``` ## What is Base? Base is a framework for rapidly creating high quality node.js applications, using plugins like building blocks. ### Guiding principles The core team follows these principles to help guide API decisions: * **Compact API surface**: The smaller the API surface, the easier the library will be to learn and use. * **Easy to extend**: Implementors can use any npm package, and write plugins in pure JavaScript. If you're building complex apps, Base simplifies inheritance. * **Easy to test**: No special setup should be required to unit test `Base` or base plugins ### Minimal API surface [The API](#api) was designed to provide only the minimum necessary functionality for creating a useful application, with or without [plugins](#plugins). **Base core** Base itself ships with only a handful of [useful methods](#api), such as: * `.set`: for setting values on the instance * `.get`: for getting values from the instance * `.has`: to check if a property exists on the instance * `.define`: for setting non-enumerable values on the instance * `.use`: for adding plugins **Be generic** When deciding on method to add or remove, we try to answer these questions: 1. Will all or most Base applications need this method? 2. Will this method encourage practices or enforce conventions that are beneficial to implementors? 3. Can or should this be done in a plugin instead? ### Composability **Plugin system** It couldn't be easier to extend Base with any features or custom functionality you can think of. Base plugins are just functions that take an instance of `Base`: ```js var base = new Base(); function plugin(base) { // do plugin stuff, in pure JavaScript } // use the plugin base.use(plugin); ``` **Inheritance** Easily inherit Base using `.extend`: ```js var Base = require('base'); function MyApp() { Base.call(this); } Base.extend(MyApp); var app = new MyApp(); app.set('a', 'b'); app.get('a'); //=> 'b'; ``` **Inherit or instantiate with a namespace** By default, the `.get`, `.set` and `.has` methods set and get values from the root of the `base` instance. You can customize this using the `.namespace` method exposed on the exported function. For example: ```js var Base = require('base'); // get and set values on the `base.cache` object var base = Base.namespace('cache'); var app = base(); app.set('foo', 'bar'); console.log(app.cache.foo); //=> 'bar' ``` ## API **Usage** ```js var Base = require('base'); var app = new Base(); app.set('foo', 'bar'); console.log(app.foo); //=> 'bar' ``` ### [Base](index.js#L44) Create an instance of `Base` with the given `config` and `options`. **Params** * `config` **{Object}**: If supplied, this object is passed to [cache-base](https://github.com/jonschlinkert/cache-base) to merge onto the the instance upon instantiation. * `options` **{Object}**: If supplied, this object is used to initialize the `base.options` object. **Example** ```js // initialize with `config` and `options` var app = new Base({isApp: true}, {abc: true}); app.set('foo', 'bar'); // values defined with the given `config` object will be on the root of the instance console.log(app.baz); //=> undefined console.log(app.foo); //=> 'bar' // or use `.get` console.log(app.get('isApp')); //=> true console.log(app.get('foo')); //=> 'bar' // values defined with the given `options` object will be on `app.options console.log(app.options.abc); //=> true ``` ### [.is](index.js#L107) Set the given `name` on `app._name` and `app.is*` properties. Used for doing lookups in plugins. **Params** * `name` **{String}** * `returns` **{Boolean}** **Example** ```js app.is('foo'); console.log(app._name); //=> 'foo' console.log(app.isFoo); //=> true app.is('bar'); console.log(app.isFoo); //=> true console.log(app.isBar); //=> true console.log(app._name); //=> 'bar' ``` ### [.isRegistered](index.js#L145) Returns true if a plugin has already been registered on an instance. Plugin implementors are encouraged to use this first thing in a plugin to prevent the plugin from being called more than once on the same instance. **Params** * `name` **{String}**: The plugin name. * `register` **{Boolean}**: If the plugin if not already registered, to record it as being registered pass `true` as the second argument. * `returns` **{Boolean}**: Returns true if a plugin is already registered. **Events** * `emits`: `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once. **Example** ```js var base = new Base(); base.use(function(app) { if (app.isRegistered('myPlugin')) return; // do stuff to `app` }); // to also record the plugin as being registered base.use(function(app) { if (app.isRegistered('myPlugin', true)) return; // do stuff to `app` }); ``` ### [.use](index.js#L175) Define a plugin function to be called immediately upon init. Plugins are chainable and expose the following arguments to the plugin function: * `app`: the current instance of `Base` * `base`: the [first ancestor instance](#base) of `Base` **Params** * `fn` **{Function}**: plugin function to call * `returns` **{Object}**: Returns the item instance for chaining. **Example** ```js var app = new Base() .use(foo) .use(bar) .use(baz) ``` ### [.define](index.js#L197) The `.define` method is used for adding non-enumerable property on the instance. Dot-notation is **not supported** with `define`. **Params** * `key` **{String}**: The name of the property to define. * `value` **{any}** * `returns` **{Object}**: Returns the instance for chaining. **Example** ```js // arbitrary `render` function using lodash `template` app.define('render', function(str, locals) { return _.template(str)(locals); }); ``` ### [.mixin](index.js#L222) Mix property `key` onto the Base prototype. If base is inherited using `Base.extend` this method will be overridden by a new `mixin` method that will only add properties to the prototype of the inheriting application. **Params** * `key` **{String}** * `val` **{Object|Array}** * `returns` **{Object}**: Returns the `base` instance for chaining. **Example** ```js app.mixin('foo', function() { // do stuff }); ``` ### [.base](index.js#L268) Getter/setter used when creating nested instances of `Base`, for storing a reference to the first ancestor instance. This works by setting an instance of `Base` on the `parent` property of a "child" instance. The `base` property defaults to the current instance if no `parent` property is defined. **Example** ```js // create an instance of `Base`, this is our first ("base") instance var first = new Base(); first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later // create another instance var second = new Base(); // create a reference to the first instance (`first`) second.parent = first; // create another instance var third = new Base(); // create a reference to the previous instance (`second`) // repeat this pattern every time a "child" instance is created third.parent = second; // we can always access the first instance using the `base` property console.log(first.base.foo); //=> 'bar' console.log(second.base.foo); //=> 'bar' console.log(third.base.foo); //=> 'bar' // and now you know how to get to third base ;) ``` ### [#use](index.js#L293) Static method for adding global plugin functions that will be added to an instance when created. **Params** * `fn` **{Function}**: Plugin function to use on each instance. * `returns` **{Object}**: Returns the `Base` constructor for chaining **Example** ```js Base.use(function(app) { app.foo = 'bar'; }); var app = new Base(); console.log(app.foo); //=> 'bar' ``` ### [#extend](index.js#L337) Static method for inheriting the prototype and static methods of the `Base` class. This method greatly simplifies the process of creating inheritance-based applications. See [static-extend](https://github.com/jonschlinkert/static-extend) for more details. **Params** * `Ctor` **{Function}**: constructor to extend * `methods` **{Object}**: Optional prototype properties to mix in. * `returns` **{Object}**: Returns the `Base` constructor for chaining **Example** ```js var extend = cu.extend(Parent); Parent.extend(Child); // optional methods Parent.extend(Child, { foo: function() {}, bar: function() {} }); ``` ### [#mixin](index.js#L379) Used for adding methods to the `Base` prototype, and/or to the prototype of child instances. When a mixin function returns a function, the returned function is pushed onto the `.mixins` array, making it available to be used on inheriting classes whenever `Base.mixins()` is called (e.g. `Base.mixins(Child)`). **Params** * `fn` **{Function}**: Function to call * `returns` **{Object}**: Returns the `Base` constructor for chaining **Example** ```js Base.mixin(function(proto) { proto.foo = function(msg) { return 'foo ' + msg; }; }); ``` ### [#mixins](index.js#L401) Static method for running global mixin functions against a child constructor. Mixins must be registered before calling this method. **Params** * `Child` **{Function}**: Constructor function of a child class * `returns` **{Object}**: Returns the `Base` constructor for chaining **Example** ```js Base.extend(Child); Base.mixins(Child); ``` ### [#inherit](index.js#L420) Similar to `util.inherit`, but copies all static properties, prototype properties, and getters/setters from `Provider` to `Receiver`. See [class-utils](https://github.com/jonschlinkert/class-utils#inherit) for more details. **Params** * `Receiver` **{Function}**: Receiving (child) constructor * `Provider` **{Function}**: Providing (parent) constructor * `returns` **{Object}**: Returns the `Base` constructor for chaining **Example** ```js Base.inherit(Foo, Bar); ``` ## In the wild The following node.js applications were built with `Base`: * [assemble](https://github.com/assemble/assemble) * [verb](https://github.com/verbose/verb) * [generate](https://github.com/generate/generate) * [scaffold](https://github.com/jonschlinkert/scaffold) * [boilerplate](https://github.com/jonschlinkert/boilerplate) ## Test coverage ``` Statements : 98.91% ( 91/92 ) Branches : 92.86% ( 26/28 ) Functions : 100% ( 17/17 ) Lines : 98.9% ( 90/91 ) ``` ## History ### v0.11.2 * fixes https://github.com/micromatch/micromatch/issues/99 ### v0.11.0 **Breaking changes** * Static `.use` and `.run` methods are now non-enumerable ### v0.9.0 **Breaking changes** * `.is` no longer takes a function, a string must be passed * all remaining `.debug` code has been removed * `app._namespace` was removed (related to `debug`) * `.plugin`, `.use`, and `.define` no longer emit events * `.assertPlugin` was removed * `.lazy` was removed ## About ### Related projects * [base-cwd](https://www.npmjs.com/package/base-cwd): Base plugin that adds a getter/setter for the current working directory. | [homepage](https://github.com/node-base/base-cwd "Base plugin that adds a getter/setter for the current working directory.") * [base-data](https://www.npmjs.com/package/base-data): adds a `data` method to base-methods. | [homepage](https://github.com/node-base/base-data "adds a `data` method to base-methods.") * [base-fs](https://www.npmjs.com/package/base-fs): base-methods plugin that adds vinyl-fs methods to your 'base' application for working with the file… [more](https://github.com/node-base/base-fs) | [homepage](https://github.com/node-base/base-fs "base-methods plugin that adds vinyl-fs methods to your 'base' application for working with the file system, like src, dest, copy and symlink.") * [base-generators](https://www.npmjs.com/package/base-generators): Adds project-generator support to your `base` application. | [homepage](https://github.com/node-base/base-generators "Adds project-generator support to your `base` application.") * [base-option](https://www.npmjs.com/package/base-option): Adds a few options methods to base, like `option`, `enable` and `disable`. See the readme… [more](https://github.com/node-base/base-option) | [homepage](https://github.com/node-base/base-option "Adds a few options methods to base, like `option`, `enable` and `disable`. See the readme for the full API.") * [base-pipeline](https://www.npmjs.com/package/base-pipeline): base-methods plugin that adds pipeline and plugin methods for dynamically composing streaming plugin pipelines. | [homepage](https://github.com/node-base/base-pipeline "base-methods plugin that adds pipeline and plugin methods for dynamically composing streaming plugin pipelines.") * [base-pkg](https://www.npmjs.com/package/base-pkg): Plugin for adding a `pkg` method that exposes pkg-store to your base application. | [homepage](https://github.com/node-base/base-pkg "Plugin for adding a `pkg` method that exposes pkg-store to your base application.") * [base-plugins](https://www.npmjs.com/package/base-plugins): Adds 'smart plugin' support to your base application. | [homepage](https://github.com/node-base/base-plugins "Adds 'smart plugin' support to your base application.") * [base-questions](https://www.npmjs.com/package/base-questions): Plugin for base-methods that adds methods for prompting the user and storing the answers on… [more](https://github.com/node-base/base-questions) | [homepage](https://github.com/node-base/base-questions "Plugin for base-methods that adds methods for prompting the user and storing the answers on a project-by-project basis.") * [base-store](https://www.npmjs.com/package/base-store): Plugin for getting and persisting config values with your base-methods application. Adds a 'store' object… [more](https://github.com/node-base/base-store) | [homepage](https://github.com/node-base/base-store "Plugin for getting and persisting config values with your base-methods application. Adds a 'store' object that exposes all of the methods from the data-store library. Also now supports sub-stores!") * [base-task](https://www.npmjs.com/package/base-task): base plugin that provides a very thin wrapper around [https://github.com/doowb/composer](https://github.com/doowb/composer) for adding task methods to… [more](https://github.com/node-base/base-task) | [homepage](https://github.com/node-base/base-task "base plugin that provides a very thin wrapper around <https://github.com/doowb/composer> for adding task methods to your application.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 141 | [jonschlinkert](https://github.com/jonschlinkert) | | 30 | [doowb](https://github.com/doowb) | | 3 | [charlike](https://github.com/charlike) | | 1 | [criticalmash](https://github.com/criticalmash) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on September 07, 2017._ # minizlib A tiny fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding. This module was created to serve the needs of [node-tar](http://npm.im/tar) v2. If your needs are different, then it may not be for you. ## How does this differ from the streams in `require('zlib')`? First, there are no convenience methods to compress or decompress a buffer. If you want those, use the built-in `zlib` module. This is only streams. This module compresses and decompresses the data as fast as you feed it in. It is synchronous, and runs on the main process thread. Zlib operations can be high CPU, but they're very fast, and doing it this way means much less bookkeeping and artificial deferral. Node's built in zlib streams are built on top of `stream.Transform`. They do the maximally safe thing with respect to consistent asynchrony, buffering, and backpressure. This module _does_ support backpressure, and will buffer output chunks that are not consumed, but is less of a mediator between the input and output. There is no high or low watermarks, no state objects, and so artificial async deferrals. It will not protect you from Zalgo. If you write, data will be emitted right away. If you write everything synchronously in one tick, and you are listening to the `data` event to consume it, then it'll all be emitted right away in that same tick. If you want data to be emitted in the next tick, then write it in the next tick. It is thus the responsibility of the reader and writer to manage their own consumption and process execution flow. The goal is to compress and decompress as fast as possible, even for files that are too large to store all in one buffer. The API is very similar to the built-in zlib module. There are classes that you instantiate with `new` and they are streams that can be piped together. uniq ==== Removes all duplicates from an array in place. Usage ===== First install using npm: npm install uniq Then use it as follows: ```javascript var arr = [1, 1, 2, 2, 3, 5] require("uniq")(arr) console.log(arr) //Prints: // // 1,2,3,5 // ``` ## `require("uniq")(array[, compare, sorted])` Removes all duplicates from a sorted array in place. * `array` is the array to remove items from * `compare` is an optional comparison function that returns 0 when two items are equal, and something non-zero when they are different. If unspecified, then the default equals will be used. * `sorted` if true, then assume array is already sorted **Returns:** A reference to `array` **Time Complexity:** `O(array.length * log(arra.length))` or `O(array.length)` if `sorted` ## Why use this instead of underscore.uniq[ue]? A few reasons: * This library updates the array in place without making an extra copy (and so it is faster for large arrays) * It also accepts a custom comparison function so you can remove duplicates from arrays containing object * It is more modular in the sense that it doesn't come with a bazillion other utility grab bag functions. # Credits (c) 2013 Mikola Lysenko. MIT License # JSON 3 # ![JSON 3 Logo](http://bestiejs.github.io/json3/page/logo.png) [![Build Status](https://secure.travis-ci.org/bestiejs/json3.png?branch=gh-pages)](http://travis-ci.org/bestiejs/json3) **JSON 3** is a modern JSON implementation compatible with a variety of JavaScript platforms, including Internet Explorer 6, Opera 7, Safari 2, and Netscape 6. The current version is **3.3.2**. - [Development Version](http://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.js) *(43 KB; uncompressed with comments)* - [Production Version](http://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js) *(3.5 KB; compressed and `gzip`-ped)* Special thanks to [cdnjs](http://cdnjs.com/libraries/json3/) and [jsDelivr](http://www.jsdelivr.com/#!json3) for hosting CDN copies of JSON 3. [JSON](http://json.org/) is a language-independent data interchange format based on a loose subset of the JavaScript grammar. Originally popularized by [Douglas Crockford](http://www.crockford.com/), the format was standardized in the [fifth edition](http://es5.github.com/) of the ECMAScript specification. The 5.1 edition, ratified in June 2011, incorporates several modifications to the grammar pertaining to the serialization of dates. JSON 3 exposes two functions: `stringify()` for [serializing](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify) a JavaScript value to JSON, and `parse()` for [producing](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse) a JavaScript value from a JSON source string. It is a **drop-in replacement** for [JSON 2](http://json.org/js). The functions behave exactly as described in the ECMAScript spec, **except** for the date serialization discrepancy noted below. The JSON 3 parser does **not** use `eval` or regular expressions. This provides security and performance benefits in obsolete and mobile environments, where the margin is particularly significant. The complete [benchmark suite](http://jsperf.com/json3) is available on [jsPerf](http://jsperf.com/). The project is [hosted on GitHub](http://git.io/json3), along with the [unit tests](http://bestiejs.github.io/json3/test/test_browser.html). It is part of the [BestieJS](https://github.com/bestiejs) family, a collection of best-in-class JavaScript libraries that promote cross-platform support, specification precedents, unit testing, and plenty of documentation. # Changes from JSON 2 # JSON 3... * Correctly serializes primitive wrapper objects. * Throws a `TypeError` when serializing cyclic structures (JSON 2 recurses until the call stack overflows). * Utilizes **feature tests** to detect broken or incomplete *native* JSON implementations (JSON 2 only checks for the presence of the native functions). The tests are only executed once at runtime, so there is no additional performance cost when parsing or serializing values. **As of v3.2.3**, JSON 3 is compatible with [Prototype](http://prototypejs.org) 1.6.1 and older. In contrast to JSON 2, JSON 3 **does not**... * Add `toJSON()` methods to the `Boolean`, `Number`, and `String` prototypes. These are not part of any standard, and are made redundant by the design of the `stringify()` implementation. * Add `toJSON()` or `toISOString()` methods to `Date.prototype`. See the note about date serialization below. ## Date Serialization **JSON 3 deviates from the specification in one important way**: it does not define `Date#toISOString()` or `Date#toJSON()`. This preserves CommonJS compatibility and avoids polluting native prototypes. Instead, date serialization is performed internally by the `stringify()` implementation: if a date object does not define a custom `toJSON()` method, it is serialized as a [simplified ISO 8601 date-time string](http://es5.github.com/#x15.9.1.15). **Several native `Date#toJSON()` implementations produce date time strings that do *not* conform to the grammar outlined in the spec**. For instance, all versions of Safari 4, as well as JSON 2, fail to serialize extended years correctly. Furthermore, JSON 2 and older implementations omit the milliseconds from the date-time string (optional in ES 5, but required in 5.1). Finally, in all versions of Safari 4 and 5, serializing an invalid date will produce the string `"Invalid Date"`, rather than `null`. Because these environments exhibit other serialization bugs, however, JSON 3 will override the native `stringify()` implementation. Portions of the date serialization code are adapted from the [`date-shim`](https://github.com/Yaffle/date-shim) project. # Usage # ## Web Browsers <script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script> <script> JSON.stringify({"Hello": 123}); // => '{"Hello":123}' JSON.parse("[[1, 2, 3], 1, 2, 3, 4]", function (key, value) { if (typeof value == "number") { value = value % 2 ? "Odd" : "Even"; } return value; }); // => [["Odd", "Even", "Odd"], "Odd", "Even", "Odd", "Even"] </script> **When used in a web browser**, JSON 3 exposes an additional `JSON3` object containing the `noConflict()` and `runInContext()` functions, as well as aliases to the `stringify()` and `parse()` functions. ### `noConflict` and `runInContext` * `JSON3.noConflict()` restores the original value of the global `JSON` object and returns a reference to the `JSON3` object. * `JSON3.runInContext([context, exports])` initializes JSON 3 using the given `context` object (e.g., `window`, `global`, etc.), or the global object if omitted. If an `exports` object is specified, the `stringify()`, `parse()`, and `runInContext()` functions will be attached to it instead of a new object. ### Asynchronous Module Loaders JSON 3 is defined as an [anonymous module](https://github.com/amdjs/amdjs-api/wiki/AMD#define-function-) for compatibility with [RequireJS](http://requirejs.org/), [`curl.js`](https://github.com/cujojs/curl), and other asynchronous module loaders. <script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.10/require.js"></script> <script> require({ "paths": { "json3": "./path/to/json3" } }, ["json3"], function (JSON) { JSON.parse("[1, 2, 3]"); // => [1, 2, 3] }); </script> To avoid issues with third-party scripts, **JSON 3 is exported to the global scope even when used with a module loader**. If this behavior is undesired, `JSON3.noConflict()` can be used to restore the global `JSON` object to its original value. ## CommonJS Environments var JSON3 = require("./path/to/json3"); JSON3.parse("[1, 2, 3]"); // => [1, 2, 3] ## JavaScript Engines load("path/to/json3.js"); JSON.stringify({"Hello": 123, "Good-bye": 456}, ["Hello"], "\t"); // => '{\n\t"Hello": 123\n}' # Compatibility # JSON 3 has been **tested** with the following web browsers, CommonJS environments, and JavaScript engines. ## Web Browsers - Windows [Internet Explorer](http://www.microsoft.com/windows/internet-explorer), version 6.0 and higher - Mozilla [Firefox](http://www.mozilla.com/firefox), version 1.0 and higher - Apple [Safari](http://www.apple.com/safari), version 2.0 and higher - [Opera](http://www.opera.com) 7.02 and higher - [Mozilla](http://sillydog.org/narchive/gecko.php) 1.0, [Netscape](http://sillydog.org/narchive/) 6.2.3, and [SeaMonkey](http://www.seamonkey-project.org/) 1.0 and higher ## CommonJS Environments - [Node](http://nodejs.org/) 0.2.6 and higher - [RingoJS](http://ringojs.org/) 0.4 and higher - [Narwhal](http://narwhaljs.org/) 0.3.2 and higher ## JavaScript Engines - Mozilla [Rhino](http://www.mozilla.org/rhino) 1.5R5 and higher - WebKit [JSC](https://trac.webkit.org/wiki/JSC) - Google [V8](http://code.google.com/p/v8) ## Known Incompatibilities * Attempting to serialize the `arguments` object may produce inconsistent results across environments due to specification version differences. As a workaround, please convert the `arguments` object to an array first: `JSON.stringify([].slice.call(arguments, 0))`. ## Required Native Methods JSON 3 assumes that the following methods exist and function as described in the ECMAScript specification: - The `Number`, `String`, `Array`, `Object`, `Date`, `SyntaxError`, and `TypeError` constructors. - `String.fromCharCode` - `Object#toString` - `Function#call` - `Math.floor` - `Number#toString` - `Date#valueOf` - `String.prototype`: `indexOf`, `charCodeAt`, `charAt`, `slice`. - `Array.prototype`: `push`, `pop`, `join`. # Contribute # Check out a working copy of the JSON 3 source code with [Git](http://git-scm.com/): $ git clone git://github.com/bestiejs/json3.git $ cd json3 If you'd like to contribute a feature or bug fix, you can [fork](http://help.github.com/fork-a-repo/) JSON 3, commit your changes, and [send a pull request](http://help.github.com/send-pull-requests/). Please make sure to update the unit tests in the `test` directory as well. Alternatively, you can use the [GitHub issue tracker](https://github.com/bestiejs/json3/issues) to submit bug reports, feature requests, and questions, or send tweets to [@kitcambridge](http://twitter.com/kitcambridge). JSON 3 is released under the [MIT License](http://kit.mit-license.org/). # loose-envify [![Build Status](https://travis-ci.org/zertosh/loose-envify.svg?branch=master)](https://travis-ci.org/zertosh/loose-envify) Fast (and loose) selective `process.env` replacer using [js-tokens](https://github.com/lydell/js-tokens) instead of an AST. Works just like [envify](https://github.com/hughsk/envify) but much faster. ## Gotchas * Doesn't handle broken syntax. * Doesn't look inside embedded expressions in template strings. - **this won't work:** ```js console.log(`the current env is ${process.env.NODE_ENV}`); ``` * Doesn't replace oddly-spaced or oddly-commented expressions. - **this won't work:** ```js console.log(process./*won't*/env./*work*/NODE_ENV); ``` ## Usage/Options loose-envify has the exact same interface as [envify](https://github.com/hughsk/envify), including the CLI. ## Benchmark ``` envify: $ for i in {1..5}; do node bench/bench.js 'envify'; done 708ms 727ms 791ms 719ms 720ms loose-envify: $ for i in {1..5}; do node bench/bench.js '../'; done 51ms 52ms 52ms 52ms 52ms ``` # parseurl [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Parse a URL with memoization. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install parseurl ``` ## API ```js var parseurl = require('parseurl') ``` ### parseurl(req) Parse the URL of the given request object (looks at the `req.url` property) and return the result. The result is the same as `url.parse` in Node.js core. Calling this function multiple times on the same `req` where `req.url` does not change will return a cached parsed object, rather than parsing again. ### parseurl.original(req) Parse the original URL of the given request object and return the result. This works by trying to parse `req.originalUrl` if it is a string, otherwise parses `req.url`. The result is the same as `url.parse` in Node.js core. Calling this function multiple times on the same `req` where `req.originalUrl` does not change will return a cached parsed object, rather than parsing again. ## Benchmark ```bash $ npm run-script bench > [email protected] bench nodejs-parseurl > node benchmark/index.js [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] modules@64 [email protected] napi@3 [email protected] [email protected] [email protected] [email protected] tz@2018c > node benchmark/fullurl.js Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" 4 tests completed. fasturl x 2,207,842 ops/sec ±3.76% (184 runs sampled) nativeurl - legacy x 507,180 ops/sec ±0.82% (191 runs sampled) nativeurl - whatwg x 290,044 ops/sec ±1.96% (189 runs sampled) parseurl x 488,907 ops/sec ±2.13% (192 runs sampled) > node benchmark/pathquery.js Parsing URL "/foo/bar?user=tj&pet=fluffy" 4 tests completed. fasturl x 3,812,564 ops/sec ±3.15% (188 runs sampled) nativeurl - legacy x 2,651,631 ops/sec ±1.68% (189 runs sampled) nativeurl - whatwg x 161,837 ops/sec ±2.26% (189 runs sampled) parseurl x 4,166,338 ops/sec ±2.23% (184 runs sampled) > node benchmark/samerequest.js Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object 4 tests completed. fasturl x 3,821,651 ops/sec ±2.42% (185 runs sampled) nativeurl - legacy x 2,651,162 ops/sec ±1.90% (187 runs sampled) nativeurl - whatwg x 175,166 ops/sec ±1.44% (188 runs sampled) parseurl x 14,912,606 ops/sec ±3.59% (183 runs sampled) > node benchmark/simplepath.js Parsing URL "/foo/bar" 4 tests completed. fasturl x 12,421,765 ops/sec ±2.04% (191 runs sampled) nativeurl - legacy x 7,546,036 ops/sec ±1.41% (188 runs sampled) nativeurl - whatwg x 198,843 ops/sec ±1.83% (189 runs sampled) parseurl x 24,244,006 ops/sec ±0.51% (194 runs sampled) > node benchmark/slash.js Parsing URL "/" 4 tests completed. fasturl x 17,159,456 ops/sec ±3.25% (188 runs sampled) nativeurl - legacy x 11,635,097 ops/sec ±3.79% (184 runs sampled) nativeurl - whatwg x 240,693 ops/sec ±0.83% (189 runs sampled) parseurl x 42,279,067 ops/sec ±0.55% (190 runs sampled) ``` ## License [MIT](LICENSE) [coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/parseurl/master [coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master [node-image]: https://badgen.net/npm/node/parseurl [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/parseurl [npm-url]: https://npmjs.org/package/parseurl [npm-version-image]: https://badgen.net/npm/v/parseurl [travis-image]: https://badgen.net/travis/pillarjs/parseurl/master [travis-url]: https://travis-ci.org/pillarjs/parseurl ```javascript var correct = require('spdx-correct') var assert = require('assert') assert.equal(correct('mit'), 'MIT') assert.equal(correct('Apache 2'), 'Apache-2.0') assert(correct('No idea what license') === null) // disable upgrade option assert(correct('GPL-3.0'), 'GPL-3.0-or-later') assert(correct('GPL-3.0', { upgrade: false }), 'GPL-3.0') ``` # dns-equal Compare DNS record strings for equality. Enforces [RFC 1035](https://tools.ietf.org/html/rfc1035) domain comparison. [![Build status](https://travis-ci.org/watson/dns-equal.svg?branch=master)](https://travis-ci.org/watson/dns-equal) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) ## Installation ``` npm install dns-equal --save ``` ## Usage ```js var dnsEqual = require('dns-equal') var domain1 = 'Example.COM' var domain2 = 'example.com' if (dnsEqual(domain1, domain2)) { console.log('The two domains are the same') } ``` ## License MIT # Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/coveralls/bestiejs/punycode.js/master.svg)](https://coveralls.io/r/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) A robust Punycode converter that fully complies to [RFC 3492](http://tools.ietf.org/html/rfc3492) and [RFC 5891](http://tools.ietf.org/html/rfc5891), and works on nearly all JavaScript platforms. This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](http://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project is [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with [Node.js v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc). ## Installation Via [npm](http://npmjs.org/) (only required for Node.js releases older than v0.6.2): ```bash npm install punycode ``` Via [Bower](http://bower.io/): ```bash bower install punycode ``` Via [Component](https://github.com/component/component): ```bash component install bestiejs/punycode.js ``` In a browser: ```html <script src="punycode.js"></script> ``` In [Narwhal](http://narwhaljs.org/), [Node.js](http://nodejs.org/), and [RingoJS](http://ringojs.org/): ```js var punycode = require('punycode'); ``` In [Rhino](http://www.mozilla.org/rhino/): ```js load('punycode.js'); ``` Using an AMD loader like [RequireJS](http://requirejs.org/): ```js require( { 'paths': { 'punycode': 'path/to/punycode' } }, ['punycode'], function(punycode) { console.log(punycode); } ); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that's already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Unit tests & code coverage After cloning this repository, run `npm install --dev` to install the dependencies needed for Punycode.js development and testing. You may want to install Istanbul _globally_ using `npm install istanbul -g`. Once that’s done, you can run the unit tests in Node using `npm test` or `node tests/tests.js`. To run the tests in Rhino, Ringo, Narwhal, PhantomJS, and web browsers as well, use `grunt test`. To generate the code coverage report, use `grunt cover`. Feel free to fork if you see possible improvements! ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## Contributors | [![twitter/jdalton](https://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") | |---| | [John-David Dalton](http://allyoucanleet.com/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license. # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation). * `column`: The column number in the generated source. Column numbers in this library are 0-based. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. The line number is 1-based. * `column`: The column number in the original source, or null if this information is not available. The column number is 0-based. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: The column number in the original source. The column number is 0-based. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. The line number is 1-based. * `column`: Optional. The column number in the original source. The column number is 0-based. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. The line number is 1-based. * `column`: The column number in the generated source, or null. The column number is 0-based. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # class-utils [![NPM version](https://img.shields.io/npm/v/class-utils.svg?style=flat)](https://www.npmjs.com/package/class-utils) [![NPM monthly downloads](https://img.shields.io/npm/dm/class-utils.svg?style=flat)](https://npmjs.org/package/class-utils) [![NPM total downloads](https://img.shields.io/npm/dt/class-utils.svg?style=flat)](https://npmjs.org/package/class-utils) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/class-utils.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/class-utils) > Utils for working with JavaScript classes and prototype methods. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save class-utils ``` ## Usage ```js var cu = require('class-utils'); ``` ## API ### [.has](index.js#L43) Returns true if an array has any of the given elements, or an object has any of the give keys. **Params** * `obj` **{Object}** * `val` **{String|Array}** * `returns` **{Boolean}** **Example** ```js cu.has(['a', 'b', 'c'], 'c'); //=> true cu.has(['a', 'b', 'c'], ['c', 'z']); //=> true cu.has({a: 'b', c: 'd'}, ['c', 'z']); //=> true ``` ### [.hasAll](index.js#L90) Returns true if an array or object has all of the given values. **Params** * `val` **{Object|Array}** * `values` **{String|Array}** * `returns` **{Boolean}** **Example** ```js cu.hasAll(['a', 'b', 'c'], 'c'); //=> true cu.hasAll(['a', 'b', 'c'], ['c', 'z']); //=> false cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']); //=> false ``` ### [.arrayify](index.js#L117) Cast the given value to an array. **Params** * `val` **{String|Array}** * `returns` **{Array}** **Example** ```js cu.arrayify('foo'); //=> ['foo'] cu.arrayify(['foo']); //=> ['foo'] ``` ### [.hasConstructor](index.js#L152) Returns true if a value has a `contructor` **Params** * `value` **{Object}** * `returns` **{Boolean}** **Example** ```js cu.hasConstructor({}); //=> true cu.hasConstructor(Object.create(null)); //=> false ``` ### [.nativeKeys](index.js#L174) Get the native `ownPropertyNames` from the constructor of the given `object`. An empty array is returned if the object does not have a constructor. **Params** * `obj` **{Object}**: Object that has a `constructor`. * `returns` **{Array}**: Array of keys. **Example** ```js cu.nativeKeys({a: 'b', b: 'c', c: 'd'}) //=> ['a', 'b', 'c'] cu.nativeKeys(function(){}) //=> ['length', 'caller'] ``` ### [.getDescriptor](index.js#L208) Returns property descriptor `key` if it's an "own" property of the given object. **Params** * `obj` **{Object}** * `key` **{String}** * `returns` **{Object}**: Returns descriptor `key` **Example** ```js function App() {} Object.defineProperty(App.prototype, 'count', { get: function() { return Object.keys(this).length; } }); cu.getDescriptor(App.prototype, 'count'); // returns: // { // get: [Function], // set: undefined, // enumerable: false, // configurable: false // } ``` ### [.copyDescriptor](index.js#L238) Copy a descriptor from one object to another. **Params** * `receiver` **{Object}** * `provider` **{Object}** * `name` **{String}** * `returns` **{Object}** **Example** ```js function App() {} Object.defineProperty(App.prototype, 'count', { get: function() { return Object.keys(this).length; } }); var obj = {}; cu.copyDescriptor(obj, App.prototype, 'count'); ``` ### [.copy](index.js#L264) Copy static properties, prototype properties, and descriptors from one object to another. **Params** * `receiver` **{Object}** * `provider` **{Object}** * `omit` **{String|Array}**: One or more properties to omit * `returns` **{Object}** ### [.inherit](index.js#L299) Inherit the static properties, prototype properties, and descriptors from of an object. **Params** * `receiver` **{Object}** * `provider` **{Object}** * `omit` **{String|Array}**: One or more properties to omit * `returns` **{Object}** ### [.extend](index.js#L343) Returns a function for extending the static properties, prototype properties, and descriptors from the `Parent` constructor onto `Child` constructors. **Params** * `Parent` **{Function}**: Parent ctor * `extend` **{Function}**: Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype. * `Child` **{Function}**: Child ctor * `proto` **{Object}**: Optionally pass additional prototype properties to inherit. * `returns` **{Object}** **Example** ```js var extend = cu.extend(Parent); Parent.extend(Child); // optional methods Parent.extend(Child, { foo: function() {}, bar: function() {} }); ``` ### [.bubble](index.js#L356) Bubble up events emitted from static methods on the Parent ctor. **Params** * `Parent` **{Object}** * `events` **{Array}**: Event names to bubble up ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [define-property](https://www.npmjs.com/package/define-property): Define a non-enumerable property on an object. Uses Reflect.defineProperty when available, otherwise Object.defineProperty. | [homepage](https://github.com/jonschlinkert/define-property "Define a non-enumerable property on an object. Uses Reflect.defineProperty when available, otherwise Object.defineProperty.") * [delegate-properties](https://www.npmjs.com/package/delegate-properties): Deep-clone properties from one object to another and make them non-enumerable, or make existing properties… [more](https://github.com/jonschlinkert/delegate-properties) | [homepage](https://github.com/jonschlinkert/delegate-properties "Deep-clone properties from one object to another and make them non-enumerable, or make existing properties on an object non-enumerable.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 34 | [jonschlinkert](https://github.com/jonschlinkert) | | 8 | [doowb](https://github.com/doowb) | | 2 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on January 11, 2018._ forever-agent ============= HTTP Agent that keeps socket connections alive between keep-alive requests. Formerly part of mikeal/request, now a standalone module. # es-abstract <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] [![browser support][testling-svg]][testling-url] ECMAScript spec abstract operations. When different versions of the spec conflict, the default export will be the latest version of the abstract operation. All abstract operations will also be available under an `es5`/`es2015`/`es2016`/`es2017`/`es2018` entry point, and exported property, if you require a specific version. ## Example ```js var ES = require('es-abstract'); var assert = require('assert'); assert(ES.isCallable(function () {})); assert(!ES.isCallable(/a/g)); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/es-abstract [npm-version-svg]: http://versionbadg.es/ljharb/es-abstract.svg [travis-svg]: https://travis-ci.org/ljharb/es-abstract.svg [travis-url]: https://travis-ci.org/ljharb/es-abstract [deps-svg]: https://david-dm.org/ljharb/es-abstract.svg [deps-url]: https://david-dm.org/ljharb/es-abstract [dev-deps-svg]: https://david-dm.org/ljharb/es-abstract/dev-status.svg [dev-deps-url]: https://david-dm.org/ljharb/es-abstract#info=devDependencies [testling-svg]: https://ci.testling.com/ljharb/es-abstract.png [testling-url]: https://ci.testling.com/ljharb/es-abstract [npm-badge-png]: https://nodei.co/npm/es-abstract.png?downloads=true&stars=true [license-image]: https://img.shields.io/npm/l/es-abstract.svg [license-url]: LICENSE [downloads-image]: https://img.shields.io/npm/dm/es-abstract.svg [downloads-url]: https://npm-stat.com/charts.html?package=es-abstract # figgy-pudding [![npm version](https://img.shields.io/npm/v/figgy-pudding.svg)](https://npm.im/figgy-pudding) [![license](https://img.shields.io/npm/l/figgy-pudding.svg)](https://npm.im/figgy-pudding) [![Travis](https://img.shields.io/travis/zkat/figgy-pudding.svg)](https://travis-ci.org/zkat/figgy-pudding) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/figgy-pudding?svg=true)](https://ci.appveyor.com/project/zkat/figgy-pudding) [![Coverage Status](https://coveralls.io/repos/github/zkat/figgy-pudding/badge.svg?branch=latest)](https://coveralls.io/github/zkat/figgy-pudding?branch=latest) [`figgy-pudding`](https://github.com/zkat/figgy-pudding) is a small JavaScript library for managing and composing cascading options objects -- hiding what needs to be hidden from each layer, without having to do a lot of manual munging and passing of options. ### The God Object is Dead! ### Now Bring Us Some Figgy Pudding! ## Install `$ npm install figgy-pudding` ## Table of Contents * [Example](#example) * [Features](#features) * [API](#api) * [`figgyPudding(spec)`](#figgy-pudding) * [`PuddingFactory(values)`](#pudding-factory) * [`opts.get()`](#opts-get) * [`opts.concat()`](#opts-concat) * [`opts.toJSON()`](#opts-to-json) * [`opts.forEach()`](#opts-for-each) * [`opts[Symbol.iterator]()`](#opts-symbol-iterator) * [`opts.entries()`](#opts-entries) * [`opts.keys()`](#opts-keys) * [`opts.value()`](#opts-values) ### Example ```javascript // print-package.js const fetch = require('./fetch.js') const puddin = require('figgy-pudding') const PrintOpts = puddin({ json: { default: false } }) async function printPkg (name, opts) { // Expected pattern is to call this in every interface function. If `opts` is // not passed in, it will automatically create an (empty) object for it. opts = PrintOpts(opts) const uri = `https://registry.npmjs.com/${name}` const res = await fetch(uri, opts.concat({ // Add or override any passed-in configs and pass them down. log: customLogger })) // The following would throw an error, because it's not in PrintOpts: // console.log(opts.log) if (opts.json) { return res.json() } else { return res.text() } } console.log(await printPkg('figgy', { // Pass in *all* configs at the toplevel, as a regular object. json: true, cache: './tmp-cache' })) ``` ```javascript // fetch.js const puddin = require('figgy-pudding') const FetchOpts = puddin({ log: { default: require('npmlog') }, cache: {} }) module.exports = async function (..., opts) { opts = FetchOpts(opts) } ``` ### Features * hide options from layer that didn't ask for it * shared multi-layer options * make sure `opts` argument is available * transparent key access like normal keys, through a Proxy. No need for`.get()`! * default values * key aliases * arbitrary key filter functions * key/value iteration * serialization * 100% test coverage using `tap --100` ### API #### <a name="figgy-pudding"></a> `> figgyPudding({ key: { default: val } | String }, [opts]) -> PuddingFactory` Defines an Options constructor that can be used to collect only the needed options. An optional `default` property for specs can be used to specify default values if nothing was passed in. If the value for a spec is a string, it will be treated as an alias to that other key. ##### Example ```javascript const MyAppOpts = figgyPudding({ lg: 'log', log: { default: () => require('npmlog') }, cache: {} }) ``` #### <a name="pudding-factory"></a> `> PuddingFactory(...providers) -> FiggyPudding{}` Instantiates an options object defined by `figgyPudding()`, which uses `providers`, in order, to find requested properties. Each provider can be either a plain object, a `Map`-like object (that is, one with a `.get()` method) or another figgyPudding `Opts` object. When nesting `Opts` objects, their properties will not become available to the new object, but any further nested `Opts` that reference that property _will_ be able to read from their grandparent, as long as they define that key. Default values for nested `Opts` parents will be used, if found. ##### Example ```javascript const ReqOpts = figgyPudding({ follow: {} }) const opts = ReqOpts({ follow: true, log: require('npmlog') }) opts.follow // => true opts.log // => Error: ReqOpts does not define `log` const MoreOpts = figgyPudding({ log: {} }) MoreOpts(opts).log // => npmlog object (passed in from original plain obj) MoreOpts(opts).follow // => Error: MoreOpts does not define `follow` ``` #### <a name="opts-get"></a> `> opts.get(key) -> Value` Gets a value from the options object. ##### Example ```js const opts = MyOpts(config) opts.get('foo') // value of `foo` opts.foo // Proxy-based access through `.get()` ``` #### <a name="opts-concat"></a> `> opts.concat(...moreProviders) -> FiggyPudding{}` Creates a new opts object of the same type as `opts` with additional providers. Providers further to the right shadow providers to the left, with properties in the original `opts` being shadows by the new providers. ##### Example ```js const opts = MyOpts({x: 1}) opts.get('x') // 1 opts.concat({x: 2}).get('x') // 2 opts.get('x') // 1 (original opts object left intact) ``` #### <a name="opts-to-json"></a> `> opts.toJSON() -> Value` Converts `opts` to a plain, JSON-stringifiable JavaScript value. Used internally by JavaScript to get `JSON.stringify()` working. Only keys that are readable by the current pudding type will be serialized. ##### Example ```js const opts = MyOpts({x: 1}) opts.toJSON() // {x: 1} JSON.stringify(opts) // '{"x":1}' ``` #### <a name="opts-for-each"></a> `> opts.forEach((value, key, opts) => {}, thisArg) -> undefined` Iterates over the values of `opts`, limited to the keys readable by the current pudding type. `thisArg` will be used to set the `this` argument when calling the `fn`. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) opts.forEach((value, key) => console.log(key, '=', value)) ``` #### <a name="opts-entries"></a> `> opts.entries() -> Iterator<[[key, value], ...]>` Returns an iterator that iterates over the keys and values in `opts`, limited to the keys readable by the current pudding type. Each iteration returns an array of `[key, value]`. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).entries()] // [['x', 1], ['y', 2]] ``` #### <a name="opts-symbol-iterator"></a> `> opts[Symbol.iterator]() -> Iterator<[[key, value], ...]>` Returns an iterator that iterates over the keys and values in `opts`, limited to the keys readable by the current pudding type. Each iteration returns an array of `[key, value]`. Makes puddings work natively with JS iteration mechanisms. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2})] // [['x', 1], ['y', 2]] for (let [key, value] of opts({x: 1, y: 2})) { console.log(key, '=', value) } ``` #### <a name="opts-keys"></a> `> opts.keys() -> Iterator<[key, ...]>` Returns an iterator that iterates over the keys in `opts`, limited to the keys readable by the current pudding type. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).keys()] // ['x', 'y'] ``` #### <a name="opts-values"></a> `> opts.values() -> Iterator<[value, ...]>` Returns an iterator that iterates over the values in `opts`, limited to the keys readable by the current pudding type. ##### Example ' ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).values()] // [1, 2] ``` # IP [![](https://badge.fury.io/js/ip.svg)](https://www.npmjs.com/package/ip) IP address utilities for node.js ## Installation ### npm ```shell npm install ip ``` ### git ```shell git clone https://github.com/indutny/node-ip.git ``` ## Usage Get your ip address, compare ip addresses, validate ip addresses, etc. ```js var ip = require('ip'); ip.address() // my ip address ip.isEqual('::1', '::0:1'); // true ip.toBuffer('127.0.0.1') // Buffer([127, 0, 0, 1]) ip.toString(new Buffer([127, 0, 0, 1])) // 127.0.0.1 ip.fromPrefixLen(24) // 255.255.255.0 ip.mask('192.168.1.134', '255.255.255.0') // 192.168.1.0 ip.cidr('192.168.1.134/26') // 192.168.1.128 ip.not('255.255.255.0') // 0.0.0.255 ip.or('192.168.1.134', '0.0.0.255') // 192.168.1.255 ip.isPrivate('127.0.0.1') // true ip.isV4Format('127.0.0.1'); // true ip.isV6Format('::ffff:127.0.0.1'); // true // operate on buffers in-place var buf = new Buffer(128); var offset = 64; ip.toBuffer('127.0.0.1', buf, offset); // [127, 0, 0, 1] at offset 64 ip.toString(buf, offset, 4); // '127.0.0.1' // subnet information ip.subnet('192.168.1.134', '255.255.255.192') // { networkAddress: '192.168.1.128', // firstAddress: '192.168.1.129', // lastAddress: '192.168.1.190', // broadcastAddress: '192.168.1.191', // subnetMask: '255.255.255.192', // subnetMaskLength: 26, // numHosts: 62, // length: 64, // contains: function(addr){...} } ip.cidrSubnet('192.168.1.134/26') // Same as previous. // range checking ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.190') // true // ipv4 long conversion ip.toLong('127.0.0.1'); // 2130706433 ip.fromLong(2130706433); // '127.0.0.1' ``` ### License This software is licensed under the MIT License. Copyright Fedor Indutny, 2012. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) A tiny node.js debugging utility modelled after node core's debugging technique. **Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example _app.js_: ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %s', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example _worker.js_: ```js var debug = require('debug')('worker'); setInterval(function(){ debug('doing some work'); }, 1000); ``` The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) #### Windows note On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Note that PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Then, run the program to be debugged as usual. ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` #### Web Inspector Colors Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). Colored output looks something like: ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example _stdout.js_: ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2016 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # indexes-of like Array/String#indexOf but return all the indexes in an array. ``` js var indexesOf = require('indexes-of') var twosIndexes = indexesOf([1, 2, 3, 4, 5, 4, 3, 2, 1], 2) console.log(twosIndexes) // [1, 7] ``` # Haiku * A 5 line module. * But the tests are 40 lines. * npm publish. ## License MIT # readable-stream ***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream) [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) [![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) [![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream) ```bash npm install --save readable-stream ``` ***Node-core streams for userland*** This package is a mirror of the Streams2 and Streams3 implementations in Node-core. Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html). If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). As of version 2.0.0 **readable-stream** uses semantic versioning. # Streams Working Group `readable-stream` is maintained by the Streams Working Group, which oversees the development and maintenance of the Streams API within Node.js. The responsibilities of the Streams Working Group include: * Addressing stream issues on the Node.js issue tracker. * Authoring and editing stream documentation within the Node.js project. * Reviewing changes to stream subclasses within the Node.js project. * Redirecting changes to streams from the Node.js project to this project. * Assisting in the implementation of stream providers within Node.js. * Recommending versions of `readable-stream` to be included in Node.js. * Messaging about the future of streams to give the community advance notice of changes. <a name="members"></a> ## Team Members * **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;[email protected]&gt; - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B * **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;[email protected]&gt; - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 * **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;[email protected]&gt; - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D * **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;[email protected]&gt; * **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;[email protected]&gt; * **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;[email protected]&gt; * **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;[email protected]&gt; - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E * **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;[email protected]&gt; # lodash.assign v4.2.0 The [lodash](https://lodash.com/) method `_.assign` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.assign ``` In Node.js: ```js var assign = require('lodash.assign'); ``` See the [documentation](https://lodash.com/docs#assign) or [package source](https://github.com/lodash/lodash/blob/4.2.0-npm-packages/lodash.assign) for more details. # isexe Minimal module to check if a file is executable, and a normal file. Uses `fs.stat` and tests against the `PATHEXT` environment variable on Windows. ## USAGE ```javascript var isexe = require('isexe') isexe('some-file-name', function (err, isExe) { if (err) { console.error('probably file does not exist or something', err) } else if (isExe) { console.error('this thing can be run') } else { console.error('cannot be run') } }) // same thing but synchronous, throws errors var isExe = isexe.sync('some-file-name') // treat errors as just "not executable" isexe('maybe-missing-file', { ignoreErrors: true }, callback) var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) ``` ## API ### `isexe(path, [options], [callback])` Check if the path is executable. If no callback provided, and a global `Promise` object is available, then a Promise will be returned. Will raise whatever errors may be raised by `fs.stat`, unless `options.ignoreErrors` is set to true. ### `isexe.sync(path, [options])` Same as `isexe` but returns the value and throws any errors raised. ### Options * `ignoreErrors` Treat all errors as "no, this is not executable", but don't raise them. * `uid` Number to use as the user id * `gid` Number to use as the group id * `pathExt` List of path extensions to use instead of `PATHEXT` environment variable on Windows. # extsprintf: extended POSIX-style sprintf Stripped down version of s[n]printf(3c). We make a best effort to throw an exception when given a format string we don't understand, rather than ignoring it, so that we won't break existing programs if/when we go implement the rest of this. This implementation currently supports specifying * field alignment ('-' flag), * zero-pad ('0' flag) * always show numeric sign ('+' flag), * field width * conversions for strings, decimal integers, and floats (numbers). * argument size specifiers. These are all accepted but ignored, since Javascript has no notion of the physical size of an argument. Everything else is currently unsupported, most notably: precision, unsigned numbers, non-decimal numbers, and characters. Besides the usual POSIX conversions, this implementation supports: * `%j`: pretty-print a JSON object (using node's "inspect") * `%r`: pretty-print an Error object # Example First, install it: # npm install extsprintf Now, use it: var mod_extsprintf = require('extsprintf'); console.log(mod_extsprintf.sprintf('hello %25s', 'world')); outputs: hello world # Also supported **printf**: same args as sprintf, but prints the result to stdout **fprintf**: same args as sprintf, preceded by a Node stream. Prints the result to the given stream. # vary [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Manipulate the HTTP Vary header ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install vary ``` ## API <!-- eslint-disable no-unused-vars --> ```js var vary = require('vary') ``` ### vary(res, field) Adds the given header `field` to the `Vary` response header of `res`. This can be a string of a single field, a string of a valid `Vary` header, or an array of multiple fields. This will append the header if not already listed, otherwise leaves it listed in the current location. <!-- eslint-disable no-undef --> ```js // Append "Origin" to the Vary header of the response vary(res, 'Origin') ``` ### vary.append(header, field) Adds the given header `field` to the `Vary` response header string `header`. This can be a string of a single field, a string of a valid `Vary` header, or an array of multiple fields. This will append the header if not already listed, otherwise leaves it listed in the current location. The new header string is returned. <!-- eslint-disable no-undef --> ```js // Get header string appending "Origin" to "Accept, User-Agent" vary.append('Accept, User-Agent', 'Origin') ``` ## Examples ### Updating the Vary header when content is based on it ```js var http = require('http') var vary = require('vary') http.createServer(function onRequest (req, res) { // about to user-agent sniff vary(res, 'User-Agent') var ua = req.headers['user-agent'] || '' var isMobile = /mobi|android|touch|mini/i.test(ua) // serve site, depending on isMobile res.setHeader('Content-Type', 'text/html') res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') }) ``` ## Testing ```sh $ npm test ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/vary.svg [npm-url]: https://npmjs.org/package/vary [node-version-image]: https://img.shields.io/node/v/vary.svg [node-version-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg [travis-url]: https://travis-ci.org/jshttp/vary [coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/vary [downloads-image]: https://img.shields.io/npm/dm/vary.svg [downloads-url]: https://npmjs.org/package/vary # Array Flatten [![NPM version][npm-image]][npm-url] [![NPM downloads][downloads-image]][downloads-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] > Flatten an array of nested arrays into a single flat array. Accepts an optional depth. ## Installation ``` npm install array-flatten --save ``` ## Usage ```javascript var flatten = require('array-flatten') flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) //=> [1, 2, 3, [4, [5], 6], 7, 8, 9] (function () { flatten(arguments) //=> [1, 2, 3] })(1, [2, 3]) ``` ## License MIT [npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat [npm-url]: https://npmjs.org/package/array-flatten [downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat [downloads-url]: https://npmjs.org/package/array-flatten [travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat [travis-url]: https://travis-ci.org/blakeembrey/array-flatten [coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat [coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master [`core-js-compat` package](https://github.com/zloirock/core-js/packages/core-js-compat) contains data about the necessity of [`core-js`](https://github.com/zloirock/core-js) modules and API for getting a list of required core-js modules by browserslist query. ```js const { list, // array of required modules targets, // object with targets for each module } = require('core-js-compat')({ targets: '> 2.5%', // browserslist query filter: 'es.', // optional filter - string-prefix, regexp or list of modules }); console.log(targets); /* => { 'es.symbol.description': { ios: '12.0-12.1' }, 'es.array.reverse': { ios: '12.0-12.1' }, 'es.string.replace': { firefox: '63', ios: '12.0-12.1' }, 'es.string.trim': { ios: '12.0-12.1' }, 'es.promise': { firefox: '63' }, 'es.promise.finally': { firefox: '63' }, 'es.array-buffer.slice': { ios: '12.0-12.1' }, 'es.typed-array.int8-array': { ios: '12.0-12.1' }, 'es.typed-array.uint8-array': { ios: '12.0-12.1' }, 'es.typed-array.uint8-clamped-array': { ios: '12.0-12.1' }, 'es.typed-array.int16-array': { ios: '12.0-12.1' }, 'es.typed-array.uint16-array': { ios: '12.0-12.1' }, 'es.typed-array.int32-array': { ios: '12.0-12.1' }, 'es.typed-array.uint32-array': { ios: '12.0-12.1' }, 'es.typed-array.float32-array': { ios: '12.0-12.1' }, 'es.typed-array.float64-array': { ios: '12.0-12.1' }, 'es.typed-array.from': { ios: '12.0-12.1' }, 'es.typed-array.of': { ios: '12.0-12.1' } } */ ``` If you want to add new / update data about modules required for target engines, [follow this instruction](https://github.com/zloirock/core-js/blob/master/CONTRIBUTING.md#updating-core-js-compat-data). # is-data-descriptor [![NPM version](https://img.shields.io/npm/v/is-data-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-data-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-data-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-data-descriptor) > Returns true if a value has the characteristics of a valid JavaScript data descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-data-descriptor ``` ## Usage ```js var isDataDesc = require('is-data-descriptor'); ``` ## Examples `true` when the descriptor has valid properties with valid values. ```js // `value` can be anything isDataDesc({value: 'foo'}) isDataDesc({value: function() {}}) isDataDesc({value: true}) //=> true ``` `false` when not an object ```js isDataDesc('a') //=> false isDataDesc(null) //=> false isDataDesc([]) //=> false ``` `false` when the object has invalid properties ```js isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', get: function(){}}) //=> false isDataDesc({get: function(){}, value: 'foo'}) //=> false ``` `false` when a value is not the correct type ```js isDataDesc({value: 'foo', enumerable: 'foo'}) //=> false isDataDesc({value: 'foo', configurable: 'foo'}) //=> false isDataDesc({value: 'foo', writable: 'foo'}) //=> false ``` ## Valid properties The only valid data descriptor properties are the following: * `configurable` (required) * `enumerable` (required) * `value` (optional) * `writable` (optional) To be a valid data descriptor, either `value` or `writable` must be defined. **Invalid properties** A descriptor may have additional _invalid_ properties (an error will **not** be thrown). ```js var foo = {}; Object.defineProperty(foo, 'bar', { enumerable: true, whatever: 'blah', // invalid, but doesn't cause an error get: function() { return 'baz'; } }); console.log(foo.bar); //=> 'baz' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 21 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ <div align="center"> <img width="180" height="180" vspace="20" src="https://cdn.worldvectorlogo.com/logos/css-3.svg"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] [![size][size]][size-url] # css-loader The `css-loader` interprets `@import` and `url()` like `import/require()` and will resolve them. ## Getting Started To begin, you'll need to install `css-loader`: ```console npm install --save-dev css-loader ``` Then add the plugin to your `webpack` config. For example: **file.js** ```js import css from 'file.css'; ``` **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, }; ``` Good loaders for requiring your assets are the [file-loader](https://github.com/webpack/file-loader) and the [url-loader](https://github.com/webpack/url-loader) which you should specify in your config (see [below](https://github.com/webpack-contrib/css-loader#assets)). And run `webpack` via your preferred method. ### `toString` You can also use the css-loader results directly as a string, such as in Angular's component style. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, use: ['to-string-loader', 'css-loader'], }, ], }, }; ``` or ```js const css = require('./test.css').toString(); console.log(css); // {String} ``` If there are SourceMaps, they will also be included in the result string. If, for one reason or another, you need to extract CSS as a plain string resource (i.e. not wrapped in a JS module) you might want to check out the [extract-loader](https://github.com/peerigon/extract-loader). It's useful when you, for instance, need to post process the CSS as a string. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, use: [ 'handlebars-loader', // handlebars loader expects raw resource string 'extract-loader', 'css-loader', ], }, ], }, }; ``` ## Options | Name | Type | Default | Description | | :-----------------------------------------: | :-------------------: | :-------------: | :----------------------------------------------------------------------- | | **[`url`](#url)** | `{Boolean\|Function}` | `true` | Enable/Disable `url()` handling | | **[`import`](#import)** | `{Boolean\/Function}` | `true` | Enable/Disable @import handling | | **[`modules`](#modules)** | `{Boolean\|String}` | `false` | Enable/Disable CSS Modules and setup mode | | **[`localIdentName`](#localidentname)** | `{String}` | `[hash:base64]` | Configure the generated ident | | **[`context`](#context)** | `{String}` | `undefined` | Allow to redefine basic loader context for local ident name | | **[`hashPrefix`](#hashprefix)** | `{String}` | `undefined` | Allow to add custom hash to generate more unique classes | | **[`getLocalIdent`](#getlocalident)** | `{Function}` | `undefined` | Configure the function to generate classname based on a different schema | | **[`sourceMap`](#sourcemap)** | `{Boolean}` | `false` | Enable/Disable Sourcemaps | | **[`camelCase`](#camelcase)** | `{Boolean\|String}` | `false` | Export Classnames in CamelCase | | **[`importLoaders`](#importloaders)** | `{Number}` | `0` | Number of loaders applied before CSS loader | | **[`exportOnlyLocals`](#exportonlylocals)** | `{Boolean}` | `false` | Export only locals | ### `url` Type: `Boolean|Function` Default: `true` Control `url()` resolving. Absolute URLs and root-relative URLs are not resolving. Examples resolutions: ``` url(image.png) => require('./image.png') url('image.png') => require('./image.png') url(./image.png) => require('./image.png') url('./image.png') => require('./image.png') url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png') image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png') ``` To import assets from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`: ``` url(~module/image.png) => require('module/image.png') url('~module/image.png') => require('module/image.png') url(~aliasDirectory/image.png) => require('otherDirectory/image.png') ``` #### `Boolean` Enable/disable `url()` resolving. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { url: true, }, }, ], }, }; ``` #### `Function` Allow to filter `url()`. All filtered `url()` will not be resolved (left in the code as they were written). **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { url: (url, resourcePath) => { // resourcePath - path to css file // `url()` with `img.png` stay untouched return url.includes('img.png'); }, }, }, ], }, }; ``` ### `import` Type: `Boolean` Default: `true` Control `@import` resolving. Absolute urls in `@import` will be moved in runtime code. Examples resolutions: ``` @import 'style.css' => require('./style.css') @import url(style.css) => require('./style.css') @import url('style.css') => require('./style.css') @import './style.css' => require('./style.css') @import url(./style.css) => require('./style.css') @import url('./style.css') => require('./style.css') @import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime ``` To import styles from a `node_modules` path (include `resolve.modules`) and for `alias`, prefix it with a `~`: ``` @import url(~module/style.css) => require('module/style.css') @import url('~module/style.css') => require('module/style.css') @import url(~aliasDirectory/style.css) => require('otherDirectory/style.css') ``` #### `Boolean` Enable/disable `@import` resolving. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { import: true, }, }, ], }, }; ``` #### `Function` Allow to filter `@import`. All filtered `@import` will not be resolved (left in the code as they were written). **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { import: (parsedImport, resourcePath) => { // parsedImport.url - url of `@import` // parsedImport.media - media query of `@import` // resourcePath - path to css file // `@import` with `style.css` stay untouched return parsedImport.url.includes('style.css'); }, }, }, ], }, }; ``` ### [`modules`](https://github.com/css-modules/css-modules) Type: `Boolean|String` Default: `false` The `modules` option enables/disables the **CSS Modules** spec and setup basic behaviour. | Name | Type | Description | | :------------: | :---------: | :------------------------------------------------------------------------------------------------------------------------------- | | **`true`** | `{Boolean}` | Enables local scoped CSS by default (use **local** mode by default) | | **`false`** | `{Boolean}` | Disable the **CSS Modules** spec, all **CSS Modules** features (like `@value`, `:local`, `:global` and `composes`) will not work | | **`'local'`** | `{String}` | Enables local scoped CSS by default (same as `true` value) | | **`'global'`** | `{String}` | Enables global scoped CSS by default | Using `false` value increase performance because we avoid parsing **CSS Modules** features, it will be useful for developers who use vanilla css or use other technologies. You can read about **modes** below. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { modules: true, }, }, ], }, }; ``` ##### `Scope` Using `local` value requires you to specify `:global` classes. Using `global` value requires you to specify `:local` classes. You can find more information [here](https://github.com/css-modules/css-modules). Styles can be locally scoped to avoid globally scoping styles. The syntax `:local(.className)` can be used to declare `className` in the local scope. The local identifiers are exported by the module. With `:local` (without brackets) local mode can be switched on for this selector. The `:global(.className)` nocation can be used to declare an explicit global selector. With `:global` (without brackets) global mode can be switched on for this selector. The loader replaces local selectors with unique identifiers. The chosen unique identifiers are exported by the module. ```css :local(.className) { background: red; } :local .className { color: green; } :local(.className .subClass) { color: green; } :local .className .subClass :global(.global-class-name) { color: blue; } ``` ```css ._23_aKvs-b8bW2Vg3fwHozO { background: red; } ._23_aKvs-b8bW2Vg3fwHozO { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { color: blue; } ``` > ℹ️ Identifiers are exported ```js exports.locals = { className: '_23_aKvs-b8bW2Vg3fwHozO', subClass: '_13LGdX8RMStbBE9w-t0gZ1', }; ``` CamelCase is recommended for local selectors. They are easier to use within the imported JS module. You can use `:local(#someId)`, but this is not recommended. Use classes instead of ids. ##### `Composing` When declaring a local classname you can compose a local class from another local classname. ```css :local(.className) { background: red; color: yellow; } :local(.subClass) { composes: className; background: blue; } ``` This doesn't result in any change to the CSS itself but exports multiple classnames. ```js exports.locals = { className: '_23_aKvs-b8bW2Vg3fwHozO', subClass: '_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO', }; ``` ```css ._23_aKvs-b8bW2Vg3fwHozO { background: red; color: yellow; } ._13LGdX8RMStbBE9w-t0gZ1 { background: blue; } ``` ##### `Importing` To import a local classname from another module. ```css :local(.continueButton) { composes: button from 'library/button.css'; background: red; } ``` ```css :local(.nameEdit) { composes: edit highlight from './edit.css'; background: red; } ``` To import from multiple modules use multiple `composes:` rules. ```css :local(.className) { composes: edit hightlight from './edit.css'; composes: button from 'module/button.css'; composes: classFromThisModule; background: red; } ``` ### `localIdentName` Type: `String` Default: `[hash:base64]` You can configure the generated ident with the `localIdentName` query parameter. See [loader-utils's documentation](https://github.com/webpack/loader-utils#interpolatename) for more information on options. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { modules: true, localIdentName: '[path][name]__[local]--[hash:base64:5]', }, }, ], }, }; ``` ### `context` Type: `String` Default: `undefined` Allow to redefine basic loader context for local ident name. By default we use `rootContext` of loader. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { modules: true, context: path.resolve(__dirname, 'context'), }, }, ], }, }; ``` ### `hashPrefix` Type: `String` Default: `undefined` Allow to add custom hash to generate more unique classes. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { modules: true, hashPrefix: 'hash', }, }, ], }, }; ``` ### `getLocalIdent` Type: `Function` Default: `undefined` You can also specify the absolute path to your custom `getLocalIdent` function to generate classname based on a different schema. By default we use built-in function to generate a classname. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { modules: true, getLocalIdent: (context, localIdentName, localName, options) => { return 'whatever_random_class_name'; }, }, }, ], }, }; ``` ### `sourceMap` Type: `Boolean` Default: `false` To include source maps set the `sourceMap` option. I.e. the `mini-css-extract-plugin` can handle them. They are not enabled by default because they expose a runtime overhead and increase in bundle size (JS source maps do not). In addition to that relative paths are buggy and you need to use an absolute public path which includes the server URL. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { sourceMap: true, }, }, ], }, }; ``` ### `camelCase` Type: `Boolean|String` Default: `false` By default, the exported JSON keys mirror the class names. If you want to camelize class names (useful in JS), pass the query parameter `camelCase` to css-loader. | Name | Type | Description | | :----------------: | :---------: | :----------------------------------------------------------------------------------------------------------------------- | | **`false`** | `{Boolean}` | Class names will be camelized, the original class name will not to be removed from the locals | | **`true`** | `{Boolean}` | Class names will be camelized | | **`'dashes'`** | `{String}` | Only dashes in class names will be camelized | | **`'only'`** | `{String}` | Introduced in `0.27.1`. Class names will be camelized, the original class name will be removed from the locals | | **`'dashesOnly'`** | `{String}` | Introduced in `0.27.1`. Dashes in class names will be camelized, the original class name will be removed from the locals | **file.css** ```css .class-name { } ``` **file.js** ```js import { className } from 'file.css'; ``` **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { camelCase: true, }, }, ], }, }; ``` ### `importLoaders` Type: `Number` Default: `0` The option `importLoaders` allows you to configure how many loaders before `css-loader` should be applied to `@import`ed resources. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2, // 0 => no loaders (default); 1 => postcss-loader; 2 => postcss-loader, sass-loader }, }, 'postcss-loader', 'sass-loader', ], }, ], }, }; ``` This may change in the future when the module system (i. e. webpack) supports loader matching by origin. ### `exportOnlyLocals` Type: `Boolean` Default: `false` Export only locals (**useful** when you use **css modules**). For pre-rendering with `mini-css-extract-plugin` you should use this option instead of `style-loader!css-loader` **in the pre-rendering bundle**. It doesn't embed CSS but only exports the identifier mappings. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, loader: 'css-loader', options: { exportOnlyLocals: true, }, }, ], }, }; ``` ## Examples ### Assets The following `webpack.config.js` can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as [Data URLs](https://tools.ietf.org/html/rfc2397) and copy larger files to the output directory. **webpack.config.js** ```js module.exports = { module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], }, { test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, loader: 'url-loader', options: { limit: 10000, }, }, ], }, }; ``` ### Extract For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on. - This can be achieved by using the [mini-css-extract-plugin](https://github.com/webpack-contrib/mini-css-extract-plugin) to extract the CSS when running in production mode. - As an alternative, if seeking better development performance and css outputs that mimic production. [extract-css-chunks-webpack-plugin](https://github.com/faceyspacey/extract-css-chunks-webpack-plugin) offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev ## Contributing Please take a moment to read our contributing guidelines if you haven't yet done so. [CONTRIBUTING](./.github/CONTRIBUTING.md) ## License [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/css-loader.svg [npm-url]: https://npmjs.com/package/css-loader [node]: https://img.shields.io/node/v/css-loader.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack-contrib/css-loader.svg [deps-url]: https://david-dm.org/webpack-contrib/css-loader [tests]: https://img.shields.io/circleci/project/github/webpack-contrib/css-loader.svg [tests-url]: https://circleci.com/gh/webpack-contrib/css-loader [cover]: https://codecov.io/gh/webpack-contrib/css-loader/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/css-loader [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack [size]: https://packagephobia.now.sh/badge?p=css-loader [size-url]: https://packagephobia.now.sh/result?p=css-loader # abbrev-js Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev). Usage: var abbrev = require("abbrev"); abbrev("foo", "fool", "folding", "flop"); // returns: { fl: 'flop' , flo: 'flop' , flop: 'flop' , fol: 'folding' , fold: 'folding' , foldi: 'folding' , foldin: 'folding' , folding: 'folding' , foo: 'foo' , fool: 'fool' } This is handy for command-line scripts, or other cases where you want to be able to accept shorthands. Generate a self signed x509 certificate from node.js. [![Build Status](https://travis-ci.org/jfromaniello/selfsigned.png)](https://travis-ci.org/jfromaniello/selfsigned) ## Install ```bash npm install selfsigned ``` ## Usage ```js var selfsigned = require('selfsigned'); var attrs = [{ name: 'commonName', value: 'contoso.com' }]; var pems = selfsigned.generate(attrs, { days: 365 }); console.log(pems) ``` #### Async ```js selfsigned.generate(attrs, { days: 365 }, function (err, pems) { console.log(pems) }); ``` Will return the following like this: ```js { private: '-----BEGIN RSA PRIVATE KEY-----\r\nMIICXAIBAAKBgQCBFMXMYS/+RZz6+qzv+xeqXPdjw4YKZC4y3dPhSwgEwkecrCTX\r\nsR6boue+1MjIqPqWggXZnotIGldfEN0kn0Jbh2vMTrTx6YwqQ8tceBPoyuuqcYBO\r\nOONAcKOB3MLnZbyOgVtbyT3j68JE5V/lx6LhpIKAgY0m5WIuaKrW6mvLXQIDAQAB\r\nAoGAU6ODGxAqSecPdayyG/ml9vSwNAuAMgGB0eHcpZG5i2PbhRAh+0TAIXaoFQXJ\r\naAPeA2ISqlTJyRmQXYAO2uj61FzeyDzYCf0z3+yZEVz3cO7jB5Pl6iBvzbxWuuuA\r\ncbJtWLhWtW5/jioc8F0EAzZ+lkC/XuVJdwKHDmwt2qvJO+ECQQD+dvo1g3Sz9xGw\r\n21n+fDG5i4128+Qh+JPgh5AeLuXSofc1HMHaOXcC6Wu/Cloh7QAD934b7W0A7VoD\r\ndLd/JLyFAkEAgdwjryyvdhy69e516IrPB3b+m4rggtntBlZREMrk9tOzeIucVO3W\r\ntKI3FHm6JebN2gVcG+rZ+FaDPo+ifJkW+QJBAPojrMwEACmUevB2f9246gxx0UsY\r\nbq6yM3No71OsWEEY8/Bi53CEQqg7Gq5+F6H33qcHmBEN8LQTngN9rY+vZh0CQBg0\r\nqJImii5B/LeK03+dICoMDDmCEYdSh9P+ku3GZBd+Lp3xqBpMmxDgi9PNPN2DwCs7\r\nhIfPpwGbXqtyqp7/CkECQB4OdY+2FbCciI473eQkTu310RMf8jElU63iwnx4R/XN\r\n/mgqN589OfF4SS0U/MoRzYk9jF9IAJN1Mi/571T+nw4=\r\n-----END RSA PRIVATE KEY-----\r\n', public: '-----BEGIN PUBLIC KEY-----\r\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCBFMXMYS/+RZz6+qzv+xeqXPdj\r\nw4YKZC4y3dPhSwgEwkecrCTXsR6boue+1MjIqPqWggXZnotIGldfEN0kn0Jbh2vM\r\nTrTx6YwqQ8tceBPoyuuqcYBOOONAcKOB3MLnZbyOgVtbyT3j68JE5V/lx6LhpIKA\r\ngY0m5WIuaKrW6mvLXQIDAQAB\r\n-----END PUBLIC KEY-----\r\n', cert: '-----BEGIN CERTIFICATE-----\r\nMIICjTCCAfagAwIBAgIBATANBgkqhkiG9w0BAQUFADBpMRQwEgYDVQQDEwtleGFt\r\ncGxlLm9yZzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMRMwEQYDVQQH\r\nEwpCbGFja3NidXJnMQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MB4XDTEz\r\nMDgxMzA1NDAyN1oXDTE0MDgxMzA1NDAyN1owaTEUMBIGA1UEAxMLZXhhbXBsZS5v\r\ncmcxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhWaXJnaW5pYTETMBEGA1UEBxMKQmxh\r\nY2tzYnVyZzENMAsGA1UEChMEVGVzdDENMAsGA1UECxMEVGVzdDCBnzANBgkqhkiG\r\n9w0BAQEFAAOBjQAwgYkCgYEAgRTFzGEv/kWc+vqs7/sXqlz3Y8OGCmQuMt3T4UsI\r\nBMJHnKwk17Eem6LnvtTIyKj6loIF2Z6LSBpXXxDdJJ9CW4drzE608emMKkPLXHgT\r\n6MrrqnGATjjjQHCjgdzC52W8joFbW8k94+vCROVf5cei4aSCgIGNJuViLmiq1upr\r\ny10CAwEAAaNFMEMwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAvQwJgYDVR0RBB8w\r\nHYYbaHR0cDovL2V4YW1wbGUub3JnL3dlYmlkI21lMA0GCSqGSIb3DQEBBQUAA4GB\r\nAC9hGQlDh8anNo1YDJdG2mYqOQ5uybJV++kixblGaOkoDROPsWepUpL6kMDUtbAM\r\n4uXTyFkvlUQSaQkhNgOY5w/BRIAkCIu6u4D4XcjlCdwFq6vcKMEuWTHMAlBWFla3\r\nXJZAPO10PHuDen7JeMOUf1Re7lRFtwfRGAvVYmrvYFKv\r\n-----END CERTIFICATE-----\r\n' } ``` ## Attributes for attributes, please refer to: https://github.com/digitalbazaar/forge/blob/0.7.5/lib/x509.js#L129 ## Options ```js var pems = selfsigned.generate(null, { keySize: 2048, // the size for the private key in bits (default: 1024) days: 30, // how long till expiry of the signed certificate (default: 365) algorithm: 'sha256', // sign the certificate with specified algorithm (default: 'sha1') extensions: [{ name: 'basicConstraints', cA: true }], // certificate extensions array pkcs7: true, // include PKCS#7 as part of the output (default: false) clientCertificate: true, // generate client cert signed by the original key (default: false) clientCertificateCN: 'jdoe' // client certificate's common name (default: 'John Doe jdoe123') }); ``` > You can avoid key pair generation specifying your own keys (`{ keyPair: { publicKey: '-----BEGIN PUBLIC KEY-----...', privateKey: '-----BEGIN RSA PRIVATE KEY-----...' }`) ### Generate Client Certificates If you are in an environment where servers require client certificates, you can generate client keys signed by the original (server) key. ```js var pems = selfsigned.generate(null, { clientCertificate: true }); console.log(pems) ``` Will return the following like this: ```js { private: '-----BEGIN RSA PRIVATE KEY-----\r\nMIICXQIBAAKBgQDLg/kS4dCPVu96sbK6MQuUPmhqnF8SeBXVHH18h+0BTj7HqnrA\r\nA75hNVIiSLTChvpzQ0qi2Ju7O2ESUOdx7cvGiftGuZLiI8uL2HVlYuX+wQTIoRHx\r\n9nxv56TIiqnPg5d05vSTLXoiJg5uac3a6+4vnhhTo0XRRXVVboZsfNpuGQIDAQAB\r\nAoGAfhCd9QhUPLZJWeNBJvzCg221GHUMn1Arlfsz8DPyp+BkGyKLLu4iu+xfmEUZ\r\nU3ZxJX0FeqJatTwvAT2EYJpAovx+F37PWFTLAS6T57WI1O5Lj1pTIKVkLrasNQgF\r\nl6qFD3cvEtCZve4LiwDoJ52FO2OtcDcMJ0r2oqbCXSDIlAECQQDnkkxKcTejBZGH\r\nyYEXG9hAznnEZ63LLzlHHF2cIPfxT+9826Wm0IzBxn8Wr4hcAbNx3bVKgsU9p7xA\r\nfKnSqObhAkEA4PwCjPQqxFpiYUmNt7htb8nCEvUDD/QSDyxAH/uJzfr6gOJOD5nT\r\n5gZYblC+CCMDkgDUpro6oATNyeRNoU3GOQJBANdaW26DWZ1WqV9hCpcGAxdJrT30\r\nuVASq66w93Ehy9LzZqFz1tqKacwvH7NmLGZ8AngrGdSgRnOvEMfb50aMYqECQDcG\r\nzCTnbzJZHOjIkaXWsMV/pjz2ugoD2wrk+sYXwoujj/NH5mnAaOhAsw5AJ0pcLfpe\r\nw6QHtmD+68ouUaJbIFkCQQDeu0AXAp6Kbk6570i2DpGUSnkRdGCGS+3ekqqJUpE7\r\nfVUSx1nCF1sPD0p+pO8Rj3i87iI4MlblQRm/wVkrkjiR\r\n-----END RSA PRIVATE KEY-----\r\n', public: '-----BEGIN PUBLIC KEY-----\r\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLg/kS4dCPVu96sbK6MQuUPmhq\r\nnF8SeBXVHH18h+0BTj7HqnrAA75hNVIiSLTChvpzQ0qi2Ju7O2ESUOdx7cvGiftG\r\nuZLiI8uL2HVlYuX+wQTIoRHx9nxv56TIiqnPg5d05vSTLXoiJg5uac3a6+4vnhhT\r\no0XRRXVVboZsfNpuGQIDAQAB\r\n-----END PUBLIC KEY-----\r\n', cert: '-----BEGIN CERTIFICATE-----\r\nMIIClTCCAf6gAwIBAgIJdMZqoEeGMVYKMA0GCSqGSIb3DQEBBQUAMGkxFDASBgNV\r\nBAMTC2V4YW1wbGUub3JnMQswCQYDVQQGEwJVUzERMA8GA1UECBMIVmlyZ2luaWEx\r\nEzARBgNVBAcTCkJsYWNrc2J1cmcxDTALBgNVBAoTBFRlc3QxDTALBgNVBAsTBFRl\r\nc3QwHhcNMTUxMDI5MTMwNjA1WhcNMTYxMDI4MTMwNjA1WjBpMRQwEgYDVQQDEwtl\r\neGFtcGxlLm9yZzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMRMwEQYD\r\nVQQHEwpCbGFja3NidXJnMQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MIGf\r\nMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLg/kS4dCPVu96sbK6MQuUPmhqnF8S\r\neBXVHH18h+0BTj7HqnrAA75hNVIiSLTChvpzQ0qi2Ju7O2ESUOdx7cvGiftGuZLi\r\nI8uL2HVlYuX+wQTIoRHx9nxv56TIiqnPg5d05vSTLXoiJg5uac3a6+4vnhhTo0XR\r\nRXVVboZsfNpuGQIDAQABo0UwQzAMBgNVHRMEBTADAQH/MAsGA1UdDwQEAwIC9DAm\r\nBgNVHREEHzAdhhtodHRwOi8vZXhhbXBsZS5vcmcvd2ViaWQjbWUwDQYJKoZIhvcN\r\nAQEFBQADgYEAj1Yyyb0R9KRFjIWNFi6RErB/riWylW4CdOK1hOyJZ+VRBWeYLKfX\r\ni///V+tqRvLlYY5x5DnrjXbDjBy0CZuN/J772/Srgp7Nl5cn92zynMJK1q4MEEs3\r\nAE/FO85R0HbGEp+IrwUwDOLR6omBFVdh1EUOTcQU2jLZNbWvLDiWbDo=\r\n-----END CERTIFICATE-----\r\n', clientprivate: '-----BEGIN RSA PRIVATE KEY-----\r\nMIICWwIBAAKBgQDjR5FrrdZ1jirqkx3KMPnGjrcObj/vmztWTEZ1kX6gTskQugJU\r\noxktzwDZza4jYODC6Ud2jouFLWeAi5BDSAeLwAQb951qVD9zVsmQ+63V/mvSJUoj\r\nigwj7YjcxyReJ17F0YgjceqrkZaPM8YRo8h1fj1JdPc4ZOUgA5ASZ0h2ewIDAQAB\r\nAoGAfB5DbjibG8ut6Di7VgX1AdhCY+EVjXaKqxAwklgIfOdJqpbKWwpO39NiNY+7\r\nf5qSZB8dZcNmsi4fjfWprPSTGVkk1Qp2uibtFS4MhbLEeyy4cgZfMIBQY+HD0Asf\r\n1NU7WTY5QfzgH3HAKuWpUEWdar/jE+hDPA+wnsMg+TgGARECQQDzlc+5WA9JsG9f\r\nwNRzhMGRxDP4QLmL0iLWupF4BMP/k4OLMjDtzWl725WJ4FjCzML7mSmkWWe/P8f5\r\nwrbR+e8lAkEA7t0CEsiIw8BE55YMuGIz5xI0QDnuwNWmCEmq6+ZziW3L+EuAr1S4\r\nDORqBYm5DuRvBWkWE9Sld0a8vNqWh58tHwJAP1ZYEhicuQuAmkRYucTuVEnRPZ8O\r\n4BV+65jNlIigskcYMEyXvm3oHMWnJ5fHXLfDh4p28n4w5ODfzcjcotK7ZQJAE7bX\r\n8fbtGsLmrPp8aEdqozqkZ1ygsPexMWPrIHcvt/sA56hLoazrV90ORxC73lfKNfcb\r\nZF2bnoGPGEMuQ1lG3wJAPnHysm3DgbSHZQiXWMjF4YDRRV2AeOqX1fmlSeMErwdj\r\ncwIs+ikIBnOwUOh6liJ7yK1YnckDTZTOfUDyG+vdFQ==\r\n-----END RSA PRIVATE KEY-----\r\n', clientpublic: '-----BEGIN PUBLIC KEY-----\r\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjR5FrrdZ1jirqkx3KMPnGjrcO\r\nbj/vmztWTEZ1kX6gTskQugJUoxktzwDZza4jYODC6Ud2jouFLWeAi5BDSAeLwAQb\r\n951qVD9zVsmQ+63V/mvSJUojigwj7YjcxyReJ17F0YgjceqrkZaPM8YRo8h1fj1J\r\ndPc4ZOUgA5ASZ0h2ewIDAQAB\r\n-----END PUBLIC KEY-----\r\n', clientcert: '-----BEGIN CERTIFICATE-----\r\nMIICSzCCAbSgAwIBAgIBAjANBgkqhkiG9w0BAQUFADBpMRQwEgYDVQQDEwtleGFt\r\ncGxlLm9yZzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMRMwEQYDVQQH\r\nEwpCbGFja3NidXJnMQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MB4XDTE1\r\nMTAyOTEzMDYwNVoXDTE2MTAyOTEzMDYwNVowbjEZMBcGA1UEAxMQSm9obiBEb2Ug\r\namRvZTEyMzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMRMwEQYDVQQH\r\nEwpCbGFja3NidXJnMQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0MIGfMA0G\r\nCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjR5FrrdZ1jirqkx3KMPnGjrcObj/vmztW\r\nTEZ1kX6gTskQugJUoxktzwDZza4jYODC6Ud2jouFLWeAi5BDSAeLwAQb951qVD9z\r\nVsmQ+63V/mvSJUojigwj7YjcxyReJ17F0YgjceqrkZaPM8YRo8h1fj1JdPc4ZOUg\r\nA5ASZ0h2ewIDAQABMA0GCSqGSIb3DQEBBQUAA4GBACOUglBxJ80jzR3DSSMrgRav\r\n7deKUPShEPC3tbVrc3LHPGpCEJUC309aK2mbMwz2jX78tr/ezePELKbyRggUvVgN\r\nB0XdIQkpR9X4mPdtFYkMiWKNVYKd79r0kolprgFPryhT3jsICIOnwE1Ur23Q+Fk2\r\nnizRS0HY4Q25JLCmsWWy\r\n-----END CERTIFICATE-----\r\n' } ``` To override the default client CN of `john doe jdoe123`, add another option for `clientCertificateCN`: ```js var pems = selfsigned.generate(null, { clientCertificate: true, clientCertificateCN: 'FooBar' }); ``` ## License MIT <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> <br> <br> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![builds][builds]][builds-url] [![builds2][builds2]][builds2-url] [![coverage][cover]][cover-url] [![licenses][licenses]][licenses-url] <br> <a href="https://dependabot.com/compatibility-score.html?dependency-name=webpack&package-manager=npm_and_yarn&new-version=latest"> <img src="https://api.dependabot.com/badges/compatibility_score?dependency-name=webpack&package-manager=npm_and_yarn&version-scheme=semver&target-version=latest"> </a> <a href="https://npmcharts.com/compare/webpack?minimal=true"> <img src="https://img.shields.io/npm/dm/webpack.svg"> </a> <a href="https://packagephobia.now.sh/result?p=webpack"> <img src="https://packagephobia.now.sh/badge?p=webpack" alt="install size"> </a> <a href="https://opencollective.com/webpack#backer"> <img src="https://opencollective.com/webpack/backers/badge.svg"> </a> <a href="https://opencollective.com/webpack#sponsors"> <img src="https://opencollective.com/webpack/sponsors/badge.svg"> </a> <a href="https://github.com/webpack/webpack/graphs/contributors"> <img src="https://img.shields.io/github/contributors/webpack/webpack.svg"> </a> <a href="https://gitter.im/webpack/webpack"> <img src="https://badges.gitter.im/webpack/webpack.svg"> </a> <h1>webpack</h1> <p> webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. </p> </div> ## Table of Contents 1. [Install](#install) 2. [Introduction](#introduction) 3. [Concepts](#concepts) 4. [Contributing](#contributing) 5. [Support](#support) 6. [Core Team](#core-team) 7. [Sponsoring](#sponsoring) 8. [Premium Partners](#premium-partners) 9. [Other Backers and Sponsors](#other-backers-and-sponsors) 10. [Gold Sponsors](#gold-sponsors) 11. [Silver Sponsors](#silver-sponsors) 12. [Bronze Sponsors](#bronze-sponsors) 13. [Backers](#backers) 14. [Special Thanks](#special-thanks-to) <h2 align="center">Install</h2> Install with npm: ```bash npm install --save-dev webpack ``` Install with yarn: ```bash yarn add webpack --dev ``` <h2 align="center">Introduction</h2> webpack is a bundler for modules. The main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. **TL;DR** * Bundles [ES Modules](http://www.2ality.com/2014/09/es6-modules-final.html), [CommonJS](http://wiki.commonjs.org/), and [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) modules (even combined). * Can create a single bundle or multiple chunks that are asynchronously loaded at runtime (to reduce initial loading time). * Dependencies are resolved during compilation, reducing the runtime size. * Loaders can preprocess files while compiling, e.g. TypeScript to JavaScript, Handlebars strings to compiled functions, images to Base64, etc. * Highly modular plugin system to do whatever else your application requires. ### Get Started Check out webpack's quick [**Get Started**](https://webpack.js.org/get-started/) guide and the [other guides](https://webpack.js.org/guides/). ### Browser Compatibility webpack supports all browsers that are [ES5-compliant](http://kangax.github.io/compat-table/es5/) (IE8 and below are not supported). webpack also needs `Promise` for `import()` and `require.ensure()`. If you want to support older browsers, you will need to [load a polyfill](https://webpack.js.org/guides/shimming/) before using these expressions. <h2 align="center">Concepts</h2> ### [Plugins](https://webpack.js.org/plugins/) webpack has a [rich plugin interface](https://webpack.js.org/plugins/). Most of the features within webpack itself use this plugin interface. This makes webpack very **flexible**. |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |[mini-css-extract-plugin][mini-css]|![mini-css-npm]|![mini-css-size]|Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS.| |[compression-webpack-plugin][compression]|![compression-npm]|![compression-size]|Prepares compressed versions of assets to serve them with Content-Encoding| |[i18n-webpack-plugin][i18n]|![i18n-npm]|![i18n-size]|Adds i18n support to your bundles| |[html-webpack-plugin][html-plugin]|![html-plugin-npm]|![html-plugin-size]| Simplifies creation of HTML files (`index.html`) to serve your bundles| |[extract-text-webpack-plugin][extract]|![extract-npm]|![extract-size]|Extract text from a bundle, or bundles, into a separate file| [common-npm]: https://img.shields.io/npm/v/webpack.svg [extract]: https://github.com/webpack/extract-text-webpack-plugin [extract-npm]: https://img.shields.io/npm/v/extract-text-webpack-plugin.svg [extract-size]: https://packagephobia.now.sh/badge?p=extract-text-webpack-plugin [mini-css]: https://github.com/webpack-contrib/mini-css-extract-plugin [mini-css-npm]: https://img.shields.io/npm/v/mini-css-extract-plugin.svg [mini-css-size]: https://packagephobia.now.sh/badge?p=mini-css-extract-plugin [component]: https://github.com/webpack/component-webpack-plugin [component-npm]: https://img.shields.io/npm/v/component-webpack-plugin.svg [component-size]: https://packagephobia.now.sh/badge?p=component-webpack-plugin [compression]: https://github.com/webpack/compression-webpack-plugin [compression-npm]: https://img.shields.io/npm/v/compression-webpack-plugin.svg [compression-size]: https://packagephobia.now.sh/badge?p=compression-webpack-plugin [i18n]: https://github.com/webpack/i18n-webpack-plugin [i18n-npm]: https://img.shields.io/npm/v/i18n-webpack-plugin.svg [i18n-size]: https://packagephobia.now.sh/badge?p=i18n-webpack-plugin [html-plugin]: https://github.com/ampedandwired/html-webpack-plugin [html-plugin-npm]: https://img.shields.io/npm/v/html-webpack-plugin.svg [html-plugin-size]: https://packagephobia.now.sh/badge?p=html-webpack-plugin ### [Loaders](https://webpack.js.org/loaders/) webpack enables use of loaders to preprocess files. This allows you to bundle **any static resource** way beyond JavaScript. You can easily [write your own loaders](https://webpack.js.org/api/loaders/) using Node.js. Loaders are activated by using `loadername!` prefixes in `require()` statements, or are automatically applied via regex from your webpack configuration. #### Files |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |[raw-loader][raw]|![raw-npm]|![raw-size]|Loads raw content of a file (utf-8)| |[val-loader][val]|![val-npm]|![val-size]|Executes code as module and considers exports as JS code| |[url-loader][url]|![url-npm]|![url-size]|Works like the file loader, but can return a Data Url if the file is smaller than a limit| |[file-loader][file]|![file-npm]|![file-size]|Emits the file into the output folder and returns the (relative) url| [raw]: https://github.com/webpack/raw-loader [raw-npm]: https://img.shields.io/npm/v/raw-loader.svg [raw-size]: https://packagephobia.now.sh/badge?p=raw-loader [val]: https://github.com/webpack/val-loader [val-npm]: https://img.shields.io/npm/v/val-loader.svg [val-size]: https://packagephobia.now.sh/badge?p=val-loader [url]: https://github.com/webpack/url-loader [url-npm]: https://img.shields.io/npm/v/url-loader.svg [url-size]: https://packagephobia.now.sh/badge?p=url-loader [file]: https://github.com/webpack/file-loader [file-npm]: https://img.shields.io/npm/v/file-loader.svg [file-size]: https://packagephobia.now.sh/badge?p=file-loader #### JSON |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/webpack/json-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/json.svg"></a>|![json-npm]|![json-size]|Loads a JSON file (included by default)| |<a href="https://github.com/webpack/json5-loader"><img width="48" height="10.656" src="https://cdn.rawgit.com/json5/json5-logo/master/json5-logo.svg"></a>|![json5-npm]|![json5-size]|Loads and transpiles a JSON 5 file| |<a href="https://github.com/awnist/cson-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![cson-npm]|![cson-size]|Loads and transpiles a CSON file| [json-npm]: https://img.shields.io/npm/v/json-loader.svg [json-size]: https://packagephobia.now.sh/badge?p=json-loader [json5-npm]: https://img.shields.io/npm/v/json5-loader.svg [json5-size]: https://packagephobia.now.sh/badge?p=json5-loader [cson-npm]: https://img.shields.io/npm/v/cson-loader.svg [cson-size]: https://packagephobia.now.sh/badge?p=cson-loader #### Transpiling |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/webpack/script-loader">`<script>`</a>|![script-npm]|![script-size]|Executes a JavaScript file once in global context (like in script tag), `require()`s are not parsed| |<a href="https://github.com/babel/babel-loader"><img width="48" height="48" title="babel-loader" src="https://worldvectorlogo.com/logos/babel-10.svg"></a>|![babel-npm]|![babel-size]|Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a>| |<a href="https://github.com/jupl/traceur-loader"><img width="48" height="48" src="https://google.github.com/traceur-compiler/logo/tc.svg"></a>|![traceur-npm]|![traceur-size]|Loads ES2015+ code and transpiles to ES5 using [Traceur](https://github.com/google/traceur-compiler)| |<a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a>|![type-npm]|![type-size]|Loads TypeScript like JavaScript| |[`awesome-typescript-loader`](https://github.com/s-panferov/awesome-typescript-loader)|![awesome-typescript-npm]|![awesome-typescript-size]|Awesome TypeScript loader for webpack| |<a href="https://github.com/webpack/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a>|![coffee-npm]|![coffee-size]|Loads CoffeeScript like JavaScript| [script-npm]: https://img.shields.io/npm/v/script-loader.svg [script-size]: https://packagephobia.now.sh/badge?p=script-loader [babel-npm]: https://img.shields.io/npm/v/babel-loader.svg [babel-size]: https://packagephobia.now.sh/badge?p=babel-loader [traceur-npm]: https://img.shields.io/npm/v/traceur-loader.svg [traceur-size]: https://packagephobia.now.sh/badge?p=traceur-loader [coffee-npm]: https://img.shields.io/npm/v/coffee-loader.svg [coffee-size]: https://packagephobia.now.sh/badge?p=coffee-loader [type-npm]: https://img.shields.io/npm/v/ts-loader.svg [type-size]: https://packagephobia.now.sh/badge?p=ts-loader [awesome-typescript-npm]: https://img.shields.io/npm/v/awesome-typescript-loader.svg [awesome-typescript-size]: https://packagephobia.now.sh/badge?p=awesome-typescript-loader #### Templating |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/webpack/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a>|![html-npm]|![html-size]|Exports HTML as string, requires references to static resources| |<a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a>|![pug-npm]|![pug-size]|Loads Pug templates and returns a function| |<a href="https://github.com/webpack/jade-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/jade-3.svg"></a>|![jade-npm]|![jade-size]|Loads Jade templates and returns a function| |<a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a>|![md-npm]|![md-size]|Compiles Markdown to HTML| |<a href="https://github.com/posthtml/posthtml-loader"><img width="48" height="48" src="http://posthtml.github.io/posthtml/logo.svg"></a>|![posthtml-npm]|![posthtml-size]|Loads and transforms a HTML file using [PostHTML](https://github.com/posthtml/posthtml)| |<a href="https://github.com/altano/handlebars-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/handlebars-1.svg"></a>|![hbs-npm]|![hbs-size]| Compiles Handlebars to HTML| [html-npm]: https://img.shields.io/npm/v/html-loader.svg [html-size]: https://packagephobia.now.sh/badge?p=html-loader [pug-npm]: https://img.shields.io/npm/v/pug-loader.svg [pug-size]: https://packagephobia.now.sh/badge?p=pug-loader [jade-npm]: https://img.shields.io/npm/v/jade-loader.svg [jade-size]: https://packagephobia.now.sh/badge?p=jade-loader [md-npm]: https://img.shields.io/npm/v/markdown-loader.svg [md-size]: https://packagephobia.now.sh/badge?p=markdown-loader [posthtml-npm]: https://img.shields.io/npm/v/posthtml-loader.svg [posthtml-size]: https://packagephobia.now.sh/badge?p=posthtml-loader [hbs-npm]: https://img.shields.io/npm/v/handlebars-loader.svg [hbs-size]: https://packagephobia.now.sh/badge?p=handlebars-loader #### Styling |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/webpack/style-loader">`<style>`</a>|![style-npm]|![style-size]|Add exports of a module as style to DOM| |<a href="https://github.com/webpack/css-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/css-3.svg"></a>|![css-npm]|![css-size]|Loads CSS file with resolved imports and returns CSS code| |<a href="https://github.com/webpack/less-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/less-63.svg"></a>|![less-npm]|![less-size]|Loads and compiles a LESS file| |<a href="https://github.com/jtangelder/sass-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/sass-1.svg"></a>|![sass-npm]|![sass-size]|Loads and compiles a Sass/SCSS file| |<a href="https://github.com/shama/stylus-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/stylus.svg"></a>|![stylus-npm]|![stylus-size]|Loads and compiles a Stylus file| |<a href="https://github.com/postcss/postcss-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/postcss.svg"></a>|![postcss-npm]|![postcss-size]|Loads and transforms a CSS/SSS file using [PostCSS](http://postcss.org)| [style-npm]: https://img.shields.io/npm/v/style-loader.svg [style-size]: https://packagephobia.now.sh/badge?p=style-loader [css-npm]: https://img.shields.io/npm/v/css-loader.svg [css-size]: https://packagephobia.now.sh/badge?p=css-loader [less-npm]: https://img.shields.io/npm/v/less-loader.svg [less-size]: https://packagephobia.now.sh/badge?p=less-loader [sass-npm]: https://img.shields.io/npm/v/sass-loader.svg [sass-size]: https://packagephobia.now.sh/badge?p=sass-loader [stylus-npm]: https://img.shields.io/npm/v/stylus-loader.svg [stylus-size]: https://packagephobia.now.sh/badge?p=stylus-loader [postcss-npm]: https://img.shields.io/npm/v/postcss-loader.svg [postcss-size]: https://packagephobia.now.sh/badge?p=postcss-loader #### Linting & Testing |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/webpack/mocha-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/mocha.svg"></a>|![mocha-npm]|![mocha-size]|Tests with mocha (Browser/NodeJS)| |<a href="https://github.com/MoOx/eslint-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/eslint.svg"></a>|![eslint-npm]|![eslint-size]|PreLoader for linting code using ESLint| |<a href="https://github.com/webpack-contrib/jshint-loader"><img width="48" height="20.64" src="http://jshint.com/res/jshint-dark.png"></a>|![jshint-npm]|![jshint-size]|PreLoader for linting code using JSHint| [mocha-npm]: https://img.shields.io/npm/v/mocha-loader.svg [mocha-size]: https://packagephobia.now.sh/badge?p=mocha-loader [eslint-npm]: https://img.shields.io/npm/v/eslint-loader.svg [eslint-size]: https://packagephobia.now.sh/badge?p=eslint-loader [jshint-npm]: https://img.shields.io/npm/v/jshint-loader.svg [jshint-size]: https://packagephobia.now.sh/badge?p=jshint-loader [jscs-npm]: https://img.shields.io/npm/v/jscs-loader.svg [jscs-size]: https://packagephobia.now.sh/badge?p=jscs-loader #### Frameworks |Name|Status|Install Size|Description| |:--:|:----:|:----------:|:----------| |<a href="https://github.com/vuejs/vue-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/vue-9.svg"></a>|![vue-npm]|![vue-size]|Loads and compiles Vue Components| |<a href="https://github.com/webpack-contrib/polymer-webpack-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/polymer.svg"></a>|![polymer-npm]|![polymer-size]|Process HTML & CSS with preprocessor of choice and `require()` Web Components like first-class modules| |<a href="https://github.com/TheLarkInn/angular2-template-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/angular-icon-1.svg"></a>|![angular-npm]|![angular-size]| Loads and compiles Angular 2 Components| |<a href="https://github.com/riot/tag-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/riot.svg"></a>|![riot-npm]|![riot-size]| Riot official webpack loader| [vue-npm]: https://img.shields.io/npm/v/vue-loader.svg [vue-size]: https://packagephobia.now.sh/badge?p=vue-loader [polymer-npm]: https://img.shields.io/npm/v/polymer-webpack-loader.svg [polymer-size]: https://packagephobia.now.sh/badge?p=polymer-webpack-loader [angular-npm]: https://img.shields.io/npm/v/angular2-template-loader.svg [angular-size]: https://packagephobia.now.sh/badge?p=angular2-template-loader [riot-npm]: https://img.shields.io/npm/v/riot-tag-loader.svg [riot-size]: https://packagephobia.now.sh/badge?p=riot-tag-loader ### Performance webpack uses async I/O and has multiple caching levels. This makes webpack fast and incredibly **fast** on incremental compilations. ### Module Formats webpack supports ES2015+, CommonJS and AMD modules **out of the box**. It performs clever static analysis on the AST of your code. It even has an evaluation engine to evaluate simple expressions. This allows you to **support most existing libraries** out of the box. ### [Code Splitting](https://webpack.js.org/guides/code-splitting/) webpack allows you to split your codebase into multiple chunks. Chunks are loaded asynchronously at runtime. This reduces the initial loading time. ### [Optimizations](https://webpack.js.org/guides/production-build/) webpack can do many optimizations to **reduce the output size of your JavaScript** by deduplicating frequently used modules, minifying, and giving you full control of what is loaded initially and what is loaded at runtime through code splitting. It can also make your code chunks **cache friendly** by using hashes. <h2 align="center">Contributing</h2> **We want contributing to webpack to be fun, enjoyable, and educational for anyone, and everyone.** We have a [vibrant ecosystem](https://medium.com/webpack/contributors-guide/home) that spans beyond this single repo. We welcome you to check out any of the repositories in [our organization](http://github.com/webpack) or [webpack-contrib organization](http://github.com/webpack-contrib) which houses all of our loaders and plugins. Contributions go far beyond pull requests and commits. Although we love giving you the opportunity to put your stamp on webpack, we also are thrilled to receive a variety of other contributions including: * [Documentation](https://github.com/webpack/webpack.js.org) updates, enhancements, designs, or bugfixes * Spelling or grammar fixes * README.md corrections or redesigns * Adding unit, or functional tests * Triaging GitHub issues -- especially determining whether an issue still persists or is reproducible. * [Searching #webpack on twitter](https://twitter.com/search?q=webpack) and helping someone else who needs help * Teaching others how to contribute to one of the many webpack's repos! * [Blogging, speaking about, or creating tutorials](https://github.com/webpack-contrib/awesome-webpack) about one of webpack's many features. * Helping others in our webpack [gitter channel](https://gitter.im/webpack/webpack). If you are worried or don't know where to start, you can **always** reach out to [Sean Larkin (@TheLarkInn) on Twitter](https://twitter.com/thelarkinn) or simply submit an issue and a maintainer can help give you guidance! We have also started a series on our [Medium Publication](https://medium.com/webpack) called [The Contributor's Guide to webpack](https://medium.com/webpack/contributors-guide/home). We welcome you to read it and post any questions or responses if you still need help. _Looking to speak about webpack?_ We'd **love** to review your talk abstract/CFP! You can email it to webpack [at] opencollective [dot] com and we can give pointers or tips!!! <h3 align="center">Creating your own plugins and loaders</h3> If you create a loader or plugin, we would <3 for you to open source it, and put it on npm. We follow the `x-loader`, `x-webpack-plugin` naming convention. <h2 align="center">Support</h2> We consider webpack to be a low-level tool used not only individually but also layered beneath other awesome tools. Because of its flexibility, webpack isn't always the _easiest_ entry-level solution, however we do believe it is the most powerful. That said, we're always looking for ways improve and simplify the tool without compromising functionality. If you have any ideas on ways to accomplish this, we're all ears! If you're just getting started, take a look at [our new docs and concepts page](https://webpack.js.org/concepts/). This has a high level overview that is great for beginners!! Looking for webpack 1 docs? Please check out the old [wiki](https://github.com/webpack/docs/wiki/contents), but note that this deprecated version is no longer supported. If you want to discuss something or just need help, [here is our Gitter room](https://gitter.im/webpack/webpack) where there are always individuals looking to help out! If you are still having difficulty, we would love for you to post a question to [StackOverflow with the webpack tag](https://stackoverflow.com/tags/webpack). It is much easier to answer questions that include your webpack.config.js and relevant files! So if you can provide them, we'd be extremely grateful (and more likely to help you find the answer!) If you are twitter savvy you can tweet #webpack with your question and someone should be able to reach out and help also. If you have discovered a 🐜 or have a feature suggestion, feel free to create an issue on Github. ### License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_large) <h2 align="center">Core Team</h2> <table> <tbody> <tr> <td align="center" valign="top"> <img width="150" height="150" src="https://github.com/sokra.png?s=150"> <br> <a href="https://github.com/sokra">Tobias Koppers</a> <p>Core</p> <br> <p>Founder of webpack</p> </td> <td align="center" valign="top"> <img width="150" height="150" src="https://github.com/jhnns.png?s=150"> <br> <a href="https://github.com/jhnns">Johannes Ewald</a> <p>Loaders &amp; Plugins</p> <br> <p>Early adopter of webpack</p> </td> <td align="center" width="20%" valign="top"> <img width="150" height="150" src="https://github.com/TheLarkInn.png?s=150"> <br> <a href="https://github.com/TheLarkInn">Sean T. Larkin</a> <p>Public Relations</p> <br> <p>Founder of the core team</p> </td> <td align="center" valign="top"> <img width="150" height="150" src="https://github.com/spacek33z.png?s=150"> <br> <a href="https://github.com/spacek33z">Kees Kluskens</a> <p>Development</p> <br> <p>Sponsor</p> <a href="https://codeyellow.nl/"> <img height="15px" src="https://cloud.githubusercontent.com/assets/1365881/20286583/ad62eb04-aac7-11e6-9c14-a0fef35b9b56.png"> </a> <br> </td> </tr> </tbody> </table> <h2 align="center">Sponsoring</h2> Most of the core team members, webpack contributors and contributors in the ecosystem do this open source work in their free time. If you use webpack for a serious task, and you'd like us to invest more time on it, please donate. This project increases your income/productivity too. It makes development and applications faster and it reduces the required bandwidth. This is how we use the donations: * Allow the core team to work on webpack * Thank contributors if they invested a large amount of time in contributing * Support projects in the ecosystem that are of great value for users * Support projects that are voted most (work in progress) * Infrastructure cost * Fees for money handling <h2 align="center">Premium Partners</h2> <div align="center"> <a href="https://www.ag-grid.com/?utm_source=webpack&utm_medium=banner&utm_campaign=sponsorship" target="_blank"><img align="center" src="https://raw.githubusercontent.com/webpack/media/2b399d58/horiz-banner-ad-ag-grid.png"> </a> </div> <h2 align="center">Other Backers and Sponsors</h2> Before we started using OpenCollective, donations were made anonymously. Now that we have made the switch, we would like to acknowledge these sponsors (and the ones who continue to donate using OpenCollective). If we've missed someone, please send us a PR, and we'll add you to this list. <div align="center"> [Google Angular Team](https://angular.io/), [Architects.io](http://architects.io/), <a href="https://moonmail.io" target="_blank" title="Email Marketing Software"><img src="https://static.moonmail.io/moonmail-logo.svg" height="30" alt="MoonMail"></a> <a href="https://monei.net" target="_blank" title="Best payment gateway rates"><img src="https://static.monei.net/monei-logo.svg" height="30" alt="MONEI"></a> </div> <h2 align="center">Gold Sponsors</h2> [Become a gold sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on Github with a link to your site. <div align="center"> <a href="https://opencollective.com/webpack/goldsponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/0/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/1/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/2/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/3/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/4/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/5/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/6/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/7/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/8/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/9/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/10/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/11/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/12/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/13/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/14/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/15/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/16/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/17/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/18/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/19/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/20/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/21/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/22/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/23/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/24/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/25/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/26/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/27/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/28/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/goldsponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/goldsponsor/29/avatar.svg?requireActive=false"></a> </div> <h2 align="center">Silver Sponsors</h2> [Become a silver sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on Github with a link to your site. <div align="center"> <a href="https://opencollective.com/webpack/silversponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/0/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/1/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/2/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/3/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/4/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/5/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/6/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/7/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/8/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/9/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/10/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/11/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/12/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/13/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/14/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/15/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/16/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/17/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/18/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/19/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/20/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/21/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/22/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/23/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/24/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/25/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/26/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/27/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/28/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/silversponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/silversponsor/29/avatar.svg?requireActive=false"></a> </div> <h2 align="center">Bronze Sponsors</h2> [Become a bronze sponsor](https://opencollective.com/webpack#sponsor) and get your logo on our README on Github with a link to your site. <div align="center"> <a href="https://opencollective.com/webpack/sponsor/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/0/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/1/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/2/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/3/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/4/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/5/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/6/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/7/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/8/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/9/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/10/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/11/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/12/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/13/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/14/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/15/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/16/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/17/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/18/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/19/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/20/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/21/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/22/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/23/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/24/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/25/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/26/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/27/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/28/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/29/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/30/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/30/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/31/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/31/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/32/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/32/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/33/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/33/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/34/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/34/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/35/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/35/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/36/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/36/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/37/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/37/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/38/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/38/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/39/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/39/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/40/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/40/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/41/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/41/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/42/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/42/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/43/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/43/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/44/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/44/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/45/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/45/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/46/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/46/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/47/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/47/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/48/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/48/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/49/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/49/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/50/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/50/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/51/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/51/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/52/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/52/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/53/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/53/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/54/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/54/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/55/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/55/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/56/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/56/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/57/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/57/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/58/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/58/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/59/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/59/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/60/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/60/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/61/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/61/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/62/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/62/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/63/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/63/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/64/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/64/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/65/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/65/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/66/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/66/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/67/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/67/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/68/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/68/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/69/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/69/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/70/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/70/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/71/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/71/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/72/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/72/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/73/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/73/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/74/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/74/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/75/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/75/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/76/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/76/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/77/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/77/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/78/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/78/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/79/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/79/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/80/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/80/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/81/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/81/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/82/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/82/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/83/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/83/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/84/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/84/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/85/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/85/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/86/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/86/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/87/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/87/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/88/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/88/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/89/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/89/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/90/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/90/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/91/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/91/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/92/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/92/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/93/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/93/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/94/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/94/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/95/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/95/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/96/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/96/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/97/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/97/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/98/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/98/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/99/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/99/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/sponsor/100/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/sponsor/100/avatar.svg?requireActive=false"></a> </div> <h2 align="center">Backers</h2> [Become a backer](https://opencollective.com/webpack#backer) and get your image on our README on Github with a link to your site. <a href="https://opencollective.com/webpack/backer/0/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/0/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/1/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/1/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/2/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/2/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/3/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/3/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/4/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/4/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/5/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/5/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/6/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/6/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/7/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/7/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/8/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/8/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/9/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/9/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/10/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/10/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/11/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/11/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/12/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/12/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/13/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/13/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/14/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/14/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/15/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/15/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/16/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/16/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/17/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/17/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/18/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/18/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/19/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/19/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/20/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/20/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/21/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/21/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/22/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/22/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/23/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/23/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/24/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/24/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/25/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/25/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/26/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/26/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/27/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/27/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/28/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/28/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/29/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/29/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/30/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/30/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/31/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/31/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/32/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/32/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/33/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/33/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/34/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/34/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/35/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/35/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/36/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/36/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/37/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/37/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/38/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/38/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/39/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/39/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/40/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/40/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/41/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/41/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/42/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/42/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/43/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/43/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/44/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/44/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/45/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/45/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/46/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/46/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/47/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/47/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/48/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/48/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/49/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/49/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/50/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/50/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/51/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/51/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/52/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/52/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/53/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/53/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/54/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/54/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/55/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/55/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/56/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/56/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/57/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/57/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/58/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/58/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/59/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/59/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/60/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/60/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/61/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/61/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/62/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/62/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/63/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/63/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/64/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/64/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/65/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/65/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/66/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/66/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/67/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/67/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/68/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/68/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/69/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/69/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/70/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/70/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/71/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/71/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/72/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/72/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/73/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/73/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/74/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/74/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/75/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/75/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/76/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/76/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/77/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/77/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/78/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/78/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/79/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/79/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/80/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/80/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/81/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/81/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/82/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/82/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/83/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/83/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/84/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/84/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/85/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/85/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/86/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/86/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/87/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/87/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/88/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/88/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/89/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/89/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/90/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/90/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/91/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/91/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/92/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/92/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/93/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/93/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/94/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/94/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/95/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/95/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/96/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/96/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/97/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/97/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/98/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/98/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/99/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/99/avatar.svg?requireActive=false"></a> <a href="https://opencollective.com/webpack/backer/100/website?requireActive=false" target="_blank"><img src="https://opencollective.com/webpack/backer/100/avatar.svg?requireActive=false"></a> <h2 align="center">Special Thanks to</h2> <p align="center">(In chronological order)</p> * @google for [Google Web Toolkit (GWT)](http://www.gwtproject.org/), which aims to compile Java to JavaScript. It features a similar [Code Splitting](http://www.gwtproject.org/doc/latest/DevGuideCodeSplitting.html) as webpack. * @medikoo for [modules-webmake](https://github.com/medikoo/modules-webmake), which is a similar project. webpack was born because I wanted Code Splitting for modules-webmake. Interestingly the [Code Splitting issue is still open](https://github.com/medikoo/modules-webmake/issues/7) (thanks also to @Phoscur for the discussion). * @substack for [browserify](http://browserify.org/), which is a similar project and source for many ideas. * @jrburke for [require.js](http://requirejs.org/), which is a similar project and source for many ideas. * @defunctzombie for the [browser-field spec](https://gist.github.com/defunctzombie/4339901), which makes modules available for node.js, browserify and webpack. * Every early webpack user, which contributed to webpack by writing issues or PRs. You influenced the direction... * @shama, @jhnns and @sokra for maintaining this project * Everyone who has written a loader for webpack. You are the ecosystem... * Everyone I forgot to mention here, but also influenced webpack. [npm]: https://img.shields.io/npm/v/webpack.svg [npm-url]: https://npmjs.com/package/webpack [node]: https://img.shields.io/node/v/webpack.svg [node-url]: https://nodejs.org [deps]: https://img.shields.io/david/webpack/webpack.svg [deps-url]: https://david-dm.org/webpack/webpack [tests]: https://img.shields.io/travis/webpack/webpack/master.svg [tests-url]: https://travis-ci.org/webpack/webpack [builds-url]: https://ci.appveyor.com/project/sokra/webpack/branch/master [builds]: https://ci.appveyor.com/api/projects/status/github/webpack/webpack?svg=true [builds2]: https://dev.azure.com/webpack/webpack/_apis/build/status/webpack.webpack [builds2-url]: https://dev.azure.com/webpack/webpack/_build/latest?definitionId=3 [licenses-url]: https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack?ref=badge_shield [licenses]: https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fwebpack%2Fwebpack.svg?type=shield [cover]: https://img.shields.io/coveralls/webpack/webpack.svg [cover-url]: https://coveralls.io/r/webpack/webpack/ # mime-db [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] This is a database of all mime types. It consists of a single, public JSON file and does not include any logic, allowing it to remain as un-opinionated as possible with an API. It aggregates data from the following sources: - http://www.iana.org/assignments/media-types/media-types.xhtml - http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - http://hg.nginx.org/nginx/raw-file/default/conf/mime.types ## Installation ```bash npm install mime-db ``` ### Database Download If you're crazy enough to use this in the browser, you can just grab the JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the JSON format may change in the future. ``` https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json ``` ## Usage ```js var db = require('mime-db'); // grab data on .js files var data = db['application/javascript']; ``` ## Data Structure The JSON file is a map lookup for lowercased mime types. Each mime type has the following properties: - `.source` - where the mime type is defined. If not set, it's probably a custom media type. - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) - `.extensions[]` - known extensions associated with this mime type. - `.compressible` - whether a file of this type can be gzipped. - `.charset` - the default charset associated with this type, if any. If unknown, every property could be `undefined`. ## Contributing To edit the database, only make PRs against `src/custom.json` or `src/custom-suffix.json`. The `src/custom.json` file is a JSON object with the MIME type as the keys and the values being an object with the following keys: - `compressible` - leave out if you don't know, otherwise `true`/`false` to indicate whether the data represented by the type is typically compressible. - `extensions` - include an array of file extensions that are associated with the type. - `notes` - human-readable notes about the type, typically what the type is. - `sources` - include an array of URLs of where the MIME type and the associated extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); links to type aggregating sites and Wikipedia are _not acceptable_. To update the build, run `npm run build`. ## Adding Custom Media Types The best way to get new media types included in this library is to register them with the IANA. The community registration procedure is outlined in [RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types registered with the IANA are automatically pulled into this library. [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master [node-image]: https://badgen.net/npm/node/mime-db [node-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-db [npm-url]: https://npmjs.org/package/mime-db [npm-version-image]: https://badgen.net/npm/v/mime-db [travis-image]: https://badgen.net/travis/jshttp/mime-db/master [travis-url]: https://travis-ci.org/jshttp/mime-db # Worker Farm [![Build Status](https://secure.travis-ci.org/rvagg/node-worker-farm.png)](http://travis-ci.org/rvagg/node-worker-farm) [![NPM](https://nodei.co/npm/worker-farm.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/worker-farm/) [![NPM](https://nodei.co/npm-dl/worker-farm.png?months=6&height=3)](https://nodei.co/npm/worker-farm/) Distribute processing tasks to child processes with an über-simple API and baked-in durability & custom concurrency options. *Available in npm as <strong>worker-farm</strong>*. ## Example Given a file, *child.js*: ```js module.exports = function (inp, callback) { callback(null, inp + ' BAR (' + process.pid + ')') } ``` And a main file: ```js var workerFarm = require('worker-farm') , workers = workerFarm(require.resolve('./child')) , ret = 0 for (var i = 0; i < 10; i++) { workers('#' + i + ' FOO', function (err, outp) { console.log(outp) if (++ret == 10) workerFarm.end(workers) }) } ``` We'll get an output something like the following: ``` #1 FOO BAR (8546) #0 FOO BAR (8545) #8 FOO BAR (8545) #9 FOO BAR (8546) #2 FOO BAR (8548) #4 FOO BAR (8551) #3 FOO BAR (8549) #6 FOO BAR (8555) #5 FOO BAR (8553) #7 FOO BAR (8557) ``` This example is contained in the *[examples/basic](https://github.com/rvagg/node-worker-farm/tree/master/examples/basic/)* directory. ### Example #1: Estimating π using child workers You will also find a more complex example in *[examples/pi](https://github.com/rvagg/node-worker-farm/tree/master/examples/pi/)* that estimates the value of **π** by using a Monte Carlo *area-under-the-curve* method and compares the speed of doing it all in-process vs using child workers to complete separate portions. Running `node examples/pi` will give you something like: ``` Doing it the slow (single-process) way... π ≈ 3.1416269360000006 (0.0000342824102075312 away from actual!) took 8341 milliseconds Doing it the fast (multi-process) way... π ≈ 3.1416233600000036 (0.00003070641021052367 away from actual!) took 1985 milliseconds ``` ## Durability An important feature of Worker Farm is **call durability**. If a child process dies for any reason during the execution of call(s), those calls will be re-queued and taken care of by other child processes. In this way, when you ask for something to be done, unless there is something *seriously* wrong with what you're doing, you should get a result on your callback function. ## My use-case There are other libraries for managing worker processes available but my use-case was fairly specific: I need to make heavy use of the [node-java](https://github.com/nearinfinity/node-java) library to interact with JVM code. Unfortunately, because the JVM garbage collector is so difficult to interact with, it's prone to killing your Node process when the GC kicks under heavy load. For safety I needed a durable way to make calls so that (1) it wouldn't kill my main process and (2) any calls that weren't successful would be resubmitted for processing. Worker Farm allows me to spin up multiple JVMs to be controlled by Node, and have a single, uncomplicated API that acts the same way as an in-process API and the calls will be taken care of by a child process even if an error kills a child process while it is working as the call will simply be passed to a new child process. **But**, don't think that Worker Farm is specific to that use-case, it's designed to be very generic and simple to adapt to anything requiring the use of child Node processes. ## API Worker Farm exports a main function and an `end()` method. The main function sets up a "farm" of coordinated child-process workers and it can be used to instantiate multiple farms, all operating independently. ### workerFarm([options, ]pathToModule[, exportedMethods]) In its most basic form, you call `workerFarm()` with the path to a module file to be invoked by the child process. You should use an **absolute path** to the module file, the best way to obtain the path is with `require.resolve('./path/to/module')`, this function can be used in exactly the same way as `require('./path/to/module')` but it returns an absolute path. #### `exportedMethods` If your module exports a single function on `module.exports` then you should omit the final parameter. However, if you are exporting multiple functions on `module.exports` then you should list them in an Array of Strings: ```js var workers = workerFarm(require.resolve('./mod'), [ 'doSomething', 'doSomethingElse' ]) workers.doSomething(function () {}) workers.doSomethingElse(function () {}) ``` Listing the available methods will instruct Worker Farm what API to provide you with on the returned object. If you don't list a `exportedMethods` Array then you'll get a single callable function to use; but if you list the available methods then you'll get an object with callable functions by those names. **It is assumed that each function you call on your child module will take a `callback` function as the last argument.** #### `options` If you don't provide an `options` object then the following defaults will be used: ```js { workerOptions : {} , maxCallsPerWorker : Infinity , maxConcurrentWorkers : require('os').cpus().length , maxConcurrentCallsPerWorker : 10 , maxConcurrentCalls : Infinity , maxCallTime : Infinity , maxRetries : Infinity , autoStart : false } ``` * **<code>workerOptions</code>** allows you to customize all the parameters passed to child nodes. This object supports [all possible options of `child_process.fork`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options). The default options passed are the parent `execArgv`, `cwd` and `env`. Any (or all) of them can be overridden, and others can be added as well. * **<code>maxCallsPerWorker</code>** allows you to control the lifespan of your child processes. A positive number will indicate that you only want each child to accept that many calls before it is terminated. This may be useful if you need to control memory leaks or similar in child processes. * **<code>maxConcurrentWorkers</code>** will set the number of child processes to maintain concurrently. By default it is set to the number of CPUs available on the current system, but it can be any reasonable number, including `1`. * **<code>maxConcurrentCallsPerWorker</code>** allows you to control the *concurrency* of individual child processes. Calls are placed into a queue and farmed out to child processes according to the number of calls they are allowed to handle concurrently. It is arbitrarily set to 10 by default so that calls are shared relatively evenly across workers, however if your calls predictably take a similar amount of time then you could set it to `Infinity` and Worker Farm won't queue any calls but spread them evenly across child processes and let them go at it. If your calls aren't I/O bound then it won't matter what value you use here as the individual workers won't be able to execute more than a single call at a time. * **<code>maxConcurrentCalls</code>** allows you to control the maximum number of calls in the queue&mdash;either actively being processed or waiting for a worker to be processed. `Infinity` indicates no limit but if you have conditions that may endlessly queue jobs and you need to set a limit then provide a `>0` value and any calls that push the limit will return on their callback with a `MaxConcurrentCallsError` error (check `err.type == 'MaxConcurrentCallsError'`). * **<code>maxCallTime</code>** *(use with caution, understand what this does before you use it!)* when `!== Infinity`, will cap a time, in milliseconds, that *any single call* can take to execute in a worker. If this time limit is exceeded by just a single call then the worker running that call will be killed and any calls running on that worker will have their callbacks returned with a `TimeoutError` (check `err.type == 'TimeoutError'`). If you are running with `maxConcurrentCallsPerWorker` value greater than `1` then **all calls currently executing** will fail and will be automatically resubmitted uless you've changed the `maxRetries` option. Use this if you have jobs that may potentially end in infinite loops that you can't programatically end with your child code. Preferably run this with a `maxConcurrentCallsPerWorker` so you don't interrupt other calls when you have a timeout. This timeout operates on a per-call basis but will interrupt a whole worker. * **<code>maxRetries</code>** allows you to control the max number of call requeues after worker termination (unexpected or timeout). By default this option is set to `Infinity` which means that each call of each terminated worker will always be auto requeued. When the number of retries exceeds `maxRetries` value, the job callback will be executed with a `ProcessTerminatedError`. Note that if you are running with finite `maxCallTime` and `maxConcurrentCallsPerWorkers` greater than `1` then any `TimeoutError` will increase the retries counter *for each* concurrent call of the terminated worker. * **<code>autoStart</code>** when set to `true` will start the workers as early as possible. Use this when your workers have to do expensive initialization. That way they'll be ready when the first request comes through. ### workerFarm.end(farm) Child processes stay alive waiting for jobs indefinitely and your farm manager will stay alive managing its workers, so if you need it to stop then you have to do so explicitly. If you send your farm API to `workerFarm.end()` then it'll cleanly end your worker processes. Note though that it's a *soft* ending so it'll wait for child processes to finish what they are working on before asking them to die. Any calls that are queued and not yet being handled by a child process will be discarded. `end()` only waits for those currently in progress. Once you end a farm, it won't handle any more calls, so don't even try! ## Related * [farm-cli](https://github.com/Kikobeats/farm-cli) – Launch a farm of workers from CLI. ## License Worker Farm is Copyright (c) 2014 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. # true-case-path ## Usage `trueCasePathSync(<fileSystemPath>)` ## Description Given a possibly case-variant version of an existing filesystem path, returns the case-exact, normalized version as stored in the filesystem. If the input path is a globbing *pattern* as defined by the 'glob' npm package, only the 1st match, if any, is returned. Only a literal input path guarantees an unambiguous result. If no matching path exists, undefined is returned. On case-SENSITIVE filesystems, a match will also be found, but if case variations of a given path exist, it is undefined which match is returned. ## Platforms Windows, OSX, and Linux (though note the limitations with case-insensitive filesystems). ## Limitations - Paths starting with `'./'` are acceptable, but paths starting with `'../'` are not - when in doubt, resolve with `fs.realPathSync()` first. An initial `'.'` and *interior* `'..'` instances are normalized, but a relative input path still results in a relative output path. If you want to ensure an absolute output path, apply `fs.realPathSync()` to the result. - On Windows, no attempt is made to case-correct the drive letter or UNC-share component of the path. - Unicode support: - Be sure to use UTF8 source-code files (with a BOM on Windows) - On OSX, the input path is automatically converted to NFD Unicode form to match how the filesystem stores names, but note that the result will invariably be NFD too (which makes no difference for ASCII-characters-only names). ## Examples ``` const trueCasePathSync = require('true-case-path') trueCasePathSync('/users/guest') // OSX: -> '/Users/Guest' trueCasePathSync('c:\\users\\all users') // Windows: -> 'c:\Users\All Users' ``` ## Attribution The code for this project was sourced from [http://stackoverflow.com/a/33139702/45375](http://stackoverflow.com/a/33139702/45375) # regenerate-unicode-properties [![Build status](https://travis-ci.org/mathiasbynens/regenerate-unicode-properties.svg?branch=master)](https://travis-ci.org/mathiasbynens/regenerate-unicode-properties) _regenerate-unicode-properties_ is a collection of [Regenerate](https://github.com/mathiasbynens/regenerate) sets for [various Unicode properties](https://github.com/tc39/proposal-regexp-unicode-property-escapes). ## Installation To use _regenerate-unicode-properties_ programmatically, install it as a dependency via [npm](https://www.npmjs.com/): ```bash $ npm install regenerate-unicode-properties ``` ## Usage To get a map of supported properties and their values: ```js const properties = require('regenerate-unicode-properties'); ``` To get a specific Regenerate set: ```js // Examples: const Lu = require('regenerate-unicode-properties/General_Category/Uppercase_Letter.js'); const Greek = require('regenerate-unicode-properties/Script_Extensions/Greek.js'); ``` To get the Unicode version the data was based on: ```js const unicodeVersion = require('regenerate-unicode-properties/unicode-version.js'); ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _regenerate-unicode-properties_ is available under the [MIT](https://mths.be/mit) license. # unicode-canonical-property-names-ecmascript [![Build status](https://travis-ci.org/mathiasbynens/unicode-canonical-property-names-ecmascript.svg?branch=master)](https://travis-ci.org/mathiasbynens/unicode-canonical-property-names-ecmascript) _unicode-canonical-property-names-ecmascript_ exports the set of canonical Unicode property names that are supported in [ECMAScript RegExp property escapes](https://github.com/tc39/proposal-regexp-unicode-property-escapes). ## Installation To use _unicode-canonical-property-names-ecmascript_, install it as a dependency via [npm](https://www.npmjs.com/): ```bash $ npm install unicode-canonical-property-names-ecmascript ``` Then, `require` it: ```js const properties = require('unicode-canonical-property-names-ecmascript'); ``` ## Example ```js properties.has('ID_Start'); // → true properties.has('IDS'); // → false ``` ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License _unicode-canonical-property-names-ecmascript_ is available under the [MIT](https://mths.be/mit) license. # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat)](https://travis-ci.org/jonschlinkert/isobject) Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject --save ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](http://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## Related projects You might also be interested in these projects: [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep) * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow) * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object) * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/isobject/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/isobject/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v0.9.0, on April 25, 2016._ 1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, false positives and missed opportunities. The input files are rewritten in place. Make sure that you have backups. You will have to manually review the changes afterwards and do some touchups. ```sh $ tools/1to2.js Usage: 1to2 [options] <file ...> Options: -h, --help output usage information -V, --version output the version number ``` # define-property [![NPM version](https://badge.fury.io/js/define-property.svg)](http://badge.fury.io/js/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i define-property --save ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## Related projects * [delegate-object](https://www.npmjs.com/package/delegate-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/delegate-object) | [homepage](https://github.com/doowb/delegate-object) * [forward-object](https://www.npmjs.com/package/forward-object): Copy properties from an object to another object, where properties with function values will be… [more](https://www.npmjs.com/package/forward-object) | [homepage](https://github.com/doowb/forward-object) * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep) * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://www.npmjs.com/package/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object) ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/define-property/issues/new). ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on August 31, 2015._ Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # url-parse [![Made by unshift](https://img.shields.io/badge/made%20by-unshift-00ffcc.svg?style=flat-square)](http://unshift.io)[![Version npm](https://img.shields.io/npm/v/url-parse.svg?style=flat-square)](https://www.npmjs.com/package/url-parse)[![Build Status](https://img.shields.io/travis/unshiftio/url-parse/master.svg?style=flat-square)](https://travis-ci.org/unshiftio/url-parse)[![Dependencies](https://img.shields.io/david/unshiftio/url-parse.svg?style=flat-square)](https://david-dm.org/unshiftio/url-parse)[![Coverage Status](https://img.shields.io/coveralls/unshiftio/url-parse/master.svg?style=flat-square)](https://coveralls.io/r/unshiftio/url-parse?branch=master)[![IRC channel](https://img.shields.io/badge/IRC-irc.freenode.net%23unshift-00a8ff.svg?style=flat-square)](https://webchat.freenode.net/?channels=unshift) [![Sauce Test Status](https://saucelabs.com/browser-matrix/url-parse.svg)](https://saucelabs.com/u/url-parse) The `url-parse` method exposes two different API interfaces. The [`url`](https://nodejs.org/api/url.html) interface that you know from Node.js and the new [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL) interface that is available in the latest browsers. In version `0.1` we moved from a DOM based parsing solution, using the `<a>` element, to a full Regular Expression solution. The main reason for this was to make the URL parser available in different JavaScript environments as you don't always have access to the DOM. An example of such environment is the [`Worker`](https://developer.mozilla.org/en/docs/Web/API/Worker) interface. The RegExp based solution didn't work well as it required a lot of lookups causing major problems in FireFox. In version `1.0.0` we ditched the RegExp based solution in favor of a pure string parsing solution which chops up the URL into smaller pieces. This module still has a really small footprint as it has been designed to be used on the client side. In addition to URL parsing we also expose the bundled `querystringify` module. ## Installation This module is designed to be used using either browserify or Node.js it's released in the public npm registry and can be installed using: ``` npm install url-parse ``` ## Usage All examples assume that this library is bootstrapped using: ```js 'use strict'; var Url = require('url-parse'); ``` To parse an URL simply call the `URL` method with the URL that needs to be transformed into an object. ```js var url = new Url('https://github.com/foo/bar'); ``` The `new` keyword is optional but it will save you an extra function invocation. The constructor takes the following arguments: - `url` (`String`): A string representing an absolute or relative URL. - `baseURL` (`Object` | `String`): An object or string representing the base URL to use in case `url` is a relative URL. This argument is optional and defaults to [`location`](https://developer.mozilla.org/en-US/docs/Web/API/Location) in the browser. - `parser` (`Boolean` | `Function`): This argument is optional and specifies how to parse the query string. By default it is `false` so the query string is not parsed. If you pass `true` the query string is parsed using the embedded `querystringify` module. If you pass a function the query string will be parsed using this function. As said above we also support the Node.js interface so you can also use the library in this way: ```js 'use strict'; var parse = require('url-parse') , url = parse('https://github.com/foo/bar', true); ``` The returned `url` instance contains the following properties: - `protocol`: The protocol scheme of the URL (e.g. `http:`). - `slashes`: A boolean which indicates whether the `protocol` is followed by two forward slashes (`//`). - `auth`: Authentication information portion (e.g. `username:password`). - `username`: Username of basic authentication. - `password`: Password of basic authentication. - `host`: Host name with port number. - `hostname`: Host name without port number. - `port`: Optional port number. - `pathname`: URL path. - `query`: Parsed object containing query string, unless parsing is set to false. - `hash`: The "fragment" portion of the URL including the pound-sign (`#`). - `href`: The full URL. - `origin`: The origin of the URL. Note that when `url-parse` is used in a browser environment, it will default to using the browser's current window location as the base URL when parsing all inputs. To parse an input independently of the browser's current URL (e.g. for functionality parity with the library in a Node environment), pass an empty location object as the second parameter: ```js var parse = require('url-parse'); parse('hostname', {}); ``` ### Url.set(key, value) A simple helper function to change parts of the URL and propagating it through all properties. When you set a new `host` you want the same value to be applied to `port` if has a different port number, `hostname` so it has a correct name again and `href` so you have a complete URL. ```js var parsed = parse('http://google.com/parse-things'); parsed.set('hostname', 'yahoo.com'); console.log(parsed.href); // http://yahoo.com/parse-things ``` It's aware of default ports so you cannot set a port 80 on an URL which has `http` as protocol. ### Url.toString() The returned `url` object comes with a custom `toString` method which will generate a full URL again when called. The method accepts an extra function which will stringify the query string for you. If you don't supply a function we will use our default method. ```js var location = url.toString(); // http://example.com/whatever/?qs=32 ``` You would rarely need to use this method as the full URL is also available as `href` property. If you are using the `URL.set` method to make changes, this will automatically update. ## Testing The testing of this module is done in 3 different ways: 1. We have unit tests that run under Node.js. You can run these tests with the `npm test` command. 2. Code coverage can be run manually using `npm run coverage`. 3. For browser testing we use Sauce Labs and `zuul`. You can run browser tests using the `npm run test-browser` command. ## License [MIT](LICENSE) These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv-keywords folder. # compressible [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Compressible `Content-Type` / `mime` checking. ## Installation ```sh $ npm install compressible ``` ## API <!-- eslint-disable no-unused-vars --> ```js var compressible = require('compressible') ``` ### compressible(type) Checks if the given `Content-Type` is compressible. The `type` argument is expected to be a value MIME type or `Content-Type` string, though no validation is performed. The MIME is looked up in the [`mime-db`](https://www.npmjs.com/package/mime-db) and if there is compressible information in the database entry, that is returned. Otherwise, this module will fallback to `true` for the following types: * `text/*` * `*/*+json` * `*/*+text` * `*/*+xml` If this module is not sure if a type is specifically compressible or specifically uncompressible, `undefined` is returned. <!-- eslint-disable no-undef --> ```js compressible('text/html') // => true compressible('image/png') // => false ``` ## License [MIT](LICENSE) [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/compressible/master [coveralls-url]: https://coveralls.io/r/jshttp/compressible?branch=master [node-version-image]: https://badgen.net/npm/node/compressible [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/compressible [npm-url]: https://npmjs.org/package/compressible [npm-version-image]: https://badgen.net/npm/v/compressible [travis-image]: https://badgen.net/travis/jshttp/compressible/master [travis-url]: https://travis-ci.org/jshttp/compressible This package parses [SPDX license expression](https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60) strings describing license terms, like [package.json license strings](https://docs.npmjs.com/files/package.json#license), into consistently structured ECMAScript objects. The npm command-line interface depends on this package, as do many automatic license-audit tools. In a nutshell: ```javascript var parse = require('spdx-expression-parse') var assert = require('assert') assert.deepEqual( // Licensed under the terms of the Two-Clause BSD License. parse('BSD-2-Clause'), {license: 'BSD-2-Clause'} ) assert.throws(function () { // An invalid SPDX license expression. // Should be `Apache-2.0`. parse('Apache 2') }) assert.deepEqual( // Dual licensed under either: // - LGPL 2.1 // - a combination of Three-Clause BSD and MIT parse('(LGPL-2.1 OR BSD-3-Clause AND MIT)'), { left: {license: 'LGPL-2.1'}, conjunction: 'or', right: { left: {license: 'BSD-3-Clause'}, conjunction: 'and', right: {license: 'MIT'} } } ) ``` The syntax comes from the [Software Package Data eXchange (SPDX)](https://spdx.org/), a standard from the [Linux Foundation](https://www.linuxfoundation.org) for shareable data about software package license terms. SPDX aims to make sharing and auditing license data easy, especially for users of open-source software. The bulk of the SPDX standard describes syntax and semantics of XML metadata files. This package implements two lightweight, plain-text components of that larger standard: 1. The [license list](https://spdx.org/licenses), a mapping from specific string identifiers, like `Apache-2.0`, to standard form license texts and bolt-on license exceptions. The [spdx-license-ids](https://www.npmjs.com/package/spdx-exceptions) and [spdx-exceptions](https://www.npmjs.com/package/spdx-license-ids) packages implement the license list. `spdx-expression-parse` depends on and `require()`s them. Any license identifier from the license list is a valid license expression: ```javascript var identifiers = [] .concat(require('spdx-license-ids')) .concat(require('spdx-license-ids/deprecated')) identifiers.forEach(function (id) { assert.deepEqual(parse(id), {license: id}) }) ``` So is any license identifier `WITH` a standardized license exception: ```javascript identifiers.forEach(function (id) { require('spdx-exceptions').forEach(function (e) { assert.deepEqual( parse(id + ' WITH ' + e), {license: id, exception: e} ) }) }) ``` 2. The license expression language, for describing simple and complex license terms, like `MIT` for MIT-licensed and `(GPL-2.0 OR Apache-2.0)` for dual-licensing under GPL 2.0 and Apache 2.0. `spdx-expression-parse` itself implements license expression language, exporting a parser. ```javascript assert.deepEqual( // Licensed under a combination of: // - the MIT License AND // - a combination of: // - LGPL 2.1 (or a later version) AND // - Three-Clause BSD parse('(MIT AND (LGPL-2.1+ AND BSD-3-Clause))'), { left: {license: 'MIT'}, conjunction: 'and', right: { left: {license: 'LGPL-2.1', plus: true}, conjunction: 'and', right: {license: 'BSD-3-Clause'} } } ) ``` The Linux Foundation and its contributors license the SPDX standard under the terms of [the Creative Commons Attribution License 3.0 Unported (SPDX: "CC-BY-3.0")](http://spdx.org/licenses/CC-BY-3.0). "SPDX" is a United States federally registered trademark of the Linux Foundation. The authors of this package license their work under the terms of the MIT License. # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # finalhandler [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-image]][node-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Node.js function to invoke as the final step to respond to HTTP request. ## Installation This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install finalhandler ``` ## API <!-- eslint-disable no-unused-vars --> ```js var finalhandler = require('finalhandler') ``` ### finalhandler(req, res, [options]) Returns function to be invoked as the final step for the given `req` and `res`. This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will write out a 404 response to the `res`. If it is truthy, an error response will be written out to the `res`. When an error is written, the following information is added to the response: * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If this value is outside the 4xx or 5xx range, it will be set to 500. * The `res.statusMessage` is set according to the status code. * The body will be the HTML of the status code message if `env` is `'production'`, otherwise will be `err.stack`. * Any headers specified in an `err.headers` object. The final handler will also unpipe anything from `req` when it is invoked. #### options.env By default, the environment is determined by `NODE_ENV` variable, but it can be overridden by this option. #### options.onerror Provide a function to be called with the `err` when it exists. Can be used for writing errors to a central location without excessive function generation. Called as `onerror(err, req, res)`. ## Examples ### always 404 ```js var finalhandler = require('finalhandler') var http = require('http') var server = http.createServer(function (req, res) { var done = finalhandler(req, res) done() }) server.listen(3000) ``` ### perform simple action ```js var finalhandler = require('finalhandler') var fs = require('fs') var http = require('http') var server = http.createServer(function (req, res) { var done = finalhandler(req, res) fs.readFile('index.html', function (err, buf) { if (err) return done(err) res.setHeader('Content-Type', 'text/html') res.end(buf) }) }) server.listen(3000) ``` ### use with middleware-style functions ```js var finalhandler = require('finalhandler') var http = require('http') var serveStatic = require('serve-static') var serve = serveStatic('public') var server = http.createServer(function (req, res) { var done = finalhandler(req, res) serve(req, res, done) }) server.listen(3000) ``` ### keep log of all errors ```js var finalhandler = require('finalhandler') var fs = require('fs') var http = require('http') var server = http.createServer(function (req, res) { var done = finalhandler(req, res, {onerror: logerror}) fs.readFile('index.html', function (err, buf) { if (err) return done(err) res.setHeader('Content-Type', 'text/html') res.end(buf) }) }) server.listen(3000) function logerror (err) { console.error(err.stack || err.toString()) } ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/finalhandler.svg [npm-url]: https://npmjs.org/package/finalhandler [node-image]: https://img.shields.io/node/v/finalhandler.svg [node-url]: https://nodejs.org/en/download [travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg [travis-url]: https://travis-ci.org/pillarjs/finalhandler [coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg [coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master [downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg [downloads-url]: https://npmjs.org/package/finalhandler # es-to-primitive <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] ECMAScript “ToPrimitive” algorithm. Provides ES5 and ES2015 versions. When different versions of the spec conflict, the default export will be the latest version of the abstract operation. Alternative versions will also be available under an `es5`/`es2015` exported property if you require a specific version. ## Example ```js var toPrimitive = require('es-to-primitive'); var assert = require('assert'); assert(toPrimitive(function () {}) === String(function () {})); var date = new Date(); assert(toPrimitive(date) === String(date)); assert(toPrimitive({ valueOf: function () { return 3; } }) === 3); assert(toPrimitive(['a', 'b', 3]) === String(['a', 'b', 3])); var sym = Symbol(); assert(toPrimitive(Object(sym)) === sym); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/es-to-primitive [npm-version-svg]: http://versionbadg.es/ljharb/es-to-primitive.svg [travis-svg]: https://travis-ci.org/ljharb/es-to-primitive.svg [travis-url]: https://travis-ci.org/ljharb/es-to-primitive [deps-svg]: https://david-dm.org/ljharb/es-to-primitive.svg [deps-url]: https://david-dm.org/ljharb/es-to-primitive [dev-deps-svg]: https://david-dm.org/ljharb/es-to-primitive/dev-status.svg [dev-deps-url]: https://david-dm.org/ljharb/es-to-primitive#info=devDependencies [testling-svg]: https://ci.testling.com/ljharb/es-to-primitive.png [testling-url]: https://ci.testling.com/ljharb/es-to-primitive [npm-badge-png]: https://nodei.co/npm/es-to-primitive.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/es-to-primitive.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/es-to-primitive.svg [downloads-url]: http://npm-stat.com/charts.html?package=es-to-primitive # minimatch A minimal matching utility. [![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # prr [![Build Status](https://secure.travis-ci.org/rvagg/prr.png)](http://travis-ci.org/rvagg/prr) An sensible alternative to `Object.defineProperty()`. Available in npm and Ender as **prr**. ## Usage Set the property `'foo'` (`obj.foo`) to have the value `'bar'` with default options (`'enumerable'`, `'configurable'` and `'writable'` are all `false`): ```js prr(obj, 'foo', 'bar') ``` Adjust the default options: ```js prr(obj, 'foo', 'bar', { enumerable: true, writable: true }) ``` Do the same operation for multiple properties: ```js prr(obj, { one: 'one', two: 'two' }) // or with options: prr(obj, { one: 'one', two: 'two' }, { enumerable: true, writable: true }) ``` ### Simplify! But obviously, having to write out the full options object makes it nearly as bad as the original `Object.defineProperty()` so we can simplify. As an alternative method we can use an options string where each character represents a option: `'e'=='enumerable'`, `'c'=='configurable'` and `'w'=='writable'`: ```js prr(obj, 'foo', 'bar', 'ew') // enumerable and writable but not configurable // muliple properties: prr(obj, { one: 'one', two: 'two' }, 'ewc') // configurable too ``` ## Where can I use it? Anywhere! For pre-ES5 environments *prr* will simply fall-back to an `object[property] = value` so you can get close to what you want. *prr* is Ender-compatible so you can include it in your Ender build and `$.prr(...)` or `var prr = require('prr'); prr(...)`. ## Licence prr is Copyright (c) 2013 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licensed under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. # wbuf #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2014. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # has-values [![NPM version](https://img.shields.io/npm/v/has-values.svg?style=flat)](https://www.npmjs.com/package/has-values) [![NPM monthly downloads](https://img.shields.io/npm/dm/has-values.svg?style=flat)](https://npmjs.org/package/has-values) [![NPM total downloads](https://img.shields.io/npm/dt/has-values.svg?style=flat)](https://npmjs.org/package/has-values) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/has-values.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/has-values) > Returns true if any values exist, false if empty. Works for booleans, functions, numbers, strings, nulls, objects and arrays. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save has-values ``` ## Usage ```js var hasValue = require('has-values'); hasValue('a'); //=> true hasValue(''); //=> false hasValue(1); //=> true hasValue(0); //=> false hasValue({a: 'a'}}); //=> true hasValue({}); hasValue({foo: undefined}); //=> false hasValue({foo: null}); //=> true hasValue(['a']); //=> true hasValue([]); hasValue([[], []]); hasValue([[[]]]); //=> false hasValue(['foo']); hasValue([0]); //=> true hasValue(function(foo) {}); //=> true hasValue(function() {}); //=> true hasValue(true); //=> true hasValue(false); //=> true ``` ## isEmpty To test for empty values, do: ```js function isEmpty(o, isZero) { return !hasValue(o, isZero); } ``` ## Release history ### v1.0.0 * `zero` always returns true * `array` now recurses, so that an array of empty arrays will return `false` * `null` now returns true ## About ### Related projects * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value "Returns true if a value exists, false if empty. Works with deeply nested values using object paths.") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 19, 2017._ # `scheduler` This is a package for cooperative scheduling in a browser environment. It is currently used internally by React, but we plan to make it more generic. The public API for this package is not yet finalized. ### Thanks The React team thanks [Anton Podviaznikov](https://podviaznikov.com/) for donating the `scheduler` package name. # fill-range [![NPM version](https://img.shields.io/npm/v/fill-range.svg?style=flat)](https://www.npmjs.com/package/fill-range) [![NPM monthly downloads](https://img.shields.io/npm/dm/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![NPM total downloads](https://img.shields.io/npm/dt/fill-range.svg?style=flat)](https://npmjs.org/package/fill-range) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fill-range.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fill-range) > Fill in a range of numbers or letters, optionally passing an increment or `step` to use, or create a regex-compatible range with `options.toRegex` ## Table of Contents - [Install](#install) - [Usage](#usage) - [Examples](#examples) - [Options](#options) * [options.step](#optionsstep) * [options.strictRanges](#optionsstrictranges) * [options.stringify](#optionsstringify) * [options.toRegex](#optionstoregex) * [options.transform](#optionstransform) - [About](#about) _(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_ ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fill-range ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add fill-range ``` ## Usage Expands numbers and letters, optionally using a `step` as the last argument. _(Numbers may be defined as JavaScript numbers or strings)_. ```js var fill = require('fill-range'); fill(from, to[, step, options]); // examples console.log(fill('1', '10')); //=> '[ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10' ]' console.log(fill('1', '10', {toRegex: true})); //=> [1-9]|10 ``` **Params** * `from`: **{String|Number}** the number or letter to start with * `to`: **{String|Number}** the number or letter to end with * `step`: **{String|Number|Object|Function}** Optionally pass a [step](#optionsstep) to use. * `options`: **{Object|Function}**: See all available [options](#options) ## Examples By default, an array of values is returned. **Alphabetical ranges** ```js console.log(fill('a', 'e')); //=> ['a', 'b', 'c', 'd', 'e'] console.log(fill('A', 'E')); //=> [ 'A', 'B', 'C', 'D', 'E' ] ``` **Numerical ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill('1', '5')); //=> [ 1, 2, 3, 4, 5 ] ``` **Negative ranges** Numbers can be defined as actual numbers or strings. ```js console.log(fill('-5', '-1')); //=> [ '-5', '-4', '-3', '-2', '-1' ] console.log(fill('-5', '5')); //=> [ '-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5' ] ``` **Steps (increments)** ```js // numerical ranges with increments console.log(fill('0', '25', 4)); //=> [ '0', '4', '8', '12', '16', '20', '24' ] console.log(fill('0', '25', 5)); //=> [ '0', '5', '10', '15', '20', '25' ] console.log(fill('0', '25', 6)); //=> [ '0', '6', '12', '18', '24' ] // alphabetical ranges with increments console.log(fill('a', 'z', 4)); //=> [ 'a', 'e', 'i', 'm', 'q', 'u', 'y' ] console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 6)); //=> [ 'a', 'g', 'm', 's', 'y' ] ``` ## Options ### options.step **Type**: `number` (formatted as a string or number) **Default**: `undefined` **Description**: The increment to use for the range. Can be used with letters or numbers. **Example(s)** ```js // numbers console.log(fill('1', '10', 2)); //=> [ '1', '3', '5', '7', '9' ] console.log(fill('1', '10', 3)); //=> [ '1', '4', '7', '10' ] console.log(fill('1', '10', 4)); //=> [ '1', '5', '9' ] // letters console.log(fill('a', 'z', 5)); //=> [ 'a', 'f', 'k', 'p', 'u', 'z' ] console.log(fill('a', 'z', 7)); //=> [ 'a', 'h', 'o', 'v' ] console.log(fill('a', 'z', 9)); //=> [ 'a', 'j', 's' ] ``` ### options.strictRanges **Type**: `boolean` **Default**: `false` **Description**: By default, `null` is returned when an invalid range is passed. Enable this option to throw a `RangeError` on invalid ranges. **Example(s)** The following are all invalid: ```js fill('1.1', '2'); // decimals not supported in ranges fill('a', '2'); // incompatible range values fill(1, 10, 'foo'); // invalid "step" argument ``` ### options.stringify **Type**: `boolean` **Default**: `undefined` **Description**: Cast all returned values to strings. By default, integers are returned as numbers. **Example(s)** ```js console.log(fill(1, 5)); //=> [ 1, 2, 3, 4, 5 ] console.log(fill(1, 5, {stringify: true})); //=> [ '1', '2', '3', '4', '5' ] ``` ### options.toRegex **Type**: `boolean` **Default**: `undefined` **Description**: Create a regex-compatible source string, instead of expanding values to an array. **Example(s)** ```js // alphabetical range console.log(fill('a', 'e', {toRegex: true})); //=> '[a-e]' // alphabetical with step console.log(fill('a', 'z', 3, {toRegex: true})); //=> 'a|d|g|j|m|p|s|v|y' // numerical range console.log(fill('1', '100', {toRegex: true})); //=> '[1-9]|[1-9][0-9]|100' // numerical range with zero padding console.log(fill('000001', '100000', {toRegex: true})); //=> '0{5}[1-9]|0{4}[1-9][0-9]|0{3}[1-9][0-9]{2}|0{2}[1-9][0-9]{3}|0[1-9][0-9]{4}|100000' ``` ### options.transform **Type**: `function` **Default**: `undefined` **Description**: Customize each value in the returned array (or [string](#optionstoRegex)). _(you can also pass this function as the last argument to `fill()`)_. **Example(s)** ```js // increase padding by two var arr = fill('01', '05', function(val, a, b, step, idx, arr, options) { return repeat('0', (options.maxLength + 2) - val.length) + val; }); console.log(arr); //=> ['0001', '0002', '0003', '0004', '0005'] ``` ## About ### Related projects * [braces](https://www.npmjs.com/package/braces): Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fast, comprehensive, bash-like brace expansion implemented in JavaScript. Complete support for the Bash 4.3 braces specification, without sacrificing speed.") * [expand-range](https://www.npmjs.com/package/expand-range): Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See… [more](https://github.com/jonschlinkert/expand-range) | [homepage](https://github.com/jonschlinkert/expand-range "Fast, bash-like range expansion. Expand a range of numbers or letters, uppercase or lowercase. See the benchmarks. Used by micromatch.") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") * [to-regex-range](https://www.npmjs.com/package/to-regex-range): Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than… [more](https://github.com/jonschlinkert/to-regex-range) | [homepage](https://github.com/jonschlinkert/to-regex-range "Pass two numbers, get a regex-compatible source string for matching ranges. Validated against more than 2.87 million test assertions.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 103 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [paulmillr](https://github.com/paulmillr) | | 1 | [edorivai](https://github.com/edorivai) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 23, 2017._ # regex-not [![NPM version](https://img.shields.io/npm/v/regex-not.svg?style=flat)](https://www.npmjs.com/package/regex-not) [![NPM monthly downloads](https://img.shields.io/npm/dm/regex-not.svg?style=flat)](https://npmjs.org/package/regex-not) [![NPM total downloads](https://img.shields.io/npm/dt/regex-not.svg?style=flat)](https://npmjs.org/package/regex-not) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/regex-not.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/regex-not) > Create a javascript regular expression for matching everything except for the given string. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save regex-not ``` ## Usage ```js var not = require('regex-not'); ``` The main export is a function that takes a string an options object. ```js not(string[, options]); ``` **Example** ```js var not = require('regex-not'); console.log(not('foo')); //=> /^(?:(?!^(?:foo)$).)+$/ ``` **Strict matching** By default, the returned regex is for strictly (not) matching the exact given pattern (in other words, "match this string if it does NOT _exactly equal_ `foo`"): ```js var re = not('foo'); console.log(re.test('foo')); //=> false console.log(re.test('bar')); //=> true console.log(re.test('foobar')); //=> true console.log(re.test('barfoo')); //=> true ``` ### .create Returns a string to allow you to create your own regex: ```js console.log(not.create('foo')); //=> '(?:(?!^(?:foo)$).)+' ``` ### Options **options.contains** You can relax strict matching by setting `options.contains` to true (in other words, "match this string if it does NOT _contain_ `foo`"): ```js var re = not('foo'); console.log(re.test('foo', {contains: true})); //=> false console.log(re.test('bar', {contains: true})); //=> true console.log(re.test('foobar', {contains: true})); //=> false console.log(re.test('barfoo', {contains: true})); //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [regex-cache](https://www.npmjs.com/package/regex-cache): Memoize the results of a call to the RegExp constructor, avoiding repetitious runtime compilation of… [more](https://github.com/jonschlinkert/regex-cache) | [homepage](https://github.com/jonschlinkert/regex-cache "Memoize the results of a call to the RegExp constructor, avoiding repetitious runtime compilation of the same string and options, resulting in surprising performance improvements.") * [to-regex](https://www.npmjs.com/package/to-regex): Generate a regex from a string or array of strings. | [homepage](https://github.com/jonschlinkert/to-regex "Generate a regex from a string or array of strings.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 9 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [EdwardBetts](https://github.com/EdwardBetts) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 19, 2018._ # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ # ssri [![npm version](https://img.shields.io/npm/v/ssri.svg)](https://npm.im/ssri) [![license](https://img.shields.io/npm/l/ssri.svg)](https://npm.im/ssri) [![Travis](https://img.shields.io/travis/zkat/ssri.svg)](https://travis-ci.org/zkat/ssri) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/ssri?svg=true)](https://ci.appveyor.com/project/zkat/ssri) [![Coverage Status](https://coveralls.io/repos/github/zkat/ssri/badge.svg?branch=latest)](https://coveralls.io/github/zkat/ssri?branch=latest) [`ssri`](https://github.com/zkat/ssri), short for Standard Subresource Integrity, is a Node.js utility for parsing, manipulating, serializing, generating, and verifying [Subresource Integrity](https://w3c.github.io/webappsec/specs/subresourceintegrity/) hashes. ## Install `$ npm install --save ssri` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * Parsing & Serializing * [`parse`](#parse) * [`stringify`](#stringify) * [`Integrity#concat`](#integrity-concat) * [`Integrity#toString`](#integrity-to-string) * [`Integrity#toJSON`](#integrity-to-json) * [`Integrity#match`](#integrity-match) * [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) * [`Integrity#hexDigest`](#integrity-hex-digest) * Integrity Generation * [`fromHex`](#from-hex) * [`fromData`](#from-data) * [`fromStream`](#from-stream) * [`create`](#create) * Integrity Verification * [`checkData`](#check-data) * [`checkStream`](#check-stream) * [`integrityStream`](#integrity-stream) ### Example ```javascript const ssri = require('ssri') const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' // Parsing and serializing const parsed = ssri.parse(integrity) ssri.stringify(parsed) // === integrity (works on non-Integrity objects) parsed.toString() // === integrity // Async stream functions ssri.checkStream(fs.createReadStream('./my-file'), integrity).then(...) ssri.fromStream(fs.createReadStream('./my-file')).then(sri => { sri.toString() === integrity }) fs.createReadStream('./my-file').pipe(ssri.createCheckerStream(sri)) // Sync data functions ssri.fromData(fs.readFileSync('./my-file')) // === parsed ssri.checkData(fs.readFileSync('./my-file'), integrity) // => 'sha512' ``` ### Features * Parses and stringifies SRI strings. * Generates SRI strings from raw data or Streams. * Strict standard compliance. * `?foo` metadata option support. * Multiple entries for the same algorithm. * Object-based integrity hash manipulation. * Small footprint: no dependencies, concise implementation. * Full test coverage. * Customizable algorithm picker. ### Contributing The ssri team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. ### API #### <a name="parse"></a> `> ssri.parse(sri, [opts]) -> Integrity` Parses `sri` into an `Integrity` data structure. `sri` can be an integrity string, an `Hash`-like with `digest` and `algorithm` fields and an optional `options` field, or an `Integrity`-like object. The resulting object will be an `Integrity` instance that has this shape: ```javascript { 'sha1': [{algorithm: 'sha1', digest: 'deadbeef', options: []}], 'sha512': [ {algorithm: 'sha512', digest: 'c0ffee', options: []}, {algorithm: 'sha512', digest: 'bad1dea', options: ['foo']} ], } ``` If `opts.single` is truthy, a single `Hash` object will be returned. That is, a single object that looks like `{algorithm, digest, options}`, as opposed to a larger object with multiple of these. If `opts.strict` is truthy, the resulting object will be filtered such that it strictly follows the Subresource Integrity spec, throwing away any entries with any invalid components. This also means a restricted set of algorithms will be used -- the spec limits them to `sha256`, `sha384`, and `sha512`. Strict mode is recommended if the integrity strings are intended for use in browsers, or in other situations where strict adherence to the spec is needed. ##### Example ```javascript ssri.parse('sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo') // -> Integrity object ``` #### <a name="stringify"></a> `> ssri.stringify(sri, [opts]) -> String` This function is identical to [`Integrity#toString()`](#integrity-to-string), except it can be used on _any_ object that [`parse`](#parse) can handle -- that is, a string, an `Hash`-like, or an `Integrity`-like. The `opts.sep` option defines the string to use when joining multiple entries together. To be spec-compliant, this _must_ be whitespace. The default is a single space (`' '`). If `opts.strict` is true, the integrity string will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript // Useful for cleaning up input SRI strings: ssri.stringify('\n\rsha512-foo\n\t\tsha384-bar') // -> 'sha512-foo sha384-bar' // Hash-like: only a single entry. ssri.stringify({ algorithm: 'sha512', digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==', options: ['foo'] }) // -> // 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' // Integrity-like: full multi-entry syntax. Similar to output of `ssri.parse` ssri.stringify({ 'sha512': [ { algorithm: 'sha512', digest:'9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==', options: ['foo'] } ] }) // -> // 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' ``` #### <a name="integrity-concat"></a> `> Integrity#concat(otherIntegrity, [opts]) -> Integrity` Concatenates an `Integrity` object with another IntegrityLike, or an integrity string. This is functionally equivalent to concatenating the string format of both integrity arguments, and calling [`ssri.parse`](#ssri-parse) on the new string. If `opts.strict` is true, the new `Integrity` will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript // This will combine the integrity checks for two different versions of // your index.js file so you can use a single integrity string and serve // either of these to clients, from a single `<script>` tag. const desktopIntegrity = ssri.fromData(fs.readFileSync('./index.desktop.js')) const mobileIntegrity = ssri.fromData(fs.readFileSync('./index.mobile.js')) // Note that browsers (and ssri) will succeed as long as ONE of the entries // for the *prioritized* algorithm succeeds. That is, in order for this fallback // to work, both desktop and mobile *must* use the same `algorithm` values. desktopIntegrity.concat(mobileIntegrity) ``` #### <a name="integrity-to-string"></a> `> Integrity#toString([opts]) -> String` Returns the string representation of an `Integrity` object. All hash entries will be concatenated in the string by `opts.sep`, which defaults to `' '`. If you want to serialize an object that didn't come from an `ssri` function, use [`ssri.stringify()`](#stringify). If `opts.strict` is true, the integrity string will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo' ssri.parse(integrity).toString() === integrity ``` #### <a name="integrity-to-json"></a> `> Integrity#toJSON() -> String` Returns the string representation of an `Integrity` object. All hash entries will be concatenated in the string by `' '`. This is a convenience method so you can pass an `Integrity` object directly to `JSON.stringify`. For more info check out [toJSON() behavior on mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON%28%29_behavior). ##### Example ```javascript const integrity = '"sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==?foo"' JSON.stringify(ssri.parse(integrity)) === integrity ``` #### <a name="integrity-match"></a> `> Integrity#match(sri, [opts]) -> Hash | false` Returns the matching (truthy) hash if `Integrity` matches the argument passed as `sri`, which can be anything that [`parse`](#parse) will accept. `opts` will be passed through to `parse` and [`pickAlgorithm()`](#integrity-pick-algorithm). ##### Example ```javascript const integrity = 'sha512-9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==' ssri.parse(integrity).match(integrity) // Hash { // digest: '9KhgCRIx/AmzC8xqYJTZRrnO8OW2Pxyl2DIMZSBOr0oDvtEFyht3xpp71j/r/pAe1DM+JI/A+line3jUBgzQ7A==' // algorithm: 'sha512' // } ssri.parse(integrity).match('sha1-deadbeef') // false ``` #### <a name="integrity-pick-algorithm"></a> `> Integrity#pickAlgorithm([opts]) -> String` Returns the "best" algorithm from those available in the integrity object. If `opts.pickAlgorithm` is provided, it will be passed two algorithms as arguments. ssri will prioritize whichever of the two algorithms is returned by this function. Note that the function may be called multiple times, and it **must** return one of the two algorithms provided. By default, ssri will make a best-effort to pick the strongest/most reliable of the given algorithms. It may intentionally deprioritize algorithms with known vulnerabilities. ##### Example ```javascript ssri.parse('sha1-WEakDigEST sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1').pickAlgorithm() // sha512 ``` #### <a name="integrity-hex-digest"></a> `> Integrity#hexDigest() -> String` `Integrity` is assumed to be either a single-hash `Integrity` instance, or a `Hash` instance. Returns its `digest`, converted to a hex representation of the base64 data. ##### Example ```javascript ssri.parse('sha1-deadbeef').hexDigest() // '75e69d6de79f' ``` #### <a name="from-hex"></a> `> ssri.fromHex(hexDigest, algorithm, [opts]) -> Integrity` Creates an `Integrity` object with a single entry, based on a hex-formatted hash. This is a utility function to help convert existing shasums to the Integrity format, and is roughly equivalent to something like: ```javascript algorithm + '-' + Buffer.from(hexDigest, 'hex').toString('base64') ``` `opts.options` may optionally be passed in: it must be an array of option strings that will be added to all generated integrity hashes generated by `fromData`. This is a loosely-specified feature of SRIs, and currently has no specified semantics besides being `?`-separated. Use at your own risk, and probably avoid if your integrity strings are meant to be used with browsers. If `opts.strict` is true, the integrity object will be created using strict parsing rules. See [`ssri.parse`](#parse). If `opts.single` is true, a single `Hash` object will be returned. ##### Example ```javascript ssri.fromHex('75e69d6de79f', 'sha1').toString() // 'sha1-deadbeef' ``` #### <a name="from-data"></a> `> ssri.fromData(data, [opts]) -> Integrity` Creates an `Integrity` object from either string or `Buffer` data, calculating all the requested hashes and adding any specified options to the object. `opts.algorithms` determines which algorithms to generate hashes for. All results will be included in a single `Integrity` object. The default value for `opts.algorithms` is `['sha512']`. All algorithm strings must be hashes listed in `crypto.getHashes()` for the host Node.js platform. `opts.options` may optionally be passed in: it must be an array of option strings that will be added to all generated integrity hashes generated by `fromData`. This is a loosely-specified feature of SRIs, and currently has no specified semantics besides being `?`-separated. Use at your own risk, and probably avoid if your integrity strings are meant to be used with browsers. If `opts.strict` is true, the integrity object will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript const integrityObj = ssri.fromData('foobarbaz', { algorithms: ['sha256', 'sha384', 'sha512'] }) integrity.toString('\n') // -> // sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0= // sha384-irnCxQ0CfQhYGlVAUdwTPC9bF3+YWLxlaDGM4xbYminxpbXEq+D+2GCEBTxcjES9 // sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1+9vBnypkYWg== ``` #### <a name="from-stream"></a> `> ssri.fromStream(stream, [opts]) -> Promise<Integrity>` Returns a Promise of an Integrity object calculated by reading data from a given `stream`. It accepts both `opts.algorithms` and `opts.options`, which are documented as part of [`ssri.fromData`](#from-data). Additionally, `opts.Promise` may be passed in to inject a Promise library of choice. By default, ssri will use Node's built-in Promises. If `opts.strict` is true, the integrity object will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript ssri.fromStream(fs.createReadStream('index.js'), { algorithms: ['sha1', 'sha512'] }).then(integrity => { return ssri.checkStream(fs.createReadStream('index.js'), integrity) }) // succeeds ``` #### <a name="create"></a> `> ssri.create([opts]) -> <Hash>` Returns a Hash object with `update(<Buffer or string>[,enc])` and `digest()` methods. The Hash object provides the same methods as [crypto class Hash](https://nodejs.org/dist/latest-v6.x/docs/api/crypto.html#crypto_class_hash). `digest()` accepts no arguments and returns an Integrity object calculated by reading data from calls to update. It accepts both `opts.algorithms` and `opts.options`, which are documented as part of [`ssri.fromData`](#from-data). If `opts.strict` is true, the integrity object will be created using strict parsing rules. See [`ssri.parse`](#parse). ##### Example ```javascript const integrity = ssri.create().update('foobarbaz').digest() integrity.toString() // -> // sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1+9vBnypkYWg== ``` #### <a name="check-data"></a> `> ssri.checkData(data, sri, [opts]) -> Hash|false` Verifies `data` integrity against an `sri` argument. `data` may be either a `String` or a `Buffer`, and `sri` can be any subresource integrity representation that [`ssri.parse`](#parse) can handle. If verification succeeds, `checkData` will return the name of the algorithm that was used for verification (a truthy value). Otherwise, it will return `false`. If `opts.pickAlgorithm` is provided, it will be used by [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) when deciding which of the available digests to match against. If `opts.error` is true, and verification fails, `checkData` will throw either an `EBADSIZE` or an `EINTEGRITY` error, instead of just returning false. ##### Example ```javascript const data = fs.readFileSync('index.js') ssri.checkData(data, ssri.fromData(data)) // -> 'sha512' ssri.checkData(data, 'sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0') ssri.checkData(data, 'sha1-BaDDigEST') // -> false ssri.checkData(data, 'sha1-BaDDigEST', {error: true}) // -> Error! EINTEGRITY ``` #### <a name="check-stream"></a> `> ssri.checkStream(stream, sri, [opts]) -> Promise<Hash>` Verifies the contents of `stream` against an `sri` argument. `stream` will be consumed in its entirety by this process. `sri` can be any subresource integrity representation that [`ssri.parse`](#parse) can handle. `checkStream` will return a Promise that either resolves to the `Hash` that succeeded verification, or, if the verification fails or an error happens with `stream`, the Promise will be rejected. If the Promise is rejected because verification failed, the returned error will have `err.code` as `EINTEGRITY`. If `opts.size` is given, it will be matched against the stream size. An error with `err.code` `EBADSIZE` will be returned by a rejection if the expected size and actual size fail to match. If `opts.pickAlgorithm` is provided, it will be used by [`Integrity#pickAlgorithm`](#integrity-pick-algorithm) when deciding which of the available digests to match against. ##### Example ```javascript const integrity = ssri.fromData(fs.readFileSync('index.js')) ssri.checkStream( fs.createReadStream('index.js'), integrity ) // -> // Promise<{ // algorithm: 'sha512', // digest: 'sha512-yzd8ELD1piyANiWnmdnpCL5F52f10UfUdEkHywVZeqTt0ymgrxR63Qz0GB7TKPoeeZQmWCaz7T1' // }> ssri.checkStream( fs.createReadStream('index.js'), 'sha256-l981iLWj8kurw4UbNy8Lpxqdzd7UOxS50Glhv8FwfZ0' ) // -> Promise<Hash> ssri.checkStream( fs.createReadStream('index.js'), 'sha1-BaDDigEST' ) // -> Promise<Error<{code: 'EINTEGRITY'}>> ``` #### <a name="integrity-stream"></a> `> integrityStream([opts]) -> IntegrityStream` Returns a `Transform` stream that data can be piped through in order to generate and optionally check data integrity for piped data. When the stream completes successfully, it emits `size` and `integrity` events, containing the total number of bytes processed and a calculated `Integrity` instance based on stream data, respectively. If `opts.algorithms` is passed in, the listed algorithms will be calculated when generating the final `Integrity` instance. The default is `['sha512']`. If `opts.single` is passed in, a single `Hash` instance will be returned. If `opts.integrity` is passed in, it should be an `integrity` value understood by [`parse`](#parse) that the stream will check the data against. If verification succeeds, the integrity stream will emit a `verified` event whose value is a single `Hash` object that is the one that succeeded verification. If verification fails, the stream will error with an `EINTEGRITY` error code. If `opts.size` is given, it will be matched against the stream size. An error with `err.code` `EBADSIZE` will be emitted by the stream if the expected size and actual size fail to match. If `opts.pickAlgorithm` is provided, it will be passed two algorithms as arguments. ssri will prioritize whichever of the two algorithms is returned by this function. Note that the function may be called multiple times, and it **must** return one of the two algorithms provided. By default, ssri will make a best-effort to pick the strongest/most reliable of the given algorithms. It may intentionally deprioritize algorithms with known vulnerabilities. ##### Example ```javascript const integrity = ssri.fromData(fs.readFileSync('index.js')) fs.createReadStream('index.js') .pipe(ssri.integrityStream({integrity})) ``` Welcome to the LibSass documentation! ## First Off LibSass is just a library. To run the code locally (i.e. to compile your stylesheets), you need an implementer. SassC (get it?) is an implementer written in C. There are a number of other implementations of LibSass - for example Node. We encourage you to write your own port - the whole point of LibSass is that we want to bring Sass to many other languages, not just Ruby! We're working hard on moving to full parity with Ruby Sass... learn more at the [The-LibSass-Compatibility-Plan](compatibility-plan.md)! ### Implementing LibSass If you're interested in implementing LibSass in your own project see the [API Documentation](api-doc.md) which now includes implementing your own [Sass functions](api-function.md). You may wish to [look at other implementations](implementations.md) for your language of choice. Or make your own! ### Contributing to LibSass | Issue Tracker | Issue Triage | Community Guidelines | |-------------------|----------------------------------|-----------------------------| | We're always needing help, so check out our issue tracker, help some people out, and read our article on [Contributing](contributing.md)! It's got all the details on what to do! | To help understand the process of triaging bugs, have a look at our [Issue-Triage](triage.md) document. | Oh, and don't forget we always follow [[Sass Community Guidelines|http://sass-lang.com/community-guidelines]]. Be nice and everyone else will be nice too! | Please refer to the steps on [Building LibSass](build.md) # fast-levenshtein - Levenshtein algorithm in Javascript [![Build Status](https://secure.travis-ci.org/hiddentao/fast-levenshtein.png)](http://travis-ci.org/hiddentao/fast-levenshtein) [![NPM module](https://badge.fury.io/js/fast-levenshtein.png)](https://badge.fury.io/js/fast-levenshtein) [![NPM downloads](https://img.shields.io/npm/dm/fast-levenshtein.svg?maxAge=2592000)](https://www.npmjs.com/package/fast-levenshtein) [![Follow on Twitter](https://img.shields.io/twitter/url/http/shields.io.svg?style=social&label=Follow&maxAge=2592000)](https://twitter.com/hiddentao) An efficient Javascript implementation of the [Levenshtein algorithm](http://en.wikipedia.org/wiki/Levenshtein_distance) with locale-specific collator support. ## Features * Works in node.js and in the browser. * Better performance than other implementations by not needing to store the whole matrix ([more info](http://www.codeproject.com/Articles/13525/Fast-memory-efficient-Levenshtein-algorithm)). * Locale-sensitive string comparisions if needed. * Comprehensive test suite and performance benchmark. * Small: <1 KB minified and gzipped ## Installation ### node.js Install using [npm](http://npmjs.org/): ```bash $ npm install fast-levenshtein ``` ### Browser Using bower: ```bash $ bower install fast-levenshtein ``` If you are not using any module loader system then the API will then be accessible via the `window.Levenshtein` object. ## Examples **Default usage** ```javascript var levenshtein = require('fast-levenshtein'); var distance = levenshtein.get('back', 'book'); // 2 var distance = levenshtein.get('我愛你', '我叫你'); // 1 ``` **Locale-sensitive string comparisons** It supports using [Intl.Collator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator) for locale-sensitive string comparisons: ```javascript var levenshtein = require('fast-levenshtein'); levenshtein.get('mikailovitch', 'Mikhaïlovitch', { useCollator: true}); // 1 ``` ## Building and Testing To build the code and run the tests: ```bash $ npm install -g grunt-cli $ npm install $ npm run build ``` ## Performance _Thanks to [Titus Wormer](https://github.com/wooorm) for [encouraging me](https://github.com/hiddentao/fast-levenshtein/issues/1) to do this._ Benchmarked against other node.js levenshtein distance modules (on Macbook Air 2012, Core i7, 8GB RAM): ```bash Running suite Implementation comparison [benchmark/speed.js]... >> levenshtein-edit-distance x 234 ops/sec ±3.02% (73 runs sampled) >> levenshtein-component x 422 ops/sec ±4.38% (83 runs sampled) >> levenshtein-deltas x 283 ops/sec ±3.83% (78 runs sampled) >> natural x 255 ops/sec ±0.76% (88 runs sampled) >> levenshtein x 180 ops/sec ±3.55% (86 runs sampled) >> fast-levenshtein x 1,792 ops/sec ±2.72% (95 runs sampled) Benchmark done. Fastest test is fast-levenshtein at 4.2x faster than levenshtein-component ``` You can run this benchmark yourself by doing: ```bash $ npm install $ npm run build $ npm run benchmark ``` ## Contributing If you wish to submit a pull request please update and/or create new tests for any changes you make and ensure the grunt build passes. See [CONTRIBUTING.md](https://github.com/hiddentao/fast-levenshtein/blob/master/CONTRIBUTING.md) for details. ## License MIT - see [LICENSE.md](https://github.com/hiddentao/fast-levenshtein/blob/master/LICENSE.md) These files are compiled dot templates from dot folder. Do NOT edit them directly, edit the templates and run `npm run build` from main ajv folder. # fragment-cache [![NPM version](https://img.shields.io/npm/v/fragment-cache.svg?style=flat)](https://www.npmjs.com/package/fragment-cache) [![NPM downloads](https://img.shields.io/npm/dm/fragment-cache.svg?style=flat)](https://npmjs.org/package/fragment-cache) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/fragment-cache.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/fragment-cache) > A cache for managing namespaced sub-caches ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save fragment-cache ``` ## Usage ```js var Fragment = require('fragment-cache'); var fragment = new Fragment(); ``` ## API ### [FragmentCache](index.js#L24) Create a new `FragmentCache` with an optional object to use for `caches`. **Example** ```js var fragment = new FragmentCache(); ``` **Params** * `cacheName` **{String}** * `returns` **{Object}**: Returns the [map-cache](https://github.com/jonschlinkert/map-cache) instance. ### [.cache](index.js#L49) Get cache `name` from the `fragment.caches` object. Creates a new `MapCache` if it doesn't already exist. **Example** ```js var cache = fragment.cache('files'); console.log(fragment.caches.hasOwnProperty('files')); //=> true ``` **Params** * `cacheName` **{String}** * `returns` **{Object}**: Returns the [map-cache](https://github.com/jonschlinkert/map-cache) instance. ### [.set](index.js#L67) Set a value for property `key` on cache `name` **Example** ```js fragment.set('files', 'somefile.js', new File({path: 'somefile.js'})); ``` **Params** * `name` **{String}** * `key` **{String}**: Property name to set * `val` **{any}**: The value of `key` * `returns` **{Object}**: The cache instance for chaining ### [.has](index.js#L93) Returns true if a non-undefined value is set for `key` on fragment cache `name`. **Example** ```js var cache = fragment.cache('files'); cache.set('somefile.js'); console.log(cache.has('somefile.js')); //=> true console.log(cache.has('some-other-file.js')); //=> false ``` **Params** * `name` **{String}**: Cache name * `key` **{String}**: Optionally specify a property to check for on cache `name` * `returns` **{Boolean}** ### [.get](index.js#L115) Get `name`, or if specified, the value of `key`. Invokes the [cache](#cache) method, so that cache `name` will be created it doesn't already exist. If `key` is not passed, the entire cache (`name`) is returned. **Example** ```js var Vinyl = require('vinyl'); var cache = fragment.cache('files'); cache.set('somefile.js', new Vinyl({path: 'somefile.js'})); console.log(cache.get('somefile.js')); //=> <File "somefile.js"> ``` **Params** * `name` **{String}** * `returns` **{Object}**: Returns cache `name`, or the value of `key` if specified ## About ### Related projects * [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/node-base/base) | [homepage](https://github.com/node-base/base "base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [map-cache](https://www.npmjs.com/package/map-cache): Basic cache object for storing key-value pairs. | [homepage](https://github.com/jonschlinkert/map-cache "Basic cache object for storing key-value pairs.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/fragment-cache/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.2.0, on October 17, 2016._ # Array Flatten [![NPM version][npm-image]][npm-url] [![NPM downloads][downloads-image]][downloads-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] > Flatten nested arrays. ## Installation ``` npm install array-flatten --save ``` ## Usage ```javascript var flatten = require('array-flatten') flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] flatten.depth([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) //=> [1, 2, 3, [4, [5], 6], 7, 8, 9] (function () { flatten.from(arguments) //=> [1, 2, 3] })(1, [2, 3]) ``` ### Methods * **flatten(array)** Flatten a nested array structure * **flatten.from(arrayish)** Flatten an array-like structure (E.g. arguments) * **flatten.depth(array, depth)** Flatten a nested array structure with a specific depth * **flatten.fromDepth(arrayish, depth)** Flatten an array-like structure with a specific depth ## License MIT [npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat [npm-url]: https://npmjs.org/package/array-flatten [downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat [downloads-url]: https://npmjs.org/package/array-flatten [travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat [travis-url]: https://travis-ci.org/blakeembrey/array-flatten [coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat [coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master # Extension pipelining `websocket-extensions` models the extension negotiation and processing pipeline of the WebSocket protocol. Between the driver parsing messages from the TCP stream and handing those messages off to the application, there may exist a stack of extensions that transform the message somehow. In the parlance of this framework, a *session* refers to a single instance of an extension, acting on a particular socket on either the server or the client side. A session may transform messages both incoming to the application and outgoing from the application, for example the `permessage-deflate` extension compresses outgoing messages and decompresses incoming messages. Message streams in either direction are independent; that is, incoming and outgoing messages cannot be assumed to 'pair up' as in a request-response protocol. Asynchronous processing of messages poses a number of problems that this pipeline construction is intended to solve. ## Overview Logically, we have the following: +-------------+ out +---+ +---+ +---+ +--------+ | |------>| |---->| |---->| |------>| | | Application | | A | | B | | C | | Driver | | |<------| |<----| |<----| |<------| | +-------------+ in +---+ +---+ +---+ +--------+ \ / +----------o----------+ | sessions For outgoing messages, the driver receives the result of C.outgoing(B.outgoing(A.outgoing(message))) or, [A, B, C].reduce(((m, ext) => ext.outgoing(m)), message) For incoming messages, the application receives the result of A.incoming(B.incoming(C.incoming(message))) or, [C, B, A].reduce(((m, ext) => ext.incoming(m)), message) A session is of the following type, to borrow notation from pseudo-Haskell: type Session = { incoming :: Message -> Message outgoing :: Message -> Message close :: () -> () } (That `() -> ()` syntax is intended to mean that `close()` is a nullary void method; I apologise to any Haskell readers for not using the right monad.) The `incoming()` and `outgoing()` methods perform message transformation in the respective directions; `close()` is called when a socket closes so the session can release any resources it's holding, for example a DEFLATE de/compression context. However because this is JavaScript, the `incoming()` and `outgoing()` methods may be asynchronous (indeed, `permessage-deflate` is based on `zlib`, whose API is stream-based). So their interface is strictly: type Session = { incoming :: Message -> Callback -> () outgoing :: Message -> Callback -> () close :: () -> () } type Callback = Either Error Message -> () This means a message *m2* can be pushed into a session while it's still processing the preceding message *m1*. The messages can be processed concurrently but they *must* be given to the next session in line (or to the application) in the same order they came in. Applications will expect to receive messages in the order they arrived over the wire, and sessions require this too. So ordering of messages must be preserved throughout the pipeline. Consider the following highly simplified extension that deflates messages on the wire. `message` is a value conforming the type: type Message = { rsv1 :: Boolean rsv2 :: Boolean rsv3 :: Boolean opcode :: Number data :: Buffer } Here's the extension: ```js var zlib = require('zlib'); var deflate = { outgoing: function(message, callback) { zlib.deflateRaw(message.data, function(error, result) { message.rsv1 = true; message.data = result; callback(error, message); }); }, incoming: function(message, callback) { // decompress inbound messages (elided) }, close: function() { // no state to clean up } }; ``` We can call it with a large message followed by a small one, and the small one will be returned first: ```js var crypto = require('crypto'), large = crypto.randomBytes(1 << 14), small = new Buffer('hi'); deflate.outgoing({data: large}, function() { console.log(1, 'large'); }); deflate.outgoing({data: small}, function() { console.log(2, 'small'); }); /* prints: 2 'small' 1 'large' */ ``` So a session that processes messages asynchronously may fail to preserve message ordering. Now, this extension is stateless, so it can process messages in any order and still produce the same output. But some extensions are stateful and require message order to be preserved. For example, when using `permessage-deflate` without `no_context_takeover` set, the session retains a DEFLATE de/compression context between messages, which accumulates state as it consumes data (later messages can refer to sections of previous ones to improve compression). Reordering parts of the DEFLATE stream will result in a failed decompression. Messages must be decompressed in the same order they were compressed by the peer in order for the DEFLATE protocol to work. Finally, there is the problem of closing a socket. When a WebSocket is closed by the application, or receives a closing request from the other peer, there may be messages outgoing from the application and incoming from the peer in the pipeline. If we close the socket and pipeline immediately, two problems arise: * We may send our own closing frame to the peer before all prior messages we sent have been written to the socket, and before we have finished processing all prior messages from the peer * The session may be instructed to close its resources (e.g. its de/compression context) while it's in the middle of processing a message, or before it has received messages that are upstream of it in the pipeline Essentially, we must defer closing the sessions and sending a closing frame until after all prior messages have exited the pipeline. ## Design goals * Message order must be preserved between the protocol driver, the extension sessions, and the application * Messages should be handed off to sessions and endpoints as soon as possible, to maximise throughput of stateless sessions * The closing procedure should block any further messages from entering the pipeline, and should allow all existing messages to drain * Sessions should be closed as soon as possible to prevent them holding memory and other resources when they have no more messages to handle * The closing API should allow the caller to detect when the pipeline is empty and it is safe to continue the WebSocket closing procedure * Individual extensions should remain as simple as possible to facilitate modularity and independent authorship The final point about modularity is an important one: this framework is designed to facilitate extensions existing as plugins, by decoupling the protocol driver, extensions, and application. In an ideal world, plugins should only need to contain code for their specific functionality, and not solve these problems that apply to all sessions. Also, solving some of these problems requires consideration of all active sessions collectively, which an individual session is incapable of doing. For example, it is entirely possible to take the simple `deflate` extension above and wrap its `incoming()` and `outgoing()` methods in two `Transform` streams, producing this type: type Session = { incoming :: TransformStream outtoing :: TransformStream close :: () -> () } The `Transform` class makes it easy to wrap an async function such that message order is preserved: ```js var stream = require('stream'), session = new stream.Transform({objectMode: true}); session._transform = function(message, _, callback) { var self = this; deflate.outgoing(message, function(error, result) { self.push(result); callback(); }); }; ``` However, this has a negative impact on throughput: it works by deferring `callback()` until the async function has 'returned', which blocks `Transform` from passing further input into the `_transform()` method until the current message is dealt with completely. This would prevent sessions from processing messages concurrently, and would unnecessarily reduce the throughput of stateless extensions. So, input should be handed off to sessions as soon as possible, and all we need is a mechanism to reorder the output so that message order is preserved for the next session in line. ## Solution We now describe the model implemented here and how it meets the above design goals. The above diagram where a stack of extensions sit between the driver and application describes the data flow, but not the object graph. That looks like this: +--------+ | Driver | +---o----+ | V +------------+ +----------+ | Extensions o----->| Pipeline | +------------+ +-----o----+ | +---------------+---------------+ | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ A driver using this framework holds an instance of the `Extensions` class, which it uses to register extension plugins, negotiate headers and transform messages. The `Extensions` instance itself holds a `Pipeline`, which contains an array of `Cell` objects, each of which wraps one of the sessions. ### Message processing Both the `Pipeline` and `Cell` classes have `incoming()` and `outgoing()` methods; the `Pipeline` interface pushes messages into the pipe, delegates the message to each `Cell` in turn, then returns it back to the driver. Outgoing messages pass through `A` then `B` then `C`, and incoming messages in the reverse order. Internally, a `Cell` contains two `Functor` objects. A `Functor` wraps an async function and makes sure its output messages maintain the order of its input messages. This name is due to [@fronx](https://github.com/fronx), on the basis that, by preserving message order, the abstraction preserves the *mapping* between input and output messages. To use our simple `deflate` extension from above: ```js var functor = new Functor(deflate, 'outgoing'); functor.call({data: large}, function() { console.log(1, 'large'); }); functor.call({data: small}, function() { console.log(2, 'small'); }); /* -> 1 'large' 2 'small' */ ``` A `Cell` contains two of these, one for each direction: +-----------------------+ +---->| Functor [A, incoming] | +----------+ | +-----------------------+ | Cell [A] o------+ +----------+ | +-----------------------+ +---->| Functor [A, outgoing] | +-----------------------+ This satisfies the message transformation requirements: the `Pipeline` simply loops over the cells in the appropriate direction to transform each message. Because each `Cell` will preserve message order, we can pass a message to the next `Cell` in line as soon as the current `Cell` returns it. This gives each `Cell` all the messages in order while maximising throughput. ### Session closing We want to close each session as soon as possible, after all existing messages have drained. To do this, each `Cell` begins with a pending message counter in each direction, labelled `in` and `out` below. +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 0 out: 0 out: 0 When a message *m1* enters the pipeline, say in the `outgoing` direction, we increment the `pending.out` counter on all cells immediately. +----------+ m1 => | Pipeline | +-----o----+ | +---------------+---------------+ | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 1 out: 1 out: 1 *m1* is handed off to `A`, meanwhile a second message `m2` arrives in the same direction. All `pending.out` counters are again incremented. +----------+ m2 => | Pipeline | +-----o----+ | +---------------+---------------+ m1 | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 2 out: 2 out: 2 When the first cell's `A.outgoing` functor finishes processing *m1*, the first `pending.out` counter is decremented and *m1* is handed off to cell `B`. +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ m2 | m1 | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 1 out: 2 out: 2 As `B` finishes with *m1*, and as `A` finishes with *m2*, the `pending.out` counters continue to decrement. +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ | m2 | m1 | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 0 out: 1 out: 2 Say `C` is a little slow, and begins processing *m2* while still processing *m1*. That's fine, the `Functor` mechanism will keep *m1* ahead of *m2* in the output. +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ | | m2 | m1 +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 0 out: 0 out: 2 Once all messages are dealt with, the counters return to `0`. +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 0 out: 0 out: 0 The same process applies in the `incoming` direction, the only difference being that messages are passed to `C` first. This makes closing the sessions quite simple. When the driver wants to close the socket, it calls `Pipeline.close()`. This *immediately* calls `close()` on all the cells. If a cell has `in == out == 0`, then it immediately calls `session.close()`. Otherwise, it stores the closing call and defers it until `in` and `out` have both ticked down to zero. The pipeline will not accept new messages after `close()` has been called, so we know the pending counts will not increase after this point. This means each session is closed as soon as possible: `A` can close while the slow `C` session is still working, because it knows there are no more messages on the way. Similarly, `C` will defer closing if `close()` is called while *m1* is still in `B`, and *m2* in `A`, because its pending count means it knows it has work yet to do, even if it's not received those messages yet. This concern cannot be addressed by extensions acting only on their own local state, unless we pollute individual extensions by making them all implement this same mechanism. The actual closing API at each level is slightly different: type Session = { close :: () -> () } type Cell = { close :: () -> Promise () } type Pipeline = { close :: Callback -> () } This might appear inconsistent so it's worth explaining. Remember that a `Pipeline` holds a list of `Cell` objects, each wrapping a `Session`. The driver talks (via the `Extensions` API) to the `Pipeline` interface, and it wants `Pipeline.close()` to do two things: close all the sessions, and tell me when it's safe to start the closing procedure (i.e. when all messages have drained from the pipe and been handed off to the application or socket). A callback API works well for that. At the other end of the stack, `Session.close()` is a nullary void method with no callback or promise API because we don't care what it does, and whatever it does do will not block the WebSocket protocol; we're not going to hold off processing messages while a session closes its de/compression context. We just tell it to close itself, and don't want to wait while it does that. In the middle, `Cell.close()` returns a promise rather than using a callback. This is for two reasons. First, `Cell.close()` might not do anything immediately, it might have to defer its effect while messages drain. So, if given a callback, it would have to store it in a queue for later execution. Callbacks work fine if your method does something and can then invoke the callback itself, but if you need to store callbacks somewhere so another method can execute them, a promise is a better fit. Second, it better serves the purposes of `Pipeline.close()`: it wants to call `close()` on each of a list of cells, and wait for all of them to finish. This is simple and idiomatic using promises: ```js var closed = cells.map((cell) => cell.close()); Promise.all(closed).then(callback); ``` (We don't actually use a full *Promises/A+* compatible promise here, we use a much simplified construction that acts as a callback aggregater and resolves synchronously and does not support chaining, but the principle is the same.) ### Error handling We've not mentioned error handling so far but it bears some explanation. The above counter system still applies, but behaves slightly differently in the presence of errors. Say we push three messages into the pipe in the outgoing direction: +----------+ m3, m2, m1 => | Pipeline | +-----o----+ | +---------------+---------------+ | | | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 3 out: 3 out: 3 They pass through the cells successfully up to this point: +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ m3 | m2 | m1 | +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 1 out: 2 out: 3 At this point, session `B` produces an error while processing *m2*, that is *m2* becomes *e2*. *m1* is still in the pipeline, and *m3* is queued behind *m2*. What ought to happen is that *m1* is handed off to the socket, then *m2* is released to the driver, which will detect the error and begin closing the socket. No further processing should be done on *m3* and it should not be released to the driver after the error is emitted. To handle this, we allow errors to pass down the pipeline just like messages do, to maintain ordering. But, once a cell sees its session produce an error, or it receives an error from upstream, it should refuse to accept any further messages. Session `B` might have begun processing *m3* by the time it produces the error *e2*, but `C` will have been given *e2* before it receives *m3*, and can simply drop *m3*. Now, say *e2* reaches the slow session `C` while *m1* is still present, meanwhile *m3* has been dropped. `C` will never receive *m3* since it will have been dropped upstream. Under the present model, its `out` counter will be `3` but it is only going to emit two more values: *m1* and *e2*. In order for closing to work, we need to decrement `out` to reflect this. The situation should look like this: +----------+ | Pipeline | +-----o----+ | +---------------+---------------+ | | e2 | m1 +-----o----+ +-----o----+ +-----o----+ | Cell [A] | | Cell [B] | | Cell [C] | +----------+ +----------+ +----------+ in: 0 in: 0 in: 0 out: 0 out: 0 out: 2 When a cell sees its session emit an error, or when it receives an error from upstream, it sets its pending count in the appropriate direction to equal the number of messages it is *currently* processing. It will not accept any messages after it sees the error, so this will allow the counter to reach zero. Note that while *e2* is in the pipeline, `Pipeline` should drop any further messages in the outgoing direction, but should continue to accept incoming messages. Until *e2* makes it out of the pipe to the driver, behind previous successful messages, the driver does not know an error has happened, and a message may arrive over the socket and make it all the way through the incoming pipe in the meantime. We only halt processing in the affected direction to avoid doing unnecessary work since messages arriving after an error should not be processed. Some unnecessary work may happen, for example any messages already in the pipeline following *m2* will be processed by `A`, since it's upstream of the error. Those messages will be dropped by `B`. ## Alternative ideas I am considering implementing `Functor` as an object-mode transform stream rather than what is essentially an async function. Being object-mode, a stream would preserve message boundaries and would also possibly help address back-pressure. I'm not sure whether this would require external API changes so that such streams could be connected to the downstream driver's streams. ## Acknowledgements Credit is due to [@mnowster](https://github.com/mnowster) for helping with the design and to [@fronx](https://github.com/fronx) for helping name things. # hosted-git-info This will let you identify and transform various git hosts URLs between protocols. It also can tell you what the URL is for the raw path for particular file for direct access without git. ## Example ```javascript var hostedGitInfo = require("hosted-git-info") var info = hostedGitInfo.fromUrl("[email protected]:npm/hosted-git-info.git", opts) /* info looks like: { type: "github", domain: "github.com", user: "npm", project: "hosted-git-info" } */ ``` If the URL can't be matched with a git host, `null` will be returned. We can match git, ssh and https urls. Additionally, we can match ssh connect strings (`[email protected]:npm/hosted-git-info`) and shortcuts (eg, `github:npm/hosted-git-info`). Github specifically, is detected in the case of a third, unprefixed, form: `npm/hosted-git-info`. If it does match, the returned object has properties of: * info.type -- The short name of the service * info.domain -- The domain for git protocol use * info.user -- The name of the user/org on the git host * info.project -- The name of the project on the git host ## Version Contract The major version will be bumped any time… * The constructor stops accepting URLs that it previously accepted. * A method is removed. * A method can no longer accept the number and type of arguments it previously accepted. * A method can return a different type than it currently returns. Implications: * I do not consider the specific format of the urls returned from, say `.https()` to be a part of the contract. The contract is that it will return a string that can be used to fetch the repo via HTTPS. But what that string looks like, specifically, can change. * Dropping support for a hosted git provider would constitute a breaking change. ## Usage ### var info = hostedGitInfo.fromUrl(gitSpecifier[, options]) * *gitSpecifer* is a URL of a git repository or a SCP-style specifier of one. * *options* is an optional object. It can have the following properties: * *noCommittish* — If true then committishes won't be included in generated URLs. * *noGitPlus* — If true then `git+` won't be prefixed on URLs. ## Methods All of the methods take the same options as the `fromUrl` factory. Options provided to a method override those provided to the constructor. * info.file(path, opts) Given the path of a file relative to the repository, returns a URL for directly fetching it from the githost. If no committish was set then `master` will be used as the default. For example `hostedGitInfo.fromUrl("[email protected]:npm/hosted-git-info.git#v1.0.0").file("package.json")` would return `https://raw.githubusercontent.com/npm/hosted-git-info/v1.0.0/package.json` * info.shortcut(opts) eg, `github:npm/hosted-git-info` * info.browse(path, fragment, opts) eg, `https://github.com/npm/hosted-git-info/tree/v1.2.0`, `https://github.com/npm/hosted-git-info/tree/v1.2.0/package.json`, `https://github.com/npm/hosted-git-info/tree/v1.2.0/REAMDE.md#supported-hosts` * info.bugs(opts) eg, `https://github.com/npm/hosted-git-info/issues` * info.docs(opts) eg, `https://github.com/npm/hosted-git-info/tree/v1.2.0#readme` * info.https(opts) eg, `git+https://github.com/npm/hosted-git-info.git` * info.sshurl(opts) eg, `git+ssh://[email protected]/npm/hosted-git-info.git` * info.ssh(opts) eg, `[email protected]:npm/hosted-git-info.git` * info.path(opts) eg, `npm/hosted-git-info` * info.tarball(opts) eg, `https://github.com/npm/hosted-git-info/archive/v1.2.0.tar.gz` * info.getDefaultRepresentation() Returns the default output type. The default output type is based on the string you passed in to be parsed * info.toString(opts) Uses the getDefaultRepresentation to call one of the other methods to get a URL for this resource. As such `hostedGitInfo.fromUrl(url).toString()` will give you a normalized version of the URL that still uses the same protocol. Shortcuts will still be returned as shortcuts, but the special case github form of `org/project` will be normalized to `github:org/project`. SSH connect strings will be normalized into `git+ssh` URLs. ## Supported hosts Currently this supports Github, Bitbucket and Gitlab. Pull requests for additional hosts welcome. # Browserslist [![Cult Of Martians][cult-img]][cult] <img width="120" height="120" alt="Browserslist logo by Anton Lovchikov" src="https://browserslist.github.io/browserslist/logo.svg" align="right"> The config to share target browsers and Node.js versions between different front-end tools. It is used in: * [Autoprefixer] * [Babel] * [postcss-preset-env] * [eslint-plugin-compat] * [stylelint-no-unsupported-browser-features] * [postcss-normalize] * [obsolete-webpack-plugin] [Browserslist Example] shows how every tool uses Browserslist. All tools will find target browsers automatically, when you add the following to `package.json`: ```json { "browserslist": [ "last 1 version", "> 1%", "maintained node versions", "not dead" ] } ``` Or in `.browserslistrc` config: ```yaml # Browsers that we support last 1 version > 1% maintained node versions not dead ``` Developers set versions list in queries like `last 2 version` to be free from updating versions manually. Browserslist will use [Can I Use] data for this queries. Browserslist will take queries from tool option, `browserslist` config, `.browserslistrc` config, `browserslist` section in `package.json` or environment variables. You can test Browserslist queries in [online demo]. [cult-img]: https://cultofmartians.com/assets/badges/badge.svg [cult]: https://cultofmartians.com/done.html <a href="https://evilmartians.com/?utm_source=browserslist"> <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg" alt="Sponsored by Evil Martians" width="236" height="54"> </a> [stylelint-no-unsupported-browser-features]: https://github.com/ismay/stylelint-no-unsupported-browser-features [eslint-plugin-compat]: https://github.com/amilajack/eslint-plugin-compat [Browserslist Example]: https://github.com/browserslist/browserslist-example [postcss-preset-env]: https://github.com/jonathantneal/postcss-preset-env [postcss-normalize]: https://github.com/jonathantneal/postcss-normalize [Autoprefixer]: https://github.com/postcss/autoprefixer [online demo]: https://browserl.ist/ [Can I Use]: https://caniuse.com/ [Babel]: https://github.com/babel/babel/tree/master/packages/babel-preset-env [obsolete-webpack-plugin]: https://github.com/ElemeFE/obsolete-webpack-plugin ## Tools * [`browserslist-ga`] downloads your website browsers statistics to use it in `> 0.5% in my stats` query. * [`browserslist-useragent`] checks browser by user agent string to match Browserslist target browsers query. * [`browserslist-useragent-ruby`] is a Ruby library to checks browser by user agent string to match Browserslist. * [`browserslist-useragent-regexp`] compiles Browserslist query to a RegExp to test browser useragent. * [`browserslist-browserstack`] runs BrowserStack tests for all browsers in Browserslist config. * [`caniuse-api`] returns browsers which support some specific feature. * Run `npx browserslist` in your project directory to see project’s target browsers. This CLI tool is built-in and available in any project with Autoprefixer. [`browserslist-useragent-ruby`]: https://github.com/browserslist/browserslist-useragent-ruby [`browserslist-useragent`]: https://github.com/pastelsky/browserslist-useragent [`browserslist-useragent-regexp`]: https://github.com/browserslist/browserslist-useragent-regexp [`browserslist-ga`]: https://github.com/browserslist/browserslist-ga [`caniuse-api`]: https://github.com/Nyalab/caniuse-api [`browserslist-browserstack`]: https://github.com/xeroxinteractive/browserslist-browserstack ## Queries Browserslist will use browsers and Node.js versions query from one of this sources: 1. `browserslist` key in `package.json` file in current or parent directories. **We recommend this way.** 2. Tool options. For example `browsers` option in Autoprefixer. 3. `BROWSERSLIST` environment variable. 4. `browserslist` config file in current or parent directories. 5. `.browserslistrc` config file in current or parent directories. 6. If the above methods did not produce a valid result Browserslist will use defaults: `> 0.5%, last 2 versions, Firefox ESR, not dead`. ### Query Composition An `or` combiner can use the keyword `or` as well as `,`. `last 1 version or > 1%` is equal to `last 1 version, > 1%`. `and` query combinations are also supported to perform an intersection of the previous query: `last 1 version and > 1%`. There is 3 different ways to combine queries as depicted below. First you start with a single query and then we combine the queries to get our final list. Obviously you can *not* start with a `not` combiner, since the is no left-hand side query to combine it with. | Query combiner type | Illustration | Example | | ------------------- | :----------: | ------- | |`or`/ `,` combiner <br> (union) | ![Union of queries](img/union.svg) | `'> .5% or last 2 versions'` <br> `'> .5%, last 2 versions'` | | `and` combiner <br> (intersection) | ![intersection of queries](img/intersection.svg) | `'> .5% and last 2 versions'` | | `not` combiner <br> (relative complement) | ![Relative complement of queries](img/complement.svg) | `'> .5% and not last 2 versions'` <br> `'> .5% or not last 2 versions'` <br> `'> .5%, not last 2 versions'` | _A quick way to test your query is to do `npx browserslist '> 0.5%, not IE 11'` in your terminal._ ### Best Practices * Select browsers directly (`last 2 Chrome versions`) only if you are making a web app for a kiosk with one browser. There are a lot of browsers on the market. If you are making general web app you should respect browsers diversity. * If you want to change the default set of browsers we recommend to combine `last 1 version`, `not dead` with `> 0.2%` (or `> 1% in US`, `> 1% in my stats`). `last n versions` adds too many dead browsers and does not add popular old versions. Choosing a percentage above `0.2%` will in the long run make popular browsers even more popular. We might run into a monopoly and stagnation situation, as we had with Internet Explorer 6. Please use this setting with caution. * Don’t remove browsers just because you don’t know them. Opera Mini has 100 million users in Africa and it is more popular in the global market than Microsoft Edge. Chinese QQ Browsers has more market share than Firefox and desktop Safari altogether. ### Full List You can specify the browser and Node.js versions by queries (case insensitive): * `> 5%`: browsers versions selected by global usage statistics. `>=`, `<` and `<=` work too. * `> 5% in US`: uses USA usage statistics. It accepts [two-letter country code]. * `> 5% in alt-AS`: uses Asia region usage statistics. List of all region codes can be found at [`caniuse-lite/data/regions`]. * `> 5% in my stats`: uses [custom usage data]. * `cover 99.5%`: most popular browsers that provide coverage. * `cover 99.5% in US`: same as above, with [two-letter country code]. * `cover 99.5% in my stats`: uses [custom usage data]. * `maintained node versions`: all Node.js versions, which are [still maintained] by Node.js Foundation. * `node 10` and `node 10.4`: selects latest Node.js `10.x.x` or `10.4.x` release. * `current node`: Node.js version used by Browserslist right now. * `extends browserslist-config-mycompany`: take queries from `browserslist-config-mycompany` npm package. * `ie 6-8`: selects an inclusive range of versions. * `Firefox > 20`: versions of Firefox newer than 20. `>=`, `<` and `<=` work too. It also works with Node.js. * `iOS 7`: the iOS browser version 7 directly. * `Firefox ESR`: the latest [Firefox ESR] version. * `unreleased versions` or `unreleased Chrome versions`: alpha and beta versions. * `last 2 major versions` or `last 2 iOS major versions`: all minor/patch releases of last 2 major versions. * `since 2015` or `last 2 years`: all versions released since year 2015 (also `since 2015-03` and `since 2015-03-10`). * `dead`: browsers from `last 2 version` query, but with less than 0.5% in global usage statistics and without official support or updates for 24 months. Right now it is `IE 10`, `IE_Mob 10`, `BlackBerry 10`, `BlackBerry 7`, and `OperaMobile 12.1`. * `last 2 versions`: the last 2 versions for *each* browser. * `last 2 Chrome versions`: the last 2 versions of Chrome browser. * `defaults`: Browserslist’s default browsers (`> 0.5%, last 2 versions, Firefox ESR, not dead`). * `not ie <= 8`: exclude browsers selected by previous queries. You can add `not ` to any query. ### Debug Run `npx browserslist` in project directory to see what browsers was selected by your queries. ```sh $ npx browserslist and_chr 61 and_ff 56 and_qq 1.2 and_uc 11.4 android 56 baidu 7.12 bb 10 chrome 62 edge 16 firefox 56 ios_saf 11 opera 48 safari 11 samsung 5 ``` ### Notes Browserslist works with separated versions of browsers. You should avoid queries like `Firefox > 0`. The list of the specified browsers acts as a white list which means other browsers are ignored. All queries are based on the [Can I Use] support table, e.g. `last 3 iOS versions` might select `8.4, 9.2, 9.3` (mixed major and minor), whereas `last 3 Chrome versions` might select `50, 49, 48` (major only). [`caniuse-lite/data/regions`]: https://github.com/ben-eb/caniuse-lite/tree/master/data/regions [two-letter country code]: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements [custom usage data]: #custom-usage-data [still maintained]: https://github.com/nodejs/Release [Can I Use]: https://caniuse.com/ ### Browsers Names are case insensitive: * `Android` for Android WebView. * `Baidu` for Baidu Browser. * `BlackBerry` or `bb` for Blackberry browser. * `Chrome` for Google Chrome. * `ChromeAndroid` or `and_chr` for Chrome for Android * `Edge` for Microsoft Edge. * `Electron` for Electron framework. It will be converted to Chrome version. * `Explorer` or `ie` for Internet Explorer. * `ExplorerMobile` or `ie_mob` for Internet Explorer Mobile. * `Firefox` or `ff` for Mozilla Firefox. * `FirefoxAndroid` or `and_ff` for Firefox for Android. * `iOS` or `ios_saf` for iOS Safari. * `Node` for Node.js. * `Opera` for Opera. * `OperaMini` or `op_mini` for Opera Mini. * `OperaMobile` or `op_mob` for Opera Mobile. * `QQAndroid` or `and_qq` for QQ Browser for Android. * `Safari` for desktop Safari. * `Samsung` for Samsung Internet. * `UCAndroid` or `and_uc` for UC Browser for Android. ## `package.json` If you want to reduce config files in project root, you can specify browsers in `package.json` with `browserslist` key: ```json { "private": true, "dependencies": { "autoprefixer": "^6.5.4" }, "browserslist": [ "last 1 version", "> 1%", "IE 10" ] } ``` ## Config File Browserslist config should be named `.browserslistrc` or `browserslist` and have browsers queries split by a new line. Comments starts with `#` symbol: ```yaml # Browsers that we support last 1 version > 1% IE 10 # sorry ``` Browserslist will check config in every directory in `path`. So, if tool process `app/styles/main.css`, you can put config to root, `app/` or `app/styles`. You can specify direct path in `BROWSERSLIST_CONFIG` environment variables. ## Shareable Configs You can use the following query to reference an exported Browserslist config from another package: ```json "browserslist": [ "extends browserslist-config-mycompany" ] ``` For security reasons, external configuration only supports packages that have the `browserslist-config-` prefix. npm scoped packages are also supported, by naming or prefixing the module with `@scope/browserslist-config`, such as `@scope/browserslist-config` or `@scope/browserslist-config-mycompany`. If you don’t accept Browserslist queries from users, you can disable the validation by using the `dangerousExtend` option: ```js browserslist(queries, { path, dangerousExtend: true }) ``` Because this uses `npm`'s resolution, you can also reference specific files in a package: ```json "browserslist": [ "extends browserslist-config-mycompany/desktop", "extends browserslist-config-mycompany/mobile" ] ``` When writing a shared Browserslist package, just export an array. `browserslist-config-mycompany/index.js`: ```js module.exports = [ 'last 1 version', '> 1%', 'ie 10' ] ``` ## Environment Variables If some tool use Browserslist inside, you can change browsers settings by [environment variables]: * `BROWSERSLIST` with browsers queries. ```sh BROWSERSLIST="> 5%" gulp css ``` * `BROWSERSLIST_CONFIG` with path to config file. ```sh BROWSERSLIST_CONFIG=./config/browserslist gulp css ``` * `BROWSERSLIST_ENV` with environments string. ```sh BROWSERSLIST_ENV="development" gulp css ``` * `BROWSERSLIST_STATS` with path to the custom usage data for `> 1% in my stats` query. ```sh BROWSERSLIST_STATS=./config/usage_data.json gulp css ``` * `BROWSERSLIST_DISABLE_CACHE` if you want to disable config reading cache. ```sh BROWSERSLIST_DISABLE_CACHE=1 gulp css ``` [environment variables]: https://en.wikipedia.org/wiki/Environment_variable ## Environments You can also specify different browser queries for various environments. Browserslist will choose query according to `BROWSERSLIST_ENV` or `NODE_ENV` variables. If none of them is declared, Browserslist will firstly look for `production` queries and then use defaults. In `package.json`: ```js "browserslist": { "production": [ "> 1%", "ie 10" ], "development": [ "last 1 chrome version", "last 1 firefox version" ] } ``` In `.browserslistrc` config: ```ini [production staging] > 1% ie 10 [development] last 1 chrome version last 1 firefox version ``` ## Custom Usage Data If you have a website, you can query against the usage statistics of your site. [`browserslist-ga`] will ask access to Google Analytics and then generate `browserslist-stats.json`: ``` npx browserslist-ga ``` Of course, you can generate usage statistics file by any other method. File format should be like: ```js { "ie": { "6": 0.01, "7": 0.4, "8": 1.5 }, "chrome": { … }, … } ``` Note that you can query against your custom usage data while also querying against global or regional data. For example, the query `> 1% in my stats, > 5% in US, 10%` is permitted. [`browserslist-ga`]: https://github.com/browserslist/browserslist-ga [Can I Use]: https://caniuse.com/ ## JS API ```js var browserslist = require('browserslist'); // Your CSS/JS build tool code var process = function (source, opts) { var browsers = browserslist(opts.browsers, { stats: opts.stats, path: opts.file, env: opts.env }); // Your code to add features for selected browsers } ``` Queries can be a string `"> 1%, IE 10"` or an array `['> 1%', 'IE 10']`. If a query is missing, Browserslist will look for a config file. You can provide a `path` option (that can be a file) to find the config file relatively to it. Options: * `path`: file or a directory path to look for config file. Default is `.`. * `env`: what environment section use from config. Default is `production`. * `stats`: custom usage statistics data. * `config`: path to config if you want to set it manually. * `ignoreUnknownVersions`: do not throw on direct query (like `ie 12`). Default is `false.` * `dangerousExtend`: Disable security checks for `extend` query. Default is `false.` For non-JS environment and debug purpose you can use CLI tool: ```sh browserslist "> 1%, IE 10" ``` ## Coverage You can get total users coverage for selected browsers by JS API: ```js browserslist.coverage(browserslist('> 1%')) //=> 81.4 ``` ```js browserslist.coverage(browserslist('> 1% in US'), 'US') //=> 83.1 ``` ```js browserslist.coverage(browserslist('> 1% in my stats'), 'my stats') //=> 83.1 ``` ```js browserslist.coverage(browserslist('> 1% in my stats', { stats }), stats) //=> 82.2 ``` Or by CLI: ```sh $ browserslist --coverage "> 1%" These browsers account for 81.4% of all users globally ``` ```sh $ browserslist --coverage=US "> 1% in US" These browsers account for 83.1% of all users in the US ``` ```sh $ browserslist --coverage "> 1% in my stats" These browsers account for 83.1% of all users in custom statistics ``` ```sh $ browserslist --coverage "> 1% in my stats" --stats=./stats.json These browsers account for 83.1% of all users in custom statistics ``` ## Cache Browserslist caches the configuration it reads from `package.json` and `browserslist` files, as well as knowledge about the existence of files, for the duration of the hosting process. To clear these caches, use: ```js browserslist.clearCaches(); ``` To disable the caching altogether, set the `BROWSERSLIST_DISABLE_CACHE` environment variable. ## Security Contact To report a security vulnerability, please use the [Tidelift security contact]. Tidelift will coordinate the fix and disclosure. [Tidelift security contact]: https://tidelift.com/security [![Build Status](https://secure.travis-ci.org/soldair/node-buffer-indexof.png)](http://travis-ci.org/soldair/node-buffer-indexof) buffer-indexof =================== find the index of a buffer in a buffer. should behave like String.indexOf etc. ```js var bindexOf = require('buffer-indexof'); var newLineBuffer = new Buffer("\n"); var b = new Buffer("hi\nho\nsilver"); bindexOf(b,newLineBuffer) === 2 // you can also start from index bindexOf(b,newLineBuffer,3) === 5 // no match === -1 bindexOf(b,newLineBuffer,6) === -1 ``` CHANGELOG ---------- - 1.0.0 - fixed issue finding multibyte needles in haystack. thanks @imulus - 1.0.1 - fixed failing to find partial matches as pointed out by @bahaa-aidi in #2 # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # Source Map [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map) This is a library to generate and consume the source map format [described here][format]. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit ## Use with Node $ npm install source-map ## Use on the Web <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script> -------------------------------------------------------------------------------- <!-- `npm run toc` to regenerate the Table of Contents --> <!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> ## Table of Contents - [Examples](#examples) - [Consuming a source map](#consuming-a-source-map) - [Generating a source map](#generating-a-source-map) - [With SourceNode (high level API)](#with-sourcenode-high-level-api) - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) - [API](#api) - [SourceMapConsumer](#sourcemapconsumer) - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) - [SourceMapGenerator](#sourcemapgenerator) - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) - [SourceNode](#sourcenode) - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Examples ### Consuming a source map ```js var rawSourceMap = { version: 3, file: 'min.js', names: ['bar', 'baz', 'n'], sources: ['one.js', 'two.js'], sourceRoot: 'http://example.com/www/js/', mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' }; var smc = new SourceMapConsumer(rawSourceMap); console.log(smc.sources); // [ 'http://example.com/www/js/one.js', // 'http://example.com/www/js/two.js' ] console.log(smc.originalPositionFor({ line: 2, column: 28 })); // { source: 'http://example.com/www/js/two.js', // line: 2, // column: 10, // name: 'n' } console.log(smc.generatedPositionFor({ source: 'http://example.com/www/js/two.js', line: 2, column: 10 })); // { line: 2, column: 28 } smc.eachMapping(function (m) { // ... }); ``` ### Generating a source map In depth guide: [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) #### With SourceNode (high level API) ```js function compile(ast) { switch (ast.type) { case 'BinaryExpression': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, [compile(ast.left), " + ", compile(ast.right)] ); case 'Literal': return new SourceNode( ast.location.line, ast.location.column, ast.location.source, String(ast.value) ); // ... default: throw new Error("Bad AST"); } } var ast = parse("40 + 2", "add.js"); console.log(compile(ast).toStringWithSourceMap({ file: 'add.js' })); // { code: '40 + 2', // map: [object SourceMapGenerator] } ``` #### With SourceMapGenerator (low level API) ```js var map = new SourceMapGenerator({ file: "source-mapped.js" }); map.addMapping({ generated: { line: 10, column: 35 }, source: "foo.js", original: { line: 33, column: 2 }, name: "christopher" }); console.log(map.toString()); // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' ``` ## API Get a reference to the module: ```js // Node.js var sourceMap = require('source-map'); // Browser builds var sourceMap = window.sourceMap; // Inside Firefox const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); ``` ### SourceMapConsumer A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source. #### new SourceMapConsumer(rawSourceMap) The only parameter is the raw source map (either as a string which can be `JSON.parse`'d, or an object). According to the spec, source maps have the following attributes: * `version`: Which version of the source map spec this map is following. * `sources`: An array of URLs to the original source files. * `names`: An array of identifiers which can be referenced by individual mappings. * `sourceRoot`: Optional. The URL root from which all sources are relative. * `sourcesContent`: Optional. An array of contents of the original source files. * `mappings`: A string of base64 VLQs which contain the actual mappings. * `file`: Optional. The generated filename this source map is associated with. ```js var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); ``` #### SourceMapConsumer.prototype.computeColumnSpans() Compute the last column for each generated mapping. The last column is inclusive. ```js // Before: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] consumer.computeColumnSpans(); // After: consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1, // lastColumn: 9 }, // { line: 2, // column: 10, // lastColumn: 19 }, // { line: 2, // column: 20, // lastColumn: Infinity } ] ``` #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties: * `line`: The line number in the generated source. * `column`: The column number in the generated source. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to `SourceMapConsumer.GREATEST_LOWER_BOUND`. and an object is returned with the following properties: * `source`: The original source file, or null if this information is not available. * `line`: The line number in the original source, or null if this information is not available. * `column`: The column number in the original source, or null if this information is not available. * `name`: The original identifier, or null if this information is not available. ```js consumer.originalPositionFor({ line: 2, column: 10 }) // { source: 'foo.coffee', // line: 2, // column: 2, // name: null } consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) // { source: null, // line: null, // column: null, // name: null } ``` #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. * `column`: The column number in the original source. and an object is returned with the following properties: * `line`: The line number in the generated source, or null. * `column`: The column number in the generated source, or null. ```js consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) // { line: 1, // column: 56 } ``` #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets. The only argument is an object with the following properties: * `source`: The filename of the original source. * `line`: The line number in the original source. * `column`: Optional. The column number in the original source. and an array of objects is returned, each with the following properties: * `line`: The line number in the generated source, or null. * `column`: The column number in the generated source, or null. ```js consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) // [ { line: 2, // column: 1 }, // { line: 2, // column: 10 }, // { line: 2, // column: 20 } ] ``` #### SourceMapConsumer.prototype.hasContentsOfAllSources() Return true if we have the embedded source content for every source listed in the source map, false otherwise. In other words, if this method returns `true`, then `consumer.sourceContentFor(s)` will succeed for every source `s` in `consumer.sources`. ```js // ... if (consumer.hasContentsOfAllSources()) { consumerReadyCallback(consumer); } else { fetchSources(consumer, consumerReadyCallback); } // ... ``` #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) Returns the original source content for the source provided. The only argument is the URL of the original source file. If the source content for the given source is not found, then an error is thrown. Optionally, pass `true` as the second param to have `null` returned instead. ```js consumer.sources // [ "my-cool-lib.clj" ] consumer.sourceContentFor("my-cool-lib.clj") // "..." consumer.sourceContentFor("this is not in the source map"); // Error: "this is not in the source map" is not in the source map consumer.sourceContentFor("this is not in the source map", true); // null ``` #### SourceMapConsumer.prototype.eachMapping(callback, context, order) Iterate over each mapping between an original source/line/column and a generated line/column in this source map. * `callback`: The function that is called with each mapping. Mappings have the form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, name }` * `context`: Optional. If specified, this object will be the value of `this` every time that `callback` is called. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to `SourceMapConsumer.GENERATED_ORDER`. ```js consumer.eachMapping(function (m) { console.log(m); }) // ... // { source: 'illmatic.js', // generatedLine: 1, // generatedColumn: 0, // originalLine: 1, // originalColumn: 0, // name: null } // { source: 'illmatic.js', // generatedLine: 2, // generatedColumn: 0, // originalLine: 2, // originalColumn: 0, // name: null } // ... ``` ### SourceMapGenerator An instance of the SourceMapGenerator represents a source map which is being built incrementally. #### new SourceMapGenerator([startOfSourceMap]) You may pass an object with the following properties: * `file`: The filename of the generated source that this source map is associated with. * `sourceRoot`: A root for all relative URLs in this source map. * `skipValidation`: Optional. When `true`, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible. ```js var generator = new sourceMap.SourceMapGenerator({ file: "my-generated-javascript-file.js", sourceRoot: "http://example.com/app/js/" }); ``` #### SourceMapGenerator.fromSourceMap(sourceMapConsumer) Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. * `sourceMapConsumer` The SourceMap. ```js var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer); ``` #### SourceMapGenerator.prototype.addMapping(mapping) Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties: * `generated`: An object with the generated line and column positions. * `original`: An object with the original line and column positions. * `source`: The original source file (relative to the sourceRoot). * `name`: An optional original token name for this mapping. ```js generator.addMapping({ source: "module-one.scm", original: { line: 128, column: 0 }, generated: { line: 3, column: 456 } }) ``` #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for an original source file. * `sourceFile` the URL of the original source file. * `sourceContent` the content of the source file. ```js generator.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map. * `sourceMapConsumer`: The SourceMap to be applied. * `sourceFile`: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap. This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap. If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying `'.'` has the same effect.) #### SourceMapGenerator.prototype.toString() Renders the source map being generated to a string. ```js generator.toString() // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' ``` ### SourceNode SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map. #### new SourceNode([line, column, source[, chunk[, name]]]) * `line`: The original line number associated with this source node, or null if it isn't associated with an original line. * `column`: The original column number associated with this source node, or null if it isn't associated with an original column. * `source`: The original source's filename; null if no filename is provided. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see below. * `name`: Optional. The original identifier. ```js var node = new SourceNode(1, 2, "a.cpp", [ new SourceNode(3, 4, "b.cpp", "extern int status;\n"), new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), ]); ``` #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) Creates a SourceNode from generated code and a SourceMapConsumer. * `code`: The generated code * `sourceMapConsumer` The SourceMap for the generated code * `relativePath` The optional path that relative sources in `sourceMapConsumer` should be relative to. ```js var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), consumer); ``` #### SourceNode.prototype.add(chunk) Add a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.add(" + "); node.add(otherNode); node.add([leftHandOperandNode, " + ", rightHandOperandNode]); ``` #### SourceNode.prototype.prepend(chunk) Prepend a chunk of generated JS to this source node. * `chunk`: A string snippet of generated JS code, another instance of `SourceNode`, or an array where each member is one of those things. ```js node.prepend("/** Build Id: f783haef86324gf **/\n\n"); ``` #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) Set the source content for a source file. This will be added to the `SourceMap` in the `sourcesContent` field. * `sourceFile`: The filename of the source file * `sourceContent`: The content of the source file ```js node.setSourceContent("module-one.scm", fs.readFileSync("path/to/module-one.scm")) ``` #### SourceNode.prototype.walk(fn) Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location. * `fn`: The traversal function. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.walk(function (code, loc) { console.log("WALK:", code, loc); }) // WALK: uno { source: 'b.js', line: 3, column: 4, name: null } // WALK: dos { source: 'a.js', line: 1, column: 2, name: null } // WALK: tres { source: 'a.js', line: 1, column: 2, name: null } // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } ``` #### SourceNode.prototype.walkSourceContents(fn) Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content. * `fn`: The traversal function. ```js var a = new SourceNode(1, 2, "a.js", "generated from a"); a.setSourceContent("a.js", "original a"); var b = new SourceNode(1, 2, "b.js", "generated from b"); b.setSourceContent("b.js", "original b"); var c = new SourceNode(1, 2, "c.js", "generated from c"); c.setSourceContent("c.js", "original c"); var node = new SourceNode(null, null, null, [a, b, c]); node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) // WALK: a.js : original a // WALK: b.js : original b // WALK: c.js : original c ``` #### SourceNode.prototype.join(sep) Like `Array.prototype.join` except for SourceNodes. Inserts the separator between each of this source node's children. * `sep`: The separator. ```js var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); var operand = new SourceNode(3, 4, "a.rs", "="); var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); var joinedNode = node.join(" "); ``` #### SourceNode.prototype.replaceRight(pattern, replacement) Call `String.prototype.replace` on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc. * `pattern`: The pattern to replace. * `replacement`: The thing to replace the pattern with. ```js // Trim trailing white space. node.replaceRight(/\s*$/, ""); ``` #### SourceNode.prototype.toString() Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toString() // 'unodostresquatro' ``` #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources. The arguments are the same as those to `new SourceMapGenerator`. ```js var node = new SourceNode(1, 2, "a.js", [ new SourceNode(3, 4, "b.js", "uno"), "dos", [ "tres", new SourceNode(5, 6, "c.js", "quatro") ] ]); node.toStringWithSourceMap({ file: "my-output-file.js" }) // { code: 'unodostresquatro', // map: [object SourceMapGenerator] } ``` # mixin-object [![NPM version](https://badge.fury.io/js/mixin-object.svg)](http://badge.fury.io/js/mixin-object) > Mixin the own and inherited properties of other objects onto the first object. Pass an empty object as the first arg to shallow clone. If you only want to combine own-properties, use [extend-shallow](https://github.com/jonschlinkert/extend-shallow). ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i mixin-object --save ``` Install with [bower](http://bower.io/) ```sh $ bower install mixin-object --save ``` ## Usage ```js var mixin = require('mixin-object'); var obj = {c: 'c'}; var foo = mixin({a: 'a'}, {b: 'b'}); console.log(foo); //=> {c: 'c', a: 'a', b: 'b'} console.log(obj); //=> {c: 'c'} mixin({}, {a: 'a'}, {b: 'b'}); //=> {a: 'a', b: 'b'} ``` ## Related * [assign-deep](https://github.com/jonschlinkert/assign-deep): Deeply assign the enumerable properties of source objects to a destination object. * [defaults-deep](https://github.com/jonschlinkert/defaults-deep): Like `extend` but recursively copies only the missing properties/values to the target object. * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [mixin-deep](https://github.com/jonschlinkert/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. * [merge-deep](https://github.com/jonschlinkert/merge-deep): Recursively merge values in a javascript object. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/mixin-object/issues/new) ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2014-2015 [Jon Schlinkert](https://github.com/jonschlinkert) Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on July 05, 2015._ # cacache [![npm version](https://img.shields.io/npm/v/cacache.svg)](https://npm.im/cacache) [![license](https://img.shields.io/npm/l/cacache.svg)](https://npm.im/cacache) [![Travis](https://img.shields.io/travis/zkat/cacache.svg)](https://travis-ci.org/zkat/cacache) [![AppVeyor](https://ci.appveyor.com/api/projects/status/github/zkat/cacache?svg=true)](https://ci.appveyor.com/project/zkat/cacache) [![Coverage Status](https://coveralls.io/repos/github/zkat/cacache/badge.svg?branch=latest)](https://coveralls.io/github/zkat/cacache?branch=latest) [`cacache`](https://github.com/zkat/cacache) is a Node.js library for managing local key and content address caches. It's really fast, really good at concurrency, and it will never give you corrupted data, even if cache files get corrupted or manipulated. It was originally written to be used as [npm](https://npm.im)'s local cache, but can just as easily be used on its own. _Translations: [español](README.es.md)_ ## Install `$ npm install --save cacache` ## Table of Contents * [Example](#example) * [Features](#features) * [Contributing](#contributing) * [API](#api) * [Using localized APIs](#localized-api) * Reading * [`ls`](#ls) * [`ls.stream`](#ls-stream) * [`get`](#get-data) * [`get.stream`](#get-stream) * [`get.info`](#get-info) * [`get.hasContent`](#get-hasContent) * Writing * [`put`](#put-data) * [`put.stream`](#put-stream) * [`put*` opts](#put-options) * [`rm.all`](#rm-all) * [`rm.entry`](#rm-entry) * [`rm.content`](#rm-content) * Utilities * [`setLocale`](#set-locale) * [`clearMemoized`](#clear-memoized) * [`tmp.mkdir`](#tmp-mkdir) * [`tmp.withTmp`](#with-tmp) * Integrity * [Subresource Integrity](#integrity) * [`verify`](#verify) * [`verify.lastRun`](#verify-last-run) ### Example ```javascript const cacache = require('cacache/en') const fs = require('fs') const tarball = '/path/to/mytar.tgz' const cachePath = '/tmp/my-toy-cache' const key = 'my-unique-key-1234' // Cache it! Use `cachePath` as the root of the content cache cacache.put(cachePath, key, '10293801983029384').then(integrity => { console.log(`Saved content to ${cachePath}.`) }) const destination = '/tmp/mytar.tgz' // Copy the contents out of the cache and into their destination! // But this time, use stream instead! cacache.get.stream( cachePath, key ).pipe( fs.createWriteStream(destination) ).on('finish', () => { console.log('done extracting!') }) // The same thing, but skip the key index. cacache.get.byDigest(cachePath, integrityHash).then(data => { fs.writeFile(destination, data, err => { console.log('tarball data fetched based on its sha512sum and written out!') }) }) ``` ### Features * Extraction by key or by content address (shasum, etc) * [Subresource Integrity](#integrity) web standard support * Multi-hash support - safely host sha1, sha512, etc, in a single cache * Automatic content deduplication * Fault tolerance (immune to corruption, partial writes, process races, etc) * Consistency guarantees on read and write (full data verification) * Lockless, high-concurrency cache access * Streaming support * Promise support * Pretty darn fast -- sub-millisecond reads and writes including verification * Arbitrary metadata storage * Garbage collection and additional offline verification * Thorough test coverage * There's probably a bloom filter in there somewhere. Those are cool, right? 🤔 ### Contributing The cacache team enthusiastically welcomes contributions and project participation! There's a bunch of things you can do if you want to contribute! The [Contributor Guide](CONTRIBUTING.md) has all the information you need for everything from reporting bugs to contributing entire new features. Please don't hesitate to jump in if you'd like to, or even ask us questions if something isn't clear. All participants and maintainers in this project are expected to follow [Code of Conduct](CODE_OF_CONDUCT.md), and just generally be excellent to each other. Please refer to the [Changelog](CHANGELOG.md) for project history details, too. Happy hacking! ### API #### <a name="localized-api"></a> Using localized APIs cacache includes a complete API in English, with the same features as other translations. To use the English API as documented in this README, use `require('cacache/en')`. This is also currently the default if you do `require('cacache')`, but may change in the future. cacache also supports other languages! You can find the list of currently supported ones by looking in `./locales` in the source directory. You can use the API in that language with `require('cacache/<lang>')`. Want to add support for a new language? Please go ahead! You should be able to copy `./locales/en.js` and `./locales/en.json` and fill them in. Translating the `README.md` is a bit more work, but also appreciated if you get around to it. 👍🏼 #### <a name="ls"></a> `> cacache.ls(cache) -> Promise<Object>` Lists info for all entries currently in the cache as a single large object. Each entry in the object will be keyed by the unique index key, with corresponding [`get.info`](#get-info) objects as the values. ##### Example ```javascript cacache.ls(cachePath).then(console.log) // Output { 'my-thing': { key: 'my-thing', integrity: 'sha512-BaSe64/EnCoDED+HAsh==' path: '.testcache/content/deadbeef', // joined with `cachePath` time: 12345698490, size: 4023948, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } }, 'other-thing': { key: 'other-thing', integrity: 'sha1-ANothER+hasH=', path: '.testcache/content/bada55', time: 11992309289, size: 111112 } } ``` #### <a name="ls-stream"></a> `> cacache.ls.stream(cache) -> Readable` Lists info for all entries currently in the cache as a single large object. This works just like [`ls`](#ls), except [`get.info`](#get-info) entries are returned as `'data'` events on the returned stream. ##### Example ```javascript cacache.ls.stream(cachePath).on('data', console.log) // Output { key: 'my-thing', integrity: 'sha512-BaSe64HaSh', path: '.testcache/content/deadbeef', // joined with `cachePath` time: 12345698490, size: 13423, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } } { key: 'other-thing', integrity: 'whirlpool-WoWSoMuchSupport', path: '.testcache/content/bada55', time: 11992309289, size: 498023984029 } { ... } ``` #### <a name="get-data"></a> `> cacache.get(cache, key, [opts]) -> Promise({data, metadata, integrity})` Returns an object with the cached data, digest, and metadata identified by `key`. The `data` property of this object will be a `Buffer` instance that presumably holds some data that means something to you. I'm sure you know what to do with it! cacache just won't care. `integrity` is a [Subresource Integrity](#integrity) string. That is, a string that can be used to verify `data`, which looks like `<hash-algorithm>-<base64-integrity-hash>`. If there is no content identified by `key`, or if the locally-stored data does not pass the validity checksum, the promise will be rejected. A sub-function, `get.byDigest` may be used for identical behavior, except lookup will happen by integrity hash, bypassing the index entirely. This version of the function *only* returns `data` itself, without any wrapper. ##### Note This function loads the entire cache entry into memory before returning it. If you're dealing with Very Large data, consider using [`get.stream`](#get-stream) instead. ##### Example ```javascript // Look up by key cache.get(cachePath, 'my-thing').then(console.log) // Output: { metadata: { thingName: 'my' }, integrity: 'sha512-BaSe64HaSh', data: Buffer#<deadbeef>, size: 9320 } // Look up by digest cache.get.byDigest(cachePath, 'sha512-BaSe64HaSh').then(console.log) // Output: Buffer#<deadbeef> ``` #### <a name="get-stream"></a> `> cacache.get.stream(cache, key, [opts]) -> Readable` Returns a [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams) of the cached data identified by `key`. If there is no content identified by `key`, or if the locally-stored data does not pass the validity checksum, an error will be emitted. `metadata` and `integrity` events will be emitted before the stream closes, if you need to collect that extra data about the cached entry. A sub-function, `get.stream.byDigest` may be used for identical behavior, except lookup will happen by integrity hash, bypassing the index entirely. This version does not emit the `metadata` and `integrity` events at all. ##### Example ```javascript // Look up by key cache.get.stream( cachePath, 'my-thing' ).on('metadata', metadata => { console.log('metadata:', metadata) }).on('integrity', integrity => { console.log('integrity:', integrity) }).pipe( fs.createWriteStream('./x.tgz') ) // Outputs: metadata: { ... } integrity: 'sha512-SoMeDIGest+64==' // Look up by digest cache.get.stream.byDigest( cachePath, 'sha512-SoMeDIGest+64==' ).pipe( fs.createWriteStream('./x.tgz') ) ``` #### <a name="get-info"></a> `> cacache.get.info(cache, key) -> Promise` Looks up `key` in the cache index, returning information about the entry if one exists. ##### Fields * `key` - Key the entry was looked up under. Matches the `key` argument. * `integrity` - [Subresource Integrity hash](#integrity) for the content this entry refers to. * `path` - Filesystem path relative to `cache` argument where content is stored. * `time` - Timestamp the entry was first added on. * `metadata` - User-assigned metadata associated with the entry/content. ##### Example ```javascript cacache.get.info(cachePath, 'my-thing').then(console.log) // Output { key: 'my-thing', integrity: 'sha256-MUSTVERIFY+ALL/THINGS==' path: '.testcache/content/deadbeef', time: 12345698490, size: 849234, metadata: { name: 'blah', version: '1.2.3', description: 'this was once a package but now it is my-thing' } } ``` #### <a name="get-hasContent"></a> `> cacache.get.hasContent(cache, integrity) -> Promise` Looks up a [Subresource Integrity hash](#integrity) in the cache. If content exists for this `integrity`, it will return an object, with the specific single integrity hash that was found in `sri` key, and the size of the found content as `size`. If no content exists for this integrity, it will return `false`. ##### Example ```javascript cacache.get.hasContent(cachePath, 'sha256-MUSTVERIFY+ALL/THINGS==').then(console.log) // Output { sri: { source: 'sha256-MUSTVERIFY+ALL/THINGS==', algorithm: 'sha256', digest: 'MUSTVERIFY+ALL/THINGS==', options: [] }, size: 9001 } cacache.get.hasContent(cachePath, 'sha521-NOT+IN/CACHE==').then(console.log) // Output false ``` #### <a name="put-data"></a> `> cacache.put(cache, key, data, [opts]) -> Promise` Inserts data passed to it into the cache. The returned Promise resolves with a digest (generated according to [`opts.algorithms`](#optsalgorithms)) after the cache entry has been successfully written. ##### Example ```javascript fetch( 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz' ).then(data => { return cacache.put(cachePath, 'registry.npmjs.org|[email protected]', data) }).then(integrity => { console.log('integrity hash is', integrity) }) ``` #### <a name="put-stream"></a> `> cacache.put.stream(cache, key, [opts]) -> Writable` Returns a [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams) that inserts data written to it into the cache. Emits an `integrity` event with the digest of written contents when it succeeds. ##### Example ```javascript request.get( 'https://registry.npmjs.org/cacache/-/cacache-1.0.0.tgz' ).pipe( cacache.put.stream( cachePath, 'registry.npmjs.org|[email protected]' ).on('integrity', d => console.log(`integrity digest is ${d}`)) ) ``` #### <a name="put-options"></a> `> cacache.put options` `cacache.put` functions have a number of options in common. ##### `opts.metadata` Arbitrary metadata to be attached to the inserted key. ##### `opts.size` If provided, the data stream will be verified to check that enough data was passed through. If there's more or less data than expected, insertion will fail with an `EBADSIZE` error. ##### `opts.integrity` If present, the pre-calculated digest for the inserted content. If this option if provided and does not match the post-insertion digest, insertion will fail with an `EINTEGRITY` error. `algorithms` has no effect if this option is present. ##### `opts.algorithms` Default: ['sha512'] Hashing algorithms to use when calculating the [subresource integrity digest](#integrity) for inserted data. Can use any algorithm listed in `crypto.getHashes()` or `'omakase'`/`'お任せします'` to pick a random hash algorithm on each insertion. You may also use any anagram of `'modnar'` to use this feature. Currently only supports one algorithm at a time (i.e., an array length of exactly `1`). Has no effect if `opts.integrity` is present. ##### `opts.uid`/`opts.gid` If provided, cacache will do its best to make sure any new files added to the cache use this particular `uid`/`gid` combination. This can be used, for example, to drop permissions when someone uses `sudo`, but cacache makes no assumptions about your needs here. ##### `opts.memoize` Default: null If provided, cacache will memoize the given cache insertion in memory, bypassing any filesystem checks for that key or digest in future cache fetches. Nothing will be written to the in-memory cache unless this option is explicitly truthy. If `opts.memoize` is an object or a `Map`-like (that is, an object with `get` and `set` methods), it will be written to instead of the global memoization cache. Reading from disk data can be forced by explicitly passing `memoize: false` to the reader functions, but their default will be to read from memory. #### <a name="rm-all"></a> `> cacache.rm.all(cache) -> Promise` Clears the entire cache. Mainly by blowing away the cache directory itself. ##### Example ```javascript cacache.rm.all(cachePath).then(() => { console.log('THE APOCALYPSE IS UPON US 😱') }) ``` #### <a name="rm-entry"></a> `> cacache.rm.entry(cache, key) -> Promise` Alias: `cacache.rm` Removes the index entry for `key`. Content will still be accessible if requested directly by content address ([`get.stream.byDigest`](#get-stream)). To remove the content itself (which might still be used by other entries), use [`rm.content`](#rm-content). Or, to safely vacuum any unused content, use [`verify`](#verify). ##### Example ```javascript cacache.rm.entry(cachePath, 'my-thing').then(() => { console.log('I did not like it anyway') }) ``` #### <a name="rm-content"></a> `> cacache.rm.content(cache, integrity) -> Promise` Removes the content identified by `integrity`. Any index entries referring to it will not be usable again until the content is re-added to the cache with an identical digest. ##### Example ```javascript cacache.rm.content(cachePath, 'sha512-SoMeDIGest/IN+BaSE64==').then(() => { console.log('data for my-thing is gone!') }) ``` #### <a name="set-locale"></a> `> cacache.setLocale(locale)` Configure the language/locale used for messages and errors coming from cacache. The list of available locales is in the `./locales` directory in the project root. _Interested in contributing more languages! [Submit a PR](CONTRIBUTING.md)!_ #### <a name="clear-memoized"></a> `> cacache.clearMemoized()` Completely resets the in-memory entry cache. #### <a name="tmp-mkdir"></a> `> tmp.mkdir(cache, opts) -> Promise<Path>` Returns a unique temporary directory inside the cache's `tmp` dir. This directory will use the same safe user assignment that all the other stuff use. Once the directory is made, it's the user's responsibility that all files within are made according to the same `opts.gid`/`opts.uid` settings that would be passed in. If not, you can ask cacache to do it for you by calling [`tmp.fix()`](#tmp-fix), which will fix all tmp directory permissions. If you want automatic cleanup of this directory, use [`tmp.withTmp()`](#with-tpm) ##### Example ```javascript cacache.tmp.mkdir(cache).then(dir => { fs.writeFile(path.join(dir, 'blablabla'), Buffer#<1234>, ...) }) ``` #### <a name="with-tmp"></a> `> tmp.withTmp(cache, opts, cb) -> Promise` Creates a temporary directory with [`tmp.mkdir()`](#tmp-mkdir) and calls `cb` with it. The created temporary directory will be removed when the return value of `cb()` resolves -- that is, if you return a Promise from `cb()`, the tmp directory will be automatically deleted once that promise completes. The same caveats apply when it comes to managing permissions for the tmp dir's contents. ##### Example ```javascript cacache.tmp.withTmp(cache, dir => { return fs.writeFileAsync(path.join(dir, 'blablabla'), Buffer#<1234>, ...) }).then(() => { // `dir` no longer exists }) ``` #### <a name="integrity"></a> Subresource Integrity Digests For content verification and addressing, cacache uses strings following the [Subresource Integrity spec](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity). That is, any time cacache expects an `integrity` argument or option, it should be in the format `<hashAlgorithm>-<base64-hash>`. One deviation from the current spec is that cacache will support any hash algorithms supported by the underlying Node.js process. You can use `crypto.getHashes()` to see which ones you can use. ##### Generating Digests Yourself If you have an existing content shasum, they are generally formatted as a hexadecimal string (that is, a sha1 would look like: `5f5513f8822fdbe5145af33b64d8d970dcf95c6e`). In order to be compatible with cacache, you'll need to convert this to an equivalent subresource integrity string. For this example, the corresponding hash would be: `sha1-X1UT+IIv2+UUWvM7ZNjZcNz5XG4=`. If you want to generate an integrity string yourself for existing data, you can use something like this: ```javascript const crypto = require('crypto') const hashAlgorithm = 'sha512' const data = 'foobarbaz' const integrity = ( hashAlgorithm + '-' + crypto.createHash(hashAlgorithm).update(data).digest('base64') ) ``` You can also use [`ssri`](https://npm.im/ssri) to have a richer set of functionality around SRI strings, including generation, parsing, and translating from existing hex-formatted strings. #### <a name="verify"></a> `> cacache.verify(cache, opts) -> Promise` Checks out and fixes up your cache: * Cleans up corrupted or invalid index entries. * Custom entry filtering options. * Garbage collects any content entries not referenced by the index. * Checks integrity for all content entries and removes invalid content. * Fixes cache ownership. * Removes the `tmp` directory in the cache and all its contents. When it's done, it'll return an object with various stats about the verification process, including amount of storage reclaimed, number of valid entries, number of entries removed, etc. ##### Options * `opts.uid` - uid to assign to cache and its contents * `opts.gid` - gid to assign to cache and its contents * `opts.filter` - receives a formatted entry. Return false to remove it. Note: might be called more than once on the same entry. ##### Example ```sh echo somegarbage >> $CACHEPATH/content/deadbeef ``` ```javascript cacache.verify(cachePath).then(stats => { // deadbeef collected, because of invalid checksum. console.log('cache is much nicer now! stats:', stats) }) ``` #### <a name="verify-last-run"></a> `> cacache.verify.lastRun(cache) -> Promise` Returns a `Date` representing the last time `cacache.verify` was run on `cache`. ##### Example ```javascript cacache.verify(cachePath).then(() => { cacache.verify.lastRun(cachePath).then(lastTime => { console.log('cacache.verify was last called on' + lastTime) }) }) ``` # cache-base [![NPM version](https://img.shields.io/npm/v/cache-base.svg?style=flat)](https://www.npmjs.com/package/cache-base) [![NPM monthly downloads](https://img.shields.io/npm/dm/cache-base.svg?style=flat)](https://npmjs.org/package/cache-base) [![NPM total downloads](https://img.shields.io/npm/dt/cache-base.svg?style=flat)](https://npmjs.org/package/cache-base) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/cache-base.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/cache-base) > Basic object cache with `get`, `set`, `del`, and `has` methods for node.js/javascript projects. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save cache-base ``` ## Usage ```js var Cache = require('cache-base'); // instantiate var app = new Cache(); // set values app.set('a', 'b'); app.set('c.d', 'e'); // get values app.get('a'); //=> 'b' app.get('c'); //=> {d: 'e'} console.log(app.cache); //=> {a: 'b'} ``` **Inherit** ```js var util = require('util'); var Cache = require('cache-base'); function MyApp() { Cache.call(this); } util.inherits(MyApp, Cache); var app = new MyApp(); app.set('a', 'b'); app.get('a'); //=> 'b' ``` **Namespace** Define a custom property for storing values. ```js var Cache = require('cache-base').namespace('data'); var app = new Cache(); app.set('a', 'b'); console.log(app.data); //=> {a: 'b'} ``` ## API ### [namespace](index.js#L29) Create a `Cache` constructor that when instantiated will store values on the given `prop`. **Params** * `prop` **{String}**: The property name to use for storing values. * `returns` **{Function}**: Returns a custom `Cache` constructor **Example** ```js var Cache = require('cache-base').namespace('data'); var cache = new Cache(); cache.set('foo', 'bar'); //=> {data: {foo: 'bar'}} ``` ### [Cache](index.js#L43) Create a new `Cache`. Internally the `Cache` constructor is created using the `namespace` function, with `cache` defined as the storage object. **Params** * `cache` **{Object}**: Optionally pass an object to initialize with. **Example** ```js var app = new Cache(); ``` ### [.set](index.js#L84) Assign `value` to `key`. Also emits `set` with the key and value. **Params** * `key` **{String}** * `value` **{any}** * `returns` **{Object}**: Returns the instance for chaining. **Events** * `emits`: `set` with `key` and `value` as arguments. **Example** ```js app.on('set', function(key, val) { // do something when `set` is emitted }); app.set(key, value); // also takes an object or array app.set({name: 'Halle'}); app.set([{foo: 'bar'}, {baz: 'quux'}]); console.log(app); //=> {name: 'Halle', foo: 'bar', baz: 'quux'} ``` ### [.union](index.js#L114) Union `array` to `key`. Also emits `set` with the key and value. **Params** * `key` **{String}** * `value` **{any}** * `returns` **{Object}**: Returns the instance for chaining. **Example** ```js app.union('a.b', ['foo']); app.union('a.b', ['bar']); console.log(app.get('a')); //=> {b: ['foo', 'bar']} ``` ### [.get](index.js#L144) Return the value of `key`. Dot notation may be used to get [nested property values](https://github.com/jonschlinkert/get-value). **Params** * `key` **{String}**: The name of the property to get. Dot-notation may be used. * `returns` **{any}**: Returns the value of `key` **Events** * `emits`: `get` with `key` and `value` as arguments. **Example** ```js app.set('a.b.c', 'd'); app.get('a.b'); //=> {c: 'd'} app.get(['a', 'b']); //=> {c: 'd'} ``` ### [.has](index.js#L171) Return true if app has a stored value for `key`, false only if value is `undefined`. **Params** * `key` **{String}** * `returns` **{Boolean}** **Events** * `emits`: `has` with `key` and true or false as arguments. **Example** ```js app.set('foo', 'bar'); app.has('foo'); //=> true ``` ### [.del](index.js#L199) Delete one or more properties from the instance. **Params** * `key` **{String|Array}**: Property name or array of property names. * `returns` **{Object}**: Returns the instance for chaining. **Events** * `emits`: `del` with the `key` as the only argument. **Example** ```js app.del(); // delete all // or app.del('foo'); // or app.del(['foo', 'bar']); ``` ### [.clear](index.js#L218) Reset the entire cache to an empty object. **Example** ```js app.clear(); ``` ### [.visit](index.js#L235) Visit `method` over the properties in the given object, or map visit over the object-elements in an array. **Params** * `method` **{String}**: The name of the `base` method to call. * `val` **{Object|Array}**: The object or array to iterate over. * `returns` **{Object}**: Returns the instance for chaining. ## About ### Related projects * [base-methods](https://www.npmjs.com/package/base-methods): base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/jonschlinkert/base-methods) | [homepage](https://github.com/jonschlinkert/base-methods "base-methods is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value "Use property paths (`a.b.c`) to get a nested value from an object.") * [has-value](https://www.npmjs.com/package/has-value): Returns true if a value exists, false if empty. Works with deeply nested values using… [more](https://github.com/jonschlinkert/has-value) | [homepage](https://github.com/jonschlinkert/has-value "Returns true if a value exists, false if empty. Works with deeply nested values using object paths.") * [option-cache](https://www.npmjs.com/package/option-cache): Simple API for managing options in JavaScript applications. | [homepage](https://github.com/jonschlinkert/option-cache "Simple API for managing options in JavaScript applications.") * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value "Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths.") * [unset-value](https://www.npmjs.com/package/unset-value): Delete nested properties from an object using dot notation. | [homepage](https://github.com/jonschlinkert/unset-value "Delete nested properties from an object using dot notation.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 54 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ unique-slug =========== Generate a unique character string suitible for use in files and URLs. ``` var uniqueSlug = require('unique-slug') var randomSlug = uniqueSlug() var fileSlug = uniqueSlug('/etc/passwd') ``` ### uniqueSlug(*str*) → String (8 chars) If *str* is passed in then the return value will be its murmur hash in hex. If *str* is not passed in, it will be 4 bytes coverted into 8 hex characters, generated by `crypto.pseudoRandomBytes`. # is-accessor-descriptor [![NPM version](https://img.shields.io/npm/v/is-accessor-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-accessor-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-accessor-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-accessor-descriptor) > Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-accessor-descriptor ``` ## Usage ```js var isAccessor = require('is-accessor-descriptor'); isAccessor({get: function() {}}); //=> true ``` You may also pass an object and property name to check if the property is an accessor: ```js isAccessor(foo, 'bar'); ``` ## Examples `false` when not an object ```js isAccessor('a') isAccessor(null) isAccessor([]) //=> false ``` `true` when the object has valid properties and the properties all have the correct JavaScript types: ```js isAccessor({get: noop, set: noop}) isAccessor({get: noop}) isAccessor({set: noop}) //=> true ``` `false` when the object has invalid properties ```js isAccessor({get: noop, set: noop, bar: 'baz'}) isAccessor({get: noop, writable: true}) isAccessor({get: noop, value: true}) //=> false ``` `false` when an accessor is not a function ```js isAccessor({get: noop, set: 'baz'}) isAccessor({get: 'foo', set: noop}) isAccessor({get: 'foo', bar: 'baz'}) isAccessor({get: 'foo', set: 'baz'}) //=> false ``` `false` when a value is not the correct type ```js isAccessor({get: noop, set: noop, enumerable: 'foo'}) isAccessor({set: noop, configurable: 'foo'}) isAccessor({get: noop, configurable: 'foo'}) //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 22 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # regenerator-transform Transform async/generator functions with [regenerator](https://github.com/facebook/regenerator) ## Installation ```sh $ npm install regenerator-transform ``` ## Usage ### Via `.babelrc` (Recommended) **.babelrc** ```js // without options { "plugins": ["regenerator-transform"] } // with options { "plugins": [ ["regenerator-transform", { asyncGenerators: false, // true by default generators: false, // true by default async: false // true by default }] ] } ``` ### Via CLI ```sh $ babel --plugins regenerator-transform script.js ``` ### Via Node API ```javascript require("@babel/core").transformSync("code", { plugins: ["regenerator-transform"] }); ``` # yallist Yet Another Linked List There are many doubly-linked list implementations like it, but this one is mine. For when an array would be too big, and a Map can't be iterated in reverse order. [![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) ## basic usage ```javascript var yallist = require('yallist') var myList = yallist.create([1, 2, 3]) myList.push('foo') myList.unshift('bar') // of course pop() and shift() are there, too console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] myList.forEach(function (k) { // walk the list head to tail }) myList.forEachReverse(function (k, index, list) { // walk the list tail to head }) var myDoubledList = myList.map(function (k) { return k + k }) // now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] // mapReverse is also a thing var myDoubledListReverse = myList.mapReverse(function (k) { return k + k }) // ['foofoo', 6, 4, 2, 'barbar'] var reduced = myList.reduce(function (set, entry) { set += entry return set }, 'start') console.log(reduced) // 'startfoo123bar' ``` ## api The whole API is considered "public". Functions with the same name as an Array method work more or less the same way. There's reverse versions of most things because that's the point. ### Yallist Default export, the class that holds and manages a list. Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list. The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots. ### Yallist.create(..) Alias for Yallist function. Some people like factories. #### yallist.head The first node in the list #### yallist.tail The last node in the list #### yallist.length The number of nodes in the list. (Change this at your peril. It is not magic like Array length.) #### yallist.toArray() Convert the list to an array. #### yallist.forEach(fn, [thisp]) Call a function on each item in the list. #### yallist.forEachReverse(fn, [thisp]) Call a function on each item in the list, in reverse order. #### yallist.get(n) Get the data at position `n` in the list. If you use this a lot, probably better off just using an Array. #### yallist.getReverse(n) Get the data at position `n`, counting from the tail. #### yallist.map(fn, thisp) Create a new Yallist with the result of calling the function on each item. #### yallist.mapReverse(fn, thisp) Same as `map`, but in reverse. #### yallist.pop() Get the data from the list tail, and remove the tail from the list. #### yallist.push(item, ...) Insert one or more items to the tail of the list. #### yallist.reduce(fn, initialValue) Like Array.reduce. #### yallist.reduceReverse Like Array.reduce, but in reverse. #### yallist.reverse Reverse the list in place. #### yallist.shift() Get the data from the list head, and remove the head from the list. #### yallist.slice([from], [to]) Just like Array.slice, but returns a new Yallist. #### yallist.sliceReverse([from], [to]) Just like yallist.slice, but the result is returned in reverse. #### yallist.toArray() Create an array representation of the list. #### yallist.toArrayReverse() Create a reversed array representation of the list. #### yallist.unshift(item, ...) Insert one or more items to the head of the list. #### yallist.unshiftNode(node) Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.) If the node belongs to a different list, then that list will remove it first. #### yallist.pushNode(node) Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.) If the node belongs to a list already, then that list will remove it first. #### yallist.removeNode(node) Remove a node from the list, preserving referential integrity of head and tail and other nodes. Will throw an error if you try to have a list remove a node that doesn't belong to it. ### Yallist.Node The class that holds the data and is actually the list. Call with `var n = new Node(value, previousNode, nextNode)` Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :) #### node.next The next node in the list. #### node.prev The previous node in the list. #### node.value The data the node contains. #### node.list The list to which this node belongs. (Null if it does not belong to any list.) # JavaScript Sync/Async forEach An optionally-asynchronous forEach with an interesting interface. ## Getting Started This code should work just fine in Node.js: First, install the module with: `npm install async-foreach` ```javascript var forEach = require('async-foreach').forEach; forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); }); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] ``` Or in the browser: ```html <script src="dist/ba-foreach.min.js"></script> <script> forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); }); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] </script> ``` In the browser, you can attach the forEach method to any object. ```html <script> this.exports = Bocoup.utils; </script> <script src="dist/ba-foreach.min.js"></script> <script> Bocoup.utils.forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); }); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] </script> ``` ## The General Idea (Why I thought this was worth sharing) The idea is to allow the callback to decide _at runtime_ whether the loop will be synchronous or asynchronous. By using `this` in a creative way (in situations where that value isn't already spoken for), an entire control API can be offered without over-complicating function signatures. ```javascript forEach(arr, function(item, index) { // Synchronous. }); forEach(arr, function(item, index) { // Only when `this.async` is called does iteration becomes asynchronous. The // loop won't be continued until the `done` function is executed. var done = this.async(); // Continue in one second. setTimeout(done, 1000); }); forEach(arr, function(item, index) { // Break out of synchronous iteration early by returning false. return index !== 1; }); forEach(arr, function(item, index) { // Break out of asynchronous iteration early... var done = this.async(); // ...by passing false to the done function. setTimeout(function() { done(index !== 1); }); }); ``` ## Examples See the unit tests for more examples. ```javascript // Generic "done" callback. function allDone(notAborted, arr) { console.log("done", notAborted, arr); } // Synchronous. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] // done true ["a", "b", "c"] // Synchronous with early abort. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); if (item === "b") { return false; } }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // done false ["a", "b", "c"] // Asynchronous. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); var done = this.async(); setTimeout(function() { done(); }, 500); }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] // done true ["a", "b", "c"] // Asynchronous with early abort. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); var done = this.async(); setTimeout(function() { done(item !== "b"); }, 500); }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // done false ["a", "b", "c"] // Not actually asynchronous. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); var done = this.async() done(); }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // each c 2 ["a", "b", "c"] // done true ["a", "b", "c"] // Not actually asynchronous with early abort. forEach(["a", "b", "c"], function(item, index, arr) { console.log("each", item, index, arr); var done = this.async(); done(item !== "b"); }, allDone); // logs: // each a 0 ["a", "b", "c"] // each b 1 ["a", "b", "c"] // done false ["a", "b", "c"] ``` ## Contributing In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/cowboy/grunt). _Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_ ## Release History 04/29/2013 v0.1.3 Removed hard Node.js version dependency. 11/17/2011 v0.1.2 Adding sparse array support. Invalid length properties are now sanitized. This closes issue #1 (like a boss). 11/11/2011 v0.1.1 Refactored code to be much simpler. Yay for unit tests! 11/11/2011 v0.1.0 Initial Release. ## License Copyright (c) 2012 "Cowboy" Ben Alman Licensed under the MIT license. <http://benalman.com/about/license/> # console-browserify [![build status][1]][2] [![browser support][3]][4] Emulate console for all the browsers ## Example ```js var console = require("console-browserify") console.log("hello world!") ``` ## Installation `npm install console-browserify` ## Contributors - Raynos ## MIT Licenced [1]: https://secure.travis-ci.org/Raynos/console-browserify.png [2]: http://travis-ci.org/Raynos/console-browserify [3]: http://ci.testling.com/Raynos/console-browserify.png [4]: http://ci.testling.com/Raynos/console-browserify # HAR Validator [![License][license-image]][license-url] [![version][npm-image]][npm-url] [![Build Status][circle-image]][circle-url] > Extremely fast HTTP Archive ([HAR](https://github.com/ahmadnassri/har-spec/blob/master/versions/1.2.md)) validator using JSON Schema. ## Install ```bash npm install har-validator ``` ## CLI Usage Please refer to [`har-cli`](https://github.com/ahmadnassri/har-cli) for more info. ## API **Note**: as of [`v2.0.0`](https://github.com/ahmadnassri/node-har-validator/releases/tag/v2.0.0) this module defaults to Promise based API. _For backward compatibility with `v1.x` an [async/callback API](docs/async.md) is also provided_ - [async API](docs/async.md) - [callback API](docs/async.md) - [Promise API](docs/promise.md) _(default)_ --- > Author: [Ahmad Nassri](https://www.ahmadnassri.com/) &bull; > Github: [@ahmadnassri](https://github.com/ahmadnassri) &bull; > Twitter: [@ahmadnassri](https://twitter.com/ahmadnassri) [license-url]: LICENSE [license-image]: https://img.shields.io/github/license/ahmadnassri/node-har-validator.svg?style=for-the-badge&logo=circleci [circle-url]: https://circleci.com/gh/ahmadnassri/workflows/node-har-validator [circle-image]: https://img.shields.io/circleci/project/github/ahmadnassri/node-har-validator/master.svg?style=for-the-badge&logo=circleci [npm-url]: https://www.npmjs.com/package/har-validator [npm-image]: https://img.shields.io/npm/v/har-validator.svg?style=for-the-badge&logo=npm This folder contains entry points for all `core-js` features with dependencies. It's the recommended way for usage only required features. browserify-cipher === [![Build Status](https://travis-ci.org/crypto-browserify/browserify-cipher.svg)](https://travis-ci.org/crypto-browserify/browserify-cipher) Provides createCipher, createDecipher, createCipheriv, createDecipheriv and getCiphers for the browserify. Includes AES and DES ciphers. # define-property [![NPM version](https://img.shields.io/npm/v/define-property.svg?style=flat)](https://www.npmjs.com/package/define-property) [![NPM monthly downloads](https://img.shields.io/npm/dm/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![NPM total downloads](https://img.shields.io/npm/dt/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/define-property.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save define-property ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add define-property ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 20, 2017._ # ASN1.js ASN.1 DER Encoder/Decoder and DSL. ## Example Define model: ```javascript var asn = require('asn1.js'); var Human = asn.define('Human', function() { this.seq().obj( this.key('firstName').octstr(), this.key('lastName').octstr(), this.key('age').int(), this.key('gender').enum({ 0: 'male', 1: 'female' }), this.key('bio').seqof(Bio) ); }); var Bio = asn.define('Bio', function() { this.seq().obj( this.key('time').gentime(), this.key('description').octstr() ); }); ``` Encode data: ```javascript var output = Human.encode({ firstName: 'Thomas', lastName: 'Anderson', age: 28, gender: 'male', bio: [ { time: +new Date('31 March 1999'), description: 'freedom of mind' } ] }, 'der'); ``` Decode data: ```javascript var human = Human.decode(output, 'der'); console.log(human); /* { firstName: <Buffer 54 68 6f 6d 61 73>, lastName: <Buffer 41 6e 64 65 72 73 6f 6e>, age: 28, gender: 'male', bio: [ { time: 922820400000, description: <Buffer 66 72 65 65 64 6f 6d 20 6f 66 20 6d 69 6e 64> } ] } */ ``` ### Partial decode Its possible to parse data without stopping on first error. In order to do it, you should call: ```javascript var human = Human.decode(output, 'der', { partial: true }); console.log(human); /* { result: { ... }, errors: [ ... ] } */ ``` #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2013. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # arr-diff [![NPM version](https://img.shields.io/npm/v/arr-diff.svg?style=flat)](https://www.npmjs.com/package/arr-diff) [![NPM monthly downloads](https://img.shields.io/npm/dm/arr-diff.svg?style=flat)](https://npmjs.org/package/arr-diff) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/arr-diff.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/arr-diff) > Returns an array with only the unique values from the first array, by excluding all values from additional arrays using strict equality for comparisons. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save arr-diff ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add arr-diff ``` Install with [bower](https://bower.io/) ```sh $ bower install arr-diff --save ``` ## Usage Returns the difference between the first array and additional arrays. ```js var diff = require('arr-diff'); var a = ['a', 'b', 'c', 'd']; var b = ['b', 'c']; console.log(diff(a, b)) //=> ['a', 'd'] ``` ## Benchmarks This library versus [array-differ](https://github.com/sindresorhus/array-differ), on April 14, 2017: ``` Benchmarking: (4 of 4) · long-dupes · long · med · short # benchmark/fixtures/long-dupes.js (100804 bytes) arr-diff-3.0.0 x 822 ops/sec ±0.67% (86 runs sampled) arr-diff-4.0.0 x 2,141 ops/sec ±0.42% (89 runs sampled) array-differ x 708 ops/sec ±0.70% (89 runs sampled) fastest is arr-diff-4.0.0 # benchmark/fixtures/long.js (94529 bytes) arr-diff-3.0.0 x 882 ops/sec ±0.60% (87 runs sampled) arr-diff-4.0.0 x 2,329 ops/sec ±0.97% (83 runs sampled) array-differ x 769 ops/sec ±0.61% (90 runs sampled) fastest is arr-diff-4.0.0 # benchmark/fixtures/med.js (708 bytes) arr-diff-3.0.0 x 856,150 ops/sec ±0.42% (89 runs sampled) arr-diff-4.0.0 x 4,665,249 ops/sec ±1.06% (89 runs sampled) array-differ x 653,888 ops/sec ±1.02% (86 runs sampled) fastest is arr-diff-4.0.0 # benchmark/fixtures/short.js (60 bytes) arr-diff-3.0.0 x 3,078,467 ops/sec ±0.77% (93 runs sampled) arr-diff-4.0.0 x 9,213,296 ops/sec ±0.65% (89 runs sampled) array-differ x 1,337,051 ops/sec ±0.91% (92 runs sampled) fastest is arr-diff-4.0.0 ``` ## About ### Related projects * [arr-flatten](https://www.npmjs.com/package/arr-flatten): Recursively flatten an array or arrays. This is the fastest implementation of array flatten. | [homepage](https://github.com/jonschlinkert/arr-flatten "Recursively flatten an array or arrays. This is the fastest implementation of array flatten.") * [array-filter](https://www.npmjs.com/package/array-filter): Array#filter for older browsers. | [homepage](https://github.com/juliangruber/array-filter "Array#filter for older browsers.") * [array-intersection](https://www.npmjs.com/package/array-intersection): Return an array with the unique values present in _all_ given arrays using strict equality… [more](https://github.com/jonschlinkert/array-intersection) | [homepage](https://github.com/jonschlinkert/array-intersection "Return an array with the unique values present in _all_ given arrays using strict equality for comparisons.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 33 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [paulmillr](https://github.com/paulmillr) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 14, 2017._ # from2 [![Flattr this!](https://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/submit/auto?user_id=hughskennedy&url=http://github.com/hughsk/from2&title=from2&description=hughsk/from2%20on%20GitHub&language=en_GB&tags=flattr,github,javascript&category=software)[![experimental](http://hughsk.github.io/stability-badges/dist/experimental.svg)](http://github.com/hughsk/stability-badges) # `from2` is a high-level module for creating readable streams that properly handle backpressure. Convience wrapper for [readable-stream](http://github.com/isaacs/readable-stream)'s `ReadableStream` base class, with an API lifted from [from](http://github.com/dominictarr/from) and [through2](http://github.com/rvagg/through2). ## Usage ## [![from2](https://nodei.co/npm/from2.png?mini=true)](https://nodei.co/npm/from2) ### `stream = from2([opts], read)` ### Where `opts` are the options to pass on to the `ReadableStream` constructor, and `read(size, next)` is called when data is requested from the stream. * `size` is the recommended amount of data (in bytes) to retrieve. * `next(err)` should be called when you're ready to emit more data. For example, here's a readable stream that emits the contents of a given string: ``` javascript var from = require('from2') function fromString(string) { return from(function(size, next) { // if there's no more content // left in the string, close the stream. if (string.length <= 0) return next(null, null) // Pull in a new chunk of text, // removing it from the string. var chunk = string.slice(0, size) string = string.slice(size) // Emit "chunk" from the stream. next(null, chunk) }) } // pipe "hello world" out // to stdout. fromString('hello world').pipe(process.stdout) ``` ### `stream = from2.obj([opts], read)` ### Shorthand for `from2({ objectMode: true }, read)`. ### `createStream = from2.ctor([opts], read)` ### If you're creating similar streams in quick succession you can improve performance by generating a stream **constructor** that you can reuse instead of creating one-off streams on each call. Takes the same options as `from2`, instead returning a constructor which you can use to create new streams. ### See Also - [from2-array](https://github.com/binocarlos/from2-array) - Create a from2 stream based on an array of source values. - [from2-string](https://github.com/yoshuawuyts/from2-string) - Create a stream from a string. Sugary wrapper around from2. ## License ## MIT. See [LICENSE.md](http://github.com/hughsk/from2/blob/master/LICENSE.md) for details. # loader-runner ``` js import { runLoaders } from "loader-runner"; runLoaders({ resource: "/abs/path/to/file.txt?query", // String: Absolute path to the resource (optionally including query string) loaders: ["/abs/path/to/loader.js?query"], // String[]: Absolute paths to the loaders (optionally including query string) // {loader, options}[]: Absolute paths to the loaders with options object context: { minimize: true }, // Additional loader context which is used as base context readResource: fs.readFile.bind(fs) // A function to read the resource // Must have signature function(path, function(err, buffer)) }, function(err, result) { // err: Error? // result.result: Buffer | String // The result // result.resourceBuffer: Buffer // The raw resource as Buffer (useful for SourceMaps) // result.cacheable: Bool // Is the result cacheable or do it require reexecution? // result.fileDependencies: String[] // An array of paths (files) on which the result depends on // result.contextDependencies: String[] // An array of paths (directories) on which the result depends on }) ``` More documentation following... # browserify-zlib [![Travis CI](https://travis-ci.org/devongovett/browserify-zlib.svg?branch=master)](https://travis-ci.org/devongovett/browserify-zlib) [![Dependency Status](https://david-dm.org/devongovett/browserify-zlib.svg?style=flat-square)](https://david-dm.org/devongovett/browserify-zlib) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](https://github.com/feross/standard) ## Description Emulates Node's [zlib](https://nodejs.org/api/zlib.html) module for the browser. Can be used as a drop in replacement with [Browserify](http://browserify.org) and [webpack](http://webpack.github.io/). The heavy lifting is done using [pako](https://github.com/nodeca/pako). The code in this module is modeled closely after the code in the source of Node core to get as much compatability as possible. ## API https://nodejs.org/api/zlib.html ## Not implemented The following options/methods are not supported because pako does not support them yet. * The `params` method ## License MIT #object-keys <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] [![browser support][testling-svg]][testling-url] An Object.keys shim. Invoke its "shim" method to shim Object.keys if it is unavailable. Most common usage: ```js var keys = Object.keys || require('object-keys'); ``` ## Example ```js var keys = require('object-keys'); var assert = require('assert'); var obj = { a: true, b: true, c: true }; assert.deepEqual(keys(obj), ['a', 'b', 'c']); ``` ```js var keys = require('object-keys'); var assert = require('assert'); /* when Object.keys is not present */ delete Object.keys; var shimmedKeys = keys.shim(); assert.equal(shimmedKeys, keys); assert.deepEqual(Object.keys(obj), keys(obj)); ``` ```js var keys = require('object-keys'); var assert = require('assert'); /* when Object.keys is present */ var shimmedKeys = keys.shim(); assert.equal(shimmedKeys, Object.keys); assert.deepEqual(Object.keys(obj), keys(obj)); ``` ## Source Implementation taken directly from [es5-shim][es5-shim-url], with modifications, including from [lodash][lodash-url]. ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/object-keys [npm-version-svg]: http://versionbadg.es/ljharb/object-keys.svg [travis-svg]: https://travis-ci.org/ljharb/object-keys.svg [travis-url]: https://travis-ci.org/ljharb/object-keys [deps-svg]: https://david-dm.org/ljharb/object-keys.svg [deps-url]: https://david-dm.org/ljharb/object-keys [dev-deps-svg]: https://david-dm.org/ljharb/object-keys/dev-status.svg [dev-deps-url]: https://david-dm.org/ljharb/object-keys#info=devDependencies [testling-svg]: https://ci.testling.com/ljharb/object-keys.png [testling-url]: https://ci.testling.com/ljharb/object-keys [es5-shim-url]: https://github.com/es-shims/es5-shim/blob/master/es5-shim.js#L542-589 [lodash-url]: https://github.com/lodash/lodash [npm-badge-png]: https://nodei.co/npm/object-keys.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/object-keys.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/object-keys.svg [downloads-url]: http://npm-stat.com/charts.html?package=object-keys # copy-concurrently Copy files, directories and symlinks ``` const copy = require('copy-concurrently') copy('/path/to/thing', '/new/path/thing').then(() => { // this is now copied }).catch(err => { // oh noooo }) ``` Copies files, directories and symlinks. Ownership is maintained when running as root, permissions are always maintained. On Windows, if symlinks are unavailable then junctions will be used. ## PUBLIC INTERFACE ### copy(from, to, [options]) → Promise Recursively copies `from` to `to` and resolves its promise when finished. If `to` already exists then the promise will be rejected with an `EEXIST` error. Options are: * maxConcurrency – (Default: `1`) The maximum number of concurrent copies to do at once. * recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory. * isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory fails then we'll try making a junction instead. Options can also include dependency injection: * Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * writeStreamAtomic - (Default: `require('fs-write-stream-atomic')`) The implementation of `writeStreamAtomic` to use. Used to inject a mock. * getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock. ## EXTENSION INTERFACE Ordinarily you'd only call `copy` above. But it's possible to use it's component functions directly. This is useful if, say, you're writing [move-concurently](https://npmjs.com/package/move-concurrently). ### copy.file(from, to, options) → Promise Copies an ordinary file `from` to destination `to`. Uses `fs-write-stream-atomic` to ensure that the file is either entirely copied or not at all. Options are: * uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to set the user and group of `to`. If uid is present then gid must be too. * mode - (Optional) If set then `to` will have its perms set to `mode`. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's. * writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The implementation of `writeStreamAtomic` to use. Used to inject a mock. ### copy.symlink(from, to, options) → Promise Copies a symlink `from` to destination `to`. If you're using Windows and symlinking fails and what you're linking is a directory then junctions will be tried instead. Options are: * top - The top level the copy is being run from. This is used to determine if the symlink destination is within the set of files we're copying or outside it. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's. * isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory fails then we'll try making a junction instead. ### copy.recurse(from, to, options) → Promise Reads all of the files in directory `from` and adds them to the `queue` using `recurseWith` (by default `copy.item`). Options are: * queue - A [`run-queue`](https://npmjs.com/package/run-queue) object to add files found inside `from` to. * recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory. * uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to set the user and group of `to`. If uid is present then gid must be too. * mode - (Optional) If set then `to` will have its perms set to `mode`. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock. ### copy.item(from, to, options) → Promise Copies some kind of `from` to destination `to`. This looks at the filetype and calls `copy.file`, `copy.symlink` or `copy.recurse` as appropriate. Symlink copies are queued with a priority such that they happen after all file and directory copies as you can't create a junction on windows to a file that doesn't exist yet. Options are: * top - The top level the copy is being run from. This is used to determine if the symlink destination is within the set of files we're copying or outside it. * queue - The [`run-queue`](https://npmjs.com/package/run-queue) object to pass to `copy.recurse` if `from` is a directory. * recurseWith - (Default: `copy.item`) The function to call on each file after recursing into a directory. * uid, gid - (Optional) If `getuid()` is `0` then this and gid will be used to set the user and group of `to`. If uid is present then gid must be too. * mode - (Optional) If set then `to` will have its perms set to `mode`. * fs - (Default: `require('fs')`) The filesystem module to use. Can be used to use `graceful-fs` or to inject a mock. * getuid - (Default: `process.getuid`) A function that returns the current UID. Used to inject a mock. * isWindows - (Default: `process.platform === 'win32'`) If true enables Windows symlink semantics. This requires an extra `stat` to determine if the destination of a symlink is a file or directory. If symlinking a directory fails then we'll try making a junction instead. * Promise - (Default: `global.Promise`) The promise implementation to use, defaults to Node's. * writeStreamAtomic - (Default `require('fs-write-stream-atomic')`) The implementation of `writeStreamAtomic` to use. Used to inject a mock. # define-property [![NPM version](https://img.shields.io/npm/v/define-property.svg?style=flat)](https://www.npmjs.com/package/define-property) [![NPM monthly downloads](https://img.shields.io/npm/dm/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![NPM total downloads](https://img.shields.io/npm/dt/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/define-property.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save define-property ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add define-property ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 20, 2017._ <!-- TITLE/ --> <h1>domain-browser</h1> <!-- /TITLE --> <!-- BADGES/ --> <span class="badge-travisci"><a href="http://travis-ci.org/bevry/domain-browser" title="Check this project's build status on TravisCI"><img src="https://img.shields.io/travis/bevry/domain-browser/master.svg" alt="Travis CI Build Status" /></a></span> <span class="badge-npmversion"><a href="https://npmjs.org/package/domain-browser" title="View this project on NPM"><img src="https://img.shields.io/npm/v/domain-browser.svg" alt="NPM version" /></a></span> <span class="badge-npmdownloads"><a href="https://npmjs.org/package/domain-browser" title="View this project on NPM"><img src="https://img.shields.io/npm/dm/domain-browser.svg" alt="NPM downloads" /></a></span> <span class="badge-daviddm"><a href="https://david-dm.org/bevry/domain-browser" title="View the status of this project's dependencies on DavidDM"><img src="https://img.shields.io/david/bevry/domain-browser.svg" alt="Dependency Status" /></a></span> <span class="badge-daviddmdev"><a href="https://david-dm.org/bevry/domain-browser#info=devDependencies" title="View the status of this project's development dependencies on DavidDM"><img src="https://img.shields.io/david/dev/bevry/domain-browser.svg" alt="Dev Dependency Status" /></a></span> <br class="badge-separator" /> <span class="badge-patreon"><a href="https://patreon.com/bevry" title="Donate to this project using Patreon"><img src="https://img.shields.io/badge/patreon-donate-yellow.svg" alt="Patreon donate button" /></a></span> <span class="badge-opencollective"><a href="https://opencollective.com/bevry" title="Donate to this project using Open Collective"><img src="https://img.shields.io/badge/open%20collective-donate-yellow.svg" alt="Open Collective donate button" /></a></span> <span class="badge-gratipay"><a href="https://www.gratipay.com/bevry" title="Donate weekly to this project using Gratipay"><img src="https://img.shields.io/badge/gratipay-donate-yellow.svg" alt="Gratipay donate button" /></a></span> <span class="badge-flattr"><a href="https://flattr.com/profile/balupton" title="Donate to this project using Flattr"><img src="https://img.shields.io/badge/flattr-donate-yellow.svg" alt="Flattr donate button" /></a></span> <span class="badge-paypal"><a href="https://bevry.me/paypal" title="Donate to this project using Paypal"><img src="https://img.shields.io/badge/paypal-donate-yellow.svg" alt="PayPal donate button" /></a></span> <span class="badge-bitcoin"><a href="https://bevry.me/bitcoin" title="Donate once-off to this project using Bitcoin"><img src="https://img.shields.io/badge/bitcoin-donate-yellow.svg" alt="Bitcoin donate button" /></a></span> <span class="badge-wishlist"><a href="https://bevry.me/wishlist" title="Buy an item on our wishlist for us"><img src="https://img.shields.io/badge/wishlist-donate-yellow.svg" alt="Wishlist browse button" /></a></span> <br class="badge-separator" /> <span class="badge-slackin"><a href="https://slack.bevry.me" title="Join this project's slack community"><img src="https://slack.bevry.me/badge.svg" alt="Slack community badge" /></a></span> <!-- /BADGES --> <!-- DESCRIPTION/ --> Node's domain module for the web browser. This is merely an evented try...catch with the same API as node, nothing more. <!-- /DESCRIPTION --> <!-- INSTALL/ --> <h2>Install</h2> <a href="https://npmjs.com" title="npm is a package manager for javascript"><h3>NPM</h3></a><ul> <li>Install: <code>npm install --save domain-browser</code></li> <li>Module: <code>require('domain-browser')</code></li></ul> <a href="http://browserify.org" title="Browserify lets you require('modules') in the browser by bundling up all of your dependencies"><h3>Browserify</h3></a><ul> <li>Install: <code>npm install --save domain-browser</code></li> <li>Module: <code>require('domain-browser')</code></li> <li>CDN URL: <code>//wzrd.in/bundle/[email protected]</code></li></ul> <a href="http://enderjs.com" title="Ender is a full featured package manager for your browser"><h3>Ender</h3></a><ul> <li>Install: <code>ender add domain-browser</code></li> <li>Module: <code>require('domain-browser')</code></li></ul> <h3><a href="https://github.com/bevry/editions" title="Editions are the best way to produce and consume packages you care about.">Editions</a></h3> <p>This package is published with the following editions:</p> <ul><li><code>domain-browser</code> aliases <code>domain-browser/source/index.js</code></li> <li><code>domain-browser/source/index.js</code> is Source + ES5 + <a href="https://nodejs.org/dist/latest-v5.x/docs/api/modules.html" title="Node/CJS Modules">Require</a></li></ul> <!-- /INSTALL --> <!-- HISTORY/ --> <h2>History</h2> <a href="https://github.com/bevry/domain-browser/blob/master/HISTORY.md#files">Discover the release history by heading on over to the <code>HISTORY.md</code> file.</a> <!-- /HISTORY --> <!-- BACKERS/ --> <h2>Backers</h2> <h3>Maintainers</h3> These amazing people are maintaining this project: <ul><li><a href="http://balupton.com">Benjamin Lupton</a> — <a href="https://github.com/bevry/domain-browser/commits?author=balupton" title="View the GitHub contributions of Benjamin Lupton on repository bevry/domain-browser">view contributions</a></li></ul> <h3>Sponsors</h3> No sponsors yet! Will you be the first? <span class="badge-patreon"><a href="https://patreon.com/bevry" title="Donate to this project using Patreon"><img src="https://img.shields.io/badge/patreon-donate-yellow.svg" alt="Patreon donate button" /></a></span> <span class="badge-opencollective"><a href="https://opencollective.com/bevry" title="Donate to this project using Open Collective"><img src="https://img.shields.io/badge/open%20collective-donate-yellow.svg" alt="Open Collective donate button" /></a></span> <span class="badge-gratipay"><a href="https://www.gratipay.com/bevry" title="Donate weekly to this project using Gratipay"><img src="https://img.shields.io/badge/gratipay-donate-yellow.svg" alt="Gratipay donate button" /></a></span> <span class="badge-flattr"><a href="https://flattr.com/profile/balupton" title="Donate to this project using Flattr"><img src="https://img.shields.io/badge/flattr-donate-yellow.svg" alt="Flattr donate button" /></a></span> <span class="badge-paypal"><a href="https://bevry.me/paypal" title="Donate to this project using Paypal"><img src="https://img.shields.io/badge/paypal-donate-yellow.svg" alt="PayPal donate button" /></a></span> <span class="badge-bitcoin"><a href="https://bevry.me/bitcoin" title="Donate once-off to this project using Bitcoin"><img src="https://img.shields.io/badge/bitcoin-donate-yellow.svg" alt="Bitcoin donate button" /></a></span> <span class="badge-wishlist"><a href="https://bevry.me/wishlist" title="Buy an item on our wishlist for us"><img src="https://img.shields.io/badge/wishlist-donate-yellow.svg" alt="Wishlist browse button" /></a></span> <h3>Contributors</h3> These amazing people have contributed code to this project: <ul><li><a href="http://balupton.com">Benjamin Lupton</a> — <a href="https://github.com/bevry/domain-browser/commits?author=balupton" title="View the GitHub contributions of Benjamin Lupton on repository bevry/domain-browser">view contributions</a></li> <li><a href="http://evansolomon.me">Evan Solomon</a> — <a href="https://github.com/bevry/domain-browser/commits?author=evansolomon" title="View the GitHub contributions of Evan Solomon on repository bevry/domain-browser">view contributions</a></li> <li><a href="http://substack.neocities.org/">James Halliday</a> — <a href="https://github.com/bevry/domain-browser/commits?author=substack" title="View the GitHub contributions of James Halliday on repository bevry/domain-browser">view contributions</a></li> <li><a href="twitter.com/guybedford">Guy Bedford</a> — <a href="https://github.com/bevry/domain-browser/commits?author=guybedford" title="View the GitHub contributions of Guy Bedford on repository bevry/domain-browser">view contributions</a></li> <li><a href="https://github.com/TrySound">Bogdan Chadkin</a> — <a href="https://github.com/bevry/domain-browser/commits?author=TrySound" title="View the GitHub contributions of Bogdan Chadkin on repository bevry/domain-browser">view contributions</a></li></ul> <a href="https://github.com/bevry/domain-browser/blob/master/CONTRIBUTING.md#files">Discover how you can contribute by heading on over to the <code>CONTRIBUTING.md</code> file.</a> <!-- /BACKERS --> <!-- LICENSE/ --> <h2>License</h2> Unless stated otherwise all works are: <ul><li>Copyright &copy; 2013+ <a href="http://bevry.me">Bevry Pty Ltd</a></li></ul> and licensed under: <ul><li><a href="http://spdx.org/licenses/MIT.html">MIT License</a></li></ul> <!-- /LICENSE --> # spdx-license-ids [![npm version](https://img.shields.io/npm/v/spdx-license-ids.svg)](https://www.npmjs.com/package/spdx-license-ids) [![Github Actions](https://action-badges.now.sh/shinnn/spdx-license-ids)](https://wdp9fww0r9.execute-api.us-west-2.amazonaws.com/production/results/shinnn/spdx-license-ids) A list of [SPDX license](https://spdx.org/licenses/) identifiers ## Installation [Download JSON directly](https://raw.githubusercontent.com/shinnn/spdx-license-ids/master/index.json), or [use](https://docs.npmjs.com/cli/install) [npm](https://docs.npmjs.com/about-npm/): ``` npm install spdx-license-ids ``` ## [Node.js](https://nodejs.org/) API ### require('spdx-license-ids') Type: `string[]` All license IDs except for the currently deprecated ones. ```javascript const ids = require('spdx-license-ids'); //=> ['0BSD', 'AAL', 'ADSL', 'AFL-1.1', 'AFL-1.2', 'AFL-2.0', 'AFL-2.1', 'AFL-3.0', 'AGPL-1.0-only', ...] ids.includes('BSD-3-Clause'); //=> true ids.includes('CC-BY-1.0'); //=> true ids.includes('GPL-3.0'); //=> false ``` ### require('spdx-license-ids/deprecated') Type: `string[]` Deprecated license IDs. ```javascript const deprecatedIds = require('spdx-license-ids/deprecated'); //=> ['AGPL-1.0', 'AGPL-3.0', 'GFDL-1.1', 'GFDL-1.2', 'GFDL-1.3', 'GPL-1.0', 'GPL-2.0', ...] deprecatedIds.includes('BSD-3-Clause'); //=> false deprecatedIds.includes('CC-BY-1.0'); //=> false deprecatedIds.includes('GPL-3.0'); //=> true ``` ## License [Creative Commons Zero v1.0 Universal](https://creativecommons.org/publicdomain/zero/1.0/deed) # to-arraybuffer [![Build Status](https://travis-ci.org/jhiesey/to-arraybuffer.svg?branch=master)](https://travis-ci.org/jhiesey/to-arraybuffer) [![Sauce Test Status](https://saucelabs.com/browser-matrix/to-arraybuffer.svg)](https://saucelabs.com/u/to-arraybuffer) Convert from a Buffer to an ArrayBuffer as fast as possible. Note that in some cases the returned ArrayBuffer is backed by the same memory as the original Buffer (but in other cases it is a copy), so **modifying the ArrayBuffer is not recommended**. This module is designed to work both in node.js and in all browsers with ArrayBuffer support when using [the Buffer implementation provided by Browserify](https://www.npmjs.com/package/buffer). ## Usage ``` js var toArrayBuffer = require('to-arraybuffer') var buffer = new Buffer(100) // Fill the buffer with some data var ab = toArrayBuffer(buffer) // `ab` now contains the same data as `buffer` ``` ## License MIT # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Why use this? 1. [it's fast](#benchmarks) | [optimizations](#optimizations) 2. [better type checking](#better-type-checking) ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Release history ### v4.0.0 **Added** * `promise` support ### v5.0.0 **Added** * `Set Iterator` and `Map Iterator` support **Fixed** * Now returns `generatorfunction` for generator functions ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` 4. There is no reason to make the code in a microlib as terse as possible, just to win points for making it shorter. It's always better to favor performant code over terse code. You will always only be using a single `require()` statement to use the library anyway, regardless of how the code is written. ## Better type checking kind-of is more correct than other type checking libs I've looked at. For example, here are some differing results from other popular libs: ### [typeof](https://github.com/CodingFu/typeof) lib Incorrectly tests instances of custom constructors (pretty common): ```js var typeOf = require('typeof'); function Test() {} console.log(typeOf(new Test())); //=> 'test' ``` Returns `object` instead of `arguments`: ```js function foo() { console.log(typeOf(arguments)) //=> 'object' } foo(); ``` ### [type-of](https://github.com/ForbesLindesay/type-of) lib Incorrectly returns `object` for generator functions, buffers, `Map`, `Set`, `WeakMap` and `WeakSet`: ```js function * foo() {} console.log(typeOf(foo)); //=> 'object' console.log(typeOf(new Buffer(''))); //=> 'object' console.log(typeOf(new Map())); //=> 'object' console.log(typeOf(new Set())); //=> 'object' console.log(typeOf(new WeakMap())); //=> 'object' console.log(typeOf(new WeakSet())); //=> 'object' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). <details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` <details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` <details> ### Related projects You might also be interested in these projects: * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 82 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [aretecode](https://github.com/aretecode) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | | 1 | [charlike](https://github.com/charlike) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 13, 2017._ # isobject [![NPM version](https://img.shields.io/npm/v/isobject.svg?style=flat)](https://www.npmjs.com/package/isobject) [![NPM monthly downloads](https://img.shields.io/npm/dm/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![NPM total downloads](https://img.shields.io/npm/dt/isobject.svg?style=flat)](https://npmjs.org/package/isobject) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/isobject.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/isobject) > Returns true if the value is an object and not an array or null. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save isobject ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add isobject ``` Use [is-plain-object](https://github.com/jonschlinkert/is-plain-object) if you want only objects that are created by the `Object` constructor. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install isobject ``` Install with [bower](https://bower.io/) ```sh $ bower install isobject ``` ## Usage ```js var isObject = require('isobject'); ``` **True** All of the following return `true`: ```js isObject({}); isObject(Object.create({})); isObject(Object.create(Object.prototype)); isObject(Object.create(null)); isObject({}); isObject(new Foo); isObject(/foo/); ``` **False** All of the following return `false`: ```js isObject(); isObject(function () {}); isObject(1); isObject([]); isObject(undefined); isObject(null); ``` ## About ### Related projects * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 29 | [jonschlinkert](https://github.com/jonschlinkert) | | 4 | [doowb](https://github.com/doowb) | | 1 | [magnudae](https://github.com/magnudae) | | 1 | [LeSuisse](https://github.com/LeSuisse) | | 1 | [tmcw](https://github.com/tmcw) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 30, 2017._ # cross-spawn [![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url] [npm-url]:https://npmjs.org/package/cross-spawn [downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg [npm-image]:http://img.shields.io/npm/v/cross-spawn.svg [travis-url]:https://travis-ci.org/IndigoUnited/node-cross-spawn [travis-image]:http://img.shields.io/travis/IndigoUnited/node-cross-spawn/master.svg [appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn [appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg [david-dm-url]:https://david-dm.org/IndigoUnited/node-cross-spawn [david-dm-image]:https://img.shields.io/david/IndigoUnited/node-cross-spawn.svg [david-dm-dev-url]:https://david-dm.org/IndigoUnited/node-cross-spawn#info=devDependencies [david-dm-dev-image]:https://img.shields.io/david/dev/IndigoUnited/node-cross-spawn.svg A cross platform solution to node's spawn and spawnSync. ## Installation `$ npm install cross-spawn` If you are using `spawnSync` on node 0.10 or older, you will also need to install `spawn-sync`: `$ npm install spawn-sync` ## Why Node has issues when using spawn on Windows: - It ignores [PATHEXT](https://github.com/joyent/node/issues/2318) - It does not support [shebangs](http://pt.wikipedia.org/wiki/Shebang) - It does not allow you to run `del` or `dir` - It does not properly escape arguments with spaces or special characters All these issues are handled correctly by `cross-spawn`. There are some known modules, such as [win-spawn](https://github.com/ForbesLindesay/win-spawn), that try to solve this but they are either broken or provide faulty escaping of shell arguments. ## Usage Exactly the same way as node's [`spawn`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) or [`spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options), so it's a drop in replacement. ```javascript var spawn = require('cross-spawn'); // Spawn NPM asynchronously var child = spawn('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); // Spawn NPM synchronously var results = spawn.sync('npm', ['list', '-g', '-depth', '0'], { stdio: 'inherit' }); ``` ## Tests `$ npm test` ## License Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). # signal-exit [![Build Status](https://travis-ci.org/tapjs/signal-exit.png)](https://travis-ci.org/tapjs/signal-exit) [![Coverage](https://coveralls.io/repos/tapjs/signal-exit/badge.svg?branch=master)](https://coveralls.io/r/tapjs/signal-exit?branch=master) [![NPM version](https://img.shields.io/npm/v/signal-exit.svg)](https://www.npmjs.com/package/signal-exit) [![Windows Tests](https://img.shields.io/appveyor/ci/bcoe/signal-exit/master.svg?label=Windows%20Tests)](https://ci.appveyor.com/project/bcoe/signal-exit) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) When you want to fire an event no matter how a process exits: * reaching the end of execution. * explicitly having `process.exit(code)` called. * having `process.kill(pid, sig)` called. * receiving a fatal signal from outside the process Use `signal-exit`. ```js var onExit = require('signal-exit') onExit(function (code, signal) { console.log('process exited!') }) ``` ## API `var remove = onExit(function (code, signal) {}, options)` The return value of the function is a function that will remove the handler. Note that the function *only* fires for signals if the signal would cause the proces to exit. That is, there are no other listeners, and it is a fatal signal. ## Options * `alwaysLast`: Run this handler after any other signal or exit handlers. This causes `process.emit` to be monkeypatched. # abbrev-js Just like [ruby's Abbrev](http://apidock.com/ruby/Abbrev). Usage: var abbrev = require("abbrev"); abbrev("foo", "fool", "folding", "flop"); // returns: { fl: 'flop' , flo: 'flop' , flop: 'flop' , fol: 'folding' , fold: 'folding' , foldi: 'folding' , foldin: 'folding' , folding: 'folding' , foo: 'foo' , fool: 'fool' } This is handy for command-line scripts, or other cases where you want to be able to accept shorthands. # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ # EVP\_BytesToKey [![NPM Package](https://img.shields.io/npm/v/evp_bytestokey.svg?style=flat-square)](https://www.npmjs.org/package/evp_bytestokey) [![Build Status](https://img.shields.io/travis/crypto-browserify/EVP_BytesToKey.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/EVP_BytesToKey) [![Dependency status](https://img.shields.io/david/crypto-browserify/EVP_BytesToKey.svg?style=flat-square)](https://david-dm.org/crypto-browserify/EVP_BytesToKey#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) The insecure [key derivation algorithm from OpenSSL.][1] **WARNING: DO NOT USE, except for compatibility reasons.** MD5 is insecure. Use at least `scrypt` or `pbkdf2-hmac-sha256` instead. ## API `EVP_BytesToKey(password, salt, keyLen, ivLen)` * `password` - `Buffer`, password used to derive the key data. * `salt` - 8 byte `Buffer` or `null`, salt is used as a salt in the derivation. * `keyBits` - `number`, key length in **bits**. * `ivLen` - `number`, iv length in bytes. *Returns*: `{ key: Buffer, iv: Buffer }` ## Examples MD5 with `aes-256-cbc`: ```js const crypto = require('crypto') const EVP_BytesToKey = require('evp_bytestokey') const result = EVP_BytesToKey( 'my-secret-password', null, 32, 16 ) // => // { key: <Buffer e3 4f 96 f3 86 24 82 7c c2 5d ff 23 18 6f 77 72 54 45 7f 49 d4 be 4b dd 4f 6e 1b cc 92 a4 27 33>, // iv: <Buffer 85 71 9a bf ae f4 1e 74 dd 46 b6 13 79 56 f5 5b> } const cipher = crypto.createCipheriv('aes-256-cbc', result.key, result.iv) ``` ## LICENSE [MIT](LICENSE) [1]: https://wiki.openssl.org/index.php/Manual:EVP_BytesToKey(3) [2]: https://nodejs.org/api/crypto.html#crypto_class_hash # node-is-arrayish [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-is-arrayish.svg?style=flat-square)](https://travis-ci.org/Qix-/node-is-arrayish) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-is-arrayish.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-is-arrayish) > Determines if an object can be used like an Array ## Example ```javascript var isArrayish = require('is-arrayish'); isArrayish([]); // true isArrayish({__proto__: []}); // true isArrayish({}); // false isArrayish({length:10}); // false ``` ## License Licensed under the [MIT License](http://opensource.org/licenses/MIT). You can find a copy of it in [LICENSE](LICENSE). # cliui [![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) [![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) [![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) [![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) easily create complex multi-column command-line-interfaces. ## Example ```js var ui = require('cliui')() ui.div('Usage: $0 [command] [options]') ui.div({ text: 'Options:', padding: [2, 0, 2, 0] }) ui.div( { text: "-f, --file", width: 20, padding: [0, 4, 0, 4] }, { text: "the file to load." + chalk.green("(if this description is long it wraps).") , width: 20 }, { text: chalk.red("[required]"), align: 'right' } ) console.log(ui.toString()) ``` <img width="500" src="screenshot.png"> ## Layout DSL cliui exposes a simple layout DSL: If you create a single `ui.row`, passing a string rather than an object: * `\n`: characters will be interpreted as new rows. * `\t`: characters will be interpreted as new columns. * `\s`: characters will be interpreted as padding. **as an example...** ```js var ui = require('./')({ width: 60 }) ui.div( 'Usage: node ./bin/foo.js\n' + ' <regex>\t provide a regex\n' + ' <glob>\t provide a glob\t [required]' ) console.log(ui.toString()) ``` **will output:** ```shell Usage: node ./bin/foo.js <regex> provide a regex <glob> provide a glob [required] ``` ## Methods ```js cliui = require('cliui') ``` ### cliui({width: integer}) Specify the maximum width of the UI being generated. If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. ### cliui({wrap: boolean}) Enable or disable the wrapping of text in a column. ### cliui.div(column, column, column) Create a row with any number of columns, a column can either be a string, or an object with the following options: * **text:** some text to place in the column. * **width:** the width of a column. * **align:** alignment, `right` or `center`. * **padding:** `[top, right, bottom, left]`. * **border:** should a border be placed around the div? ### cliui.span(column, column, column) Similar to `div`, except the next row will be appended without a new line being created. ### cliui.resetOutput() Resets the UI elements of the current cliui instance, maintaining the values set for `width` and `wrap`. # snapdragon [![NPM version](https://img.shields.io/npm/v/snapdragon.svg?style=flat)](https://www.npmjs.com/package/snapdragon) [![NPM downloads](https://img.shields.io/npm/dm/snapdragon.svg?style=flat)](https://npmjs.org/package/snapdragon) [![Build Status](https://img.shields.io/travis/jonschlinkert/snapdragon.svg?style=flat)](https://travis-ci.org/jonschlinkert/snapdragon) > Fast, pluggable and easy-to-use parser-renderer factory. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save snapdragon ``` Created by [jonschlinkert](https://github.com/jonschlinkert) and [doowb](https://github.com/doowb). **Features** * Bootstrap your own parser, get sourcemap support for free * All parsing and compiling is handled by simple, reusable middleware functions * Inspired by the parsers in [pug](http://jade-lang.com) and [css](https://github.com/reworkcss/css). ## History ### v0.5.0 **Breaking changes** Substantial breaking changes were made in v0.5.0! Most of these changes are part of a larger refactor that will be finished in 0.6.0, including the introduction of a `Lexer` class. * Renderer was renamed to `Compiler` * the `.render` method was renamed to `.compile` * Many other smaller changes. A more detailed overview will be provided in 0.6.0. If you don't have to time review code, I recommend you wait for the 0.6.0 release. ## Usage examples ```js var Snapdragon = require('snapdragon'); var snapdragon = new Snapdragon(); ``` **Parse** ```js var ast = snapdragon.parser('some string', options) // parser middleware that can be called by other middleware .set('foo', function () {}) // parser middleware, runs immediately in the order defined .use(bar()) .use(baz()) ``` **Render** ```js // pass the `ast` from the parse method var res = snapdragon.compiler(ast) // compiler middleware, called when the name of the middleware // matches the `node.type` (defined in a parser middleware) .set('bar', function () {}) .set('baz', function () {}) .compile() ``` See the [examples](./examples/). ## Getting started **Parsers** Parsers are middleware functions used for parsing a string into an ast node. ```js var ast = snapdragon.parser(str, options) .use(function() { var pos = this.position(); var m = this.match(/^\./); if (!m) return; return pos({ // `type` specifies the compiler to use type: 'dot', val: m[0] }); }) ``` **AST node** When the parser finds a match, `pos()` is called, pushing a token for that node onto the ast that looks something like: ```js { type: 'dot', val: '.', position: { start: { lineno: 1, column: 1 }, end: { lineno: 1, column: 2 } }} ``` **Renderers** Renderers are _named_ middleware functions that visit over an array of ast nodes to compile a string. ```js var res = snapdragon.compiler(ast) .set('dot', function (node) { console.log(node.val) //=> '.' return this.emit(node.val); }) ``` **Source maps** If you want source map support, make sure to emit the position as well. ```js var res = snapdragon.compiler(ast) .set('dot', function (node) { return this.emit(node.val, node.position); }) ``` ## Docs ### Parser middleware A parser middleware is a function that returns an abject called a `token`. This token is pushed onto the AST as a node. **Example token** ```js { type: 'dot', val: '.', position: { start: { lineno: 1, column: 1 }, end: { lineno: 1, column: 2 } }} ``` **Example parser middleware** Match a single `.` in a string: 1. Get the starting position by calling `this.position()` 2. pass a regex for matching a single dot to the `.match` method 3. if **no match** is found, return `undefined` 4. if a **match** is found, `pos()` is called, which returns a token with: - `type`: the name of the [compiler] to use - `val`: The actual value captured by the regex. In this case, a `.`. Note that you can capture and return whatever will be needed by the corresponding [compiler]. - The ending position: automatically calculated by adding the length of the first capture group to the starting position. ## Renderer middleware Renderers are run when the name of the compiler middleware matches the `type` defined on an ast `node` (which is defined in a parser). **Example** Exercise: Parse a dot, then compile it as an escaped dot. ```js var ast = snapdragon.parser('.') .use(function () { var pos = this.position(); var m = this.match(/^\./); if (!m) return; return pos({ // define the `type` of compiler to use type: 'dot', val: m[0] }) }) var result = snapdragon.compiler(ast) .set('dot', function (node) { return this.emit('\\' + node.val); }) .compile() console.log(result.output); //=> '\.' ``` ## API ### [Parser](lib/parser.js#L19) Create a new `Parser` with the given `input` and `options`. **Params** * `input` **{String}** * `options` **{Object}** ### [.define](lib/parser.js#L103) Define a non-enumberable property on the `Parser` instance. **Example** ```js parser.define('foo', 'bar'); ``` **Params** * `key` **{String}**: propery name * `val` **{any}**: property value * `returns` **{Object}**: Returns the Parser instance for chaining. Set parser `name` with the given `fn` **Params** * `name` **{String}** * `fn` **{Function}** Get parser `name` **Params** * `name` **{String}** Push a `token` onto the `type` stack. **Params** * `type` **{String}** * `returns` **{Object}** `token` Pop a token off of the `type` stack **Params** * `type` **{String}** * `returns` **{Object}**: Returns a token Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`. **Params** * `type` **{String}** * `returns` **{Boolean}** **Example** ```js parser.isType(node, 'brace'); ``` **Params** * `node` **{Object}** * `type` **{String}** * `returns` **{Boolean}** ### [.define](lib/compiler.js#L71) Define a non-enumberable property on the `Compiler` instance. **Example** ```js compiler.define('foo', 'bar'); ``` **Params** * `key` **{String}**: propery name * `val` **{any}**: property value * `returns` **{Object}**: Returns the Compiler instance for chaining. ## About ### Related projects * [braces](https://www.npmjs.com/package/braces): Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces… [more](https://github.com/jonschlinkert/braces) | [homepage](https://github.com/jonschlinkert/braces "Fastest brace expansion for node.js, with the most complete support for the Bash 4.3 braces specification.") * [expand-brackets](https://www.npmjs.com/package/expand-brackets): Expand POSIX bracket expressions (character classes) in glob patterns. | [homepage](https://github.com/jonschlinkert/expand-brackets "Expand POSIX bracket expressions (character classes) in glob patterns.") * [extglob](https://www.npmjs.com/package/extglob): Convert extended globs to regex-compatible strings. Add (almost) the expressive power of regular expressions to… [more](https://github.com/jonschlinkert/extglob) | [homepage](https://github.com/jonschlinkert/extglob "Convert extended globs to regex-compatible strings. Add (almost) the expressive power of regular expressions to glob patterns.") * [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor**<br/> | | --- | --- | | 106 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [doowb](https://github.com/doowb) | ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/snapdragon/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 10, 2016._ # fast-deep-equal The fastest deep equal [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm version](https://badge.fury.io/js/fast-deep-equal.svg)](http://badge.fury.io/js/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (0.10+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` ## Performance benchmark Node.js v9.11.1: ``` fast-deep-equal x 226,960 ops/sec ±1.55% (86 runs sampled) nano-equal x 218,210 ops/sec ±0.79% (89 runs sampled) shallow-equal-fuzzy x 206,762 ops/sec ±0.84% (88 runs sampled) underscore.isEqual x 128,668 ops/sec ±0.75% (91 runs sampled) lodash.isEqual x 44,895 ops/sec ±0.67% (85 runs sampled) deep-equal x 51,616 ops/sec ±0.96% (90 runs sampled) deep-eql x 28,218 ops/sec ±0.42% (85 runs sampled) assert.deepStrictEqual x 1,777 ops/sec ±1.05% (86 runs sampled) ramda.equals x 13,466 ops/sec ±0.82% (86 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm install node benchmark ``` ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE) # lodash.clonedeep v4.5.0 The [lodash](https://lodash.com/) method `_.cloneDeep` exported as a [Node.js](https://nodejs.org/) module. ## Installation Using npm: ```bash $ {sudo -H} npm i -g npm $ npm i --save lodash.clonedeep ``` In Node.js: ```js var cloneDeep = require('lodash.clonedeep'); ``` See the [documentation](https://lodash.com/docs#cloneDeep) or [package source](https://github.com/lodash/lodash/blob/4.5.0-npm-packages/lodash.clonedeep) for more details. # minipass A _very_ minimal implementation of a [PassThrough stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough) [It's very fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0) for objects, strings, and buffers. Supports pipe()ing (including multi-pipe() and backpressure transmission), buffering data until either a `data` event handler or `pipe()` is added (so you don't lose the first chunk), and most other cases where PassThrough is a good idea. There is a `read()` method, but it's much more efficient to consume data from this stream via `'data'` events or by calling `pipe()` into some other stream. Calling `read()` requires the buffer to be flattened in some cases, which requires copying memory. There is also no `unpipe()` method. Once you start piping, there is no stopping it! If you set `objectMode: true` in the options, then whatever is written will be emitted. Otherwise, it'll do a minimal amount of Buffer copying to ensure proper Streams semantics when `read(n)` is called. This is not a `through` or `through2` stream. It doesn't transform the data, it just passes it right through. If you want to transform the data, extend the class, and override the `write()` method. Once you're done transforming the data however you want, call `super.write()` with the transform output. For an example of a stream that extends MiniPass to provide transform capabilities, check out [minizlib](http://npm.im/minizlib). ## USAGE ```js const MiniPass = require('minipass') const mp = new MiniPass(options) // optional: { encoding } mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` ### collecting ```js mp.collect().then(all => { // all is an array of all the data emitted // encoding is supported in this case, so // so the result will be a collection of strings if // an encoding is specified, or buffers/objects if not. // // In an async function, you may do // const data = await stream.collect() }) ``` ### iteration You can iterate over streams synchronously or asynchronously in platforms that support it. Synchronous iteration will end when the currently available data is consumed, even if the `end` event has not been reached. In string and buffer mode, the data is concatenated, so unless multiple writes are occurring in the same tick as the `read()`, sync iteration loops will generally only have a single iteration. To consume chunks in this way exactly as they have been written, with no flattening, create the stream with the `{ objectMode: true }` option. ```js const mp = new Minipass({ objectMode: true }) mp.write('a') mp.write('b') for (let letter of mp) { console.log(letter) // a, b } mp.write('c') mp.write('d') for (let letter of mp) { console.log(letter) // c, d } mp.write('e') mp.end() for (let letter of mp) { console.log(letter) // e } for (let letter of mp) { console.log(letter) // nothing } ``` Asynchronous iteration will continue until the end event is reached, consuming all of the data. ```js const mp = new Minipass({ encoding: 'utf8' }) // some source of some data let i = 5 const inter = setInterval(() => { if (i --> 0) mp.write(Buffer.from('foo\n', 'utf8')) else { mp.end() clearInterval(inter) } }, 100) // consume the data with asynchronous iteration async function consume () { for await (let chunk of mp) { console.log(chunk) } return 'ok' } consume().then(res => console.log(res)) // logs `foo\n` 5 times, and then `ok` ``` # run-queue A promise based, dynamic priority queue runner, with concurrency limiting. ```js const RunQueue = require('run-queue') const queue = new RunQueue({ maxConcurrency: 1 }) queue.add(1, example, [-1]) for (let ii = 0; ii < 5; ++ii) { queue.add(0, example, [ii]) } const finished = [] queue.run().then( console.log(finished) }) function example (num, next) { setTimeout(() => { finished.push(num) next() }, 5 - Math.abs(num)) } ``` would output ``` [ 0, 1, 2, 3, 4, -1 ] ``` If you bump concurrency to `2`, then you get: ``` [ 1, 0, 3, 2, 4, -1 ] ``` The concurrency means that they don't finish in order, because some take longer than others. Each priority level must finish entirely before the next priority level is run. See [PRIORITIES](https://github.com/iarna/run-queue#priorities) below. This is even true if concurrency is set high enough that all of the regular queue can execute at once, for instance, with `maxConcurrency: 10`: ``` [ 4, 3, 2, 1, 0, -1 ] ``` ## API ### const queue = new RunQueue(options) Create a new queue. Options may contain: * maxConcurrency - (Default: `1`) The maximum number of jobs to execute at once. * Promise - (Default: global.Promise) The promise implementation to use. ### queue.add (prio, fn, args) Add a new job to the end of the queue at priority `prio` that will run `fn` with `args`. If `fn` is async then it should return a Promise. ### queue.run () Start running the job queue. Returns a Promise that resolves when either all the jobs are complete or a job ends in error (throws or returns a rejected promise). If a job ended in error then this Promise will be rejected with that error and no further queue running will be done. ## PRIORITIES Priorities are any integer value >= 0. Lowest is executed first. Priorities essentially represent distinct job queues. All jobs in a queue must complete before the next highest priority job queue is executed. This means that if you have two queues, `0` and `1` then ALL jobs in `0` must complete before ANY execute in `1`. If you add new `0` level jobs while `1` level jobs are running then it will switch back processing the `0` queue and won't execute any more `1` jobs till all of the new `0` jobs complete. # dns-packet An [abstract-encoding](https://github.com/mafintosh/abstract-encoding) compliant module for encoding / decoding DNS packets. Lifted out of [multicast-dns](https://github.com/mafintosh/multicast-dns) as a separate module. ``` npm install dns-packet ``` [![build status](https://travis-ci.org/mafintosh/dns-packet.svg?branch=master)](https://travis-ci.org/mafintosh/dns-packet) ## Usage ``` js var packet = require('dns-packet') var dgram = require('dgram') var socket = dgram.createSocket('udp4') var buf = packet.encode({ type: 'query', id: 1, flags: packet.RECURSION_DESIRED, questions: [{ type: 'A', name: 'google.com' }] }) socket.on('message', function (message) { console.log(packet.decode(message)) // prints out a response from google dns }) socket.send(buf, 0, buf.length, 53, '8.8.8.8') ``` ## API #### `var buf = packets.encode(packet, [buf], [offset])` Encodes a DNS packet into a buffer. #### `var packet = packets.decode(buf, [offset])` Decode a DNS packet from a buffer #### `var len = packets.encodingLength(packet)` Returns how many bytes are needed to encode the DNS packet ## Packets Packets look like this ``` js { type: 'query|response', id: optionalIdNumber, flags: optionalBitFlags, questions: [...], answers: [...], additionals: [...], authorities: [...] } ``` The bit flags available are ``` js packet.RECURSION_DESIRED packet.RECURSION_AVAILABLE packet.TRUNCATED_RESPONSE packet.AUTHORITATIVE_ANSWER packet.AUTHENTIC_DATA packet.CHECKING_DISABLED ``` To use more than one flag bitwise-or them together ``` js var flags = packet.RECURSION_DESIRED | packet.RECURSION_AVAILABLE ``` And to check for a flag use bitwise-and ``` js var isRecursive = message.flags & packet.RECURSION_DESIRED ``` A question looks like this ``` js { type: 'A', // or SRV, AAAA, etc name: 'google.com' // which record are you looking for } ``` And an answers, additional, or authority looks like this ``` js { type: 'A', // or SRV, AAAA, etc name: 'google.com', // which name is this record for ttl: optionalTimeToLiveInSeconds, (record specific data, see below) } ``` Currently the different available records are #### `A` ``` js { data: 'IPv4 address' // fx 127.0.0.1 } ``` #### `AAAA` ``` js { data: 'IPv6 address' // fx fe80::1 } ``` #### `TXT` ``` js { data: Buffer('some text') } ``` #### `NS` ``` js { data: nameServer } ``` #### `NULL` ``` js { data: Buffer('any binary data') } ``` #### `SOA` ``` js { data: { mname: domainName, rname: mailbox, serial: zoneSerial, refresh: refreshInterval, retry: retryInterval, expire: expireInterval, minimum: minimumTTL } } ``` #### `SRV` ``` js { data: { port: servicePort, target: serviceHostName, priority: optionalServicePriority, weight: optionalServiceWeight } } ``` #### `HINFO` ``` js { data: { cpu: 'cpu info', os: 'os info' } } ``` #### `PTR` ``` js { data: 'points.to.another.record' } ``` #### `CNAME` ``` js { data: 'cname.to.another.record' } ``` #### `DNAME` ``` js { data: 'dname.to.another.record' } ``` #### `CAA` ``` js { flags: 128, // octet tag: 'issue|issuewild|iodef', value: 'ca.example.net' } ``` If you need another one, open an issue and we'll try to add it. ## License MIT # multicast-dns-service-types Parse and stringify mdns service types ``` npm install multicast-dns-service-types ``` [![build status](http://img.shields.io/travis/mafintosh/multicast-dns-service-types.svg?style=flat)](http://travis-ci.org/mafintosh/multicast-dns-service-types) ## Usage ``` js var types = require('multicast-dns-service-types') console.log(types.stringify({name: 'http', protocol: 'tcp', subtypes: ['sub1', 'sub2']})) // _http._tcp._sub1._sub2 console.log(types.parse('_http._tcp._sub1._sub2')) // {name: 'http', protocol: 'tcp', subtypes: ['sub1', 'sub2']} ``` The following shorthands also exist ``` js types.stringify(name, protocol, subtypes) types.tcp(name, subtypes) // set protocol to tcp types.udp(name, subtypes) // set protocol to udp ``` ## License MIT terser ====== ![Terser](https://raw.githubusercontent.com/terser-js/terser/master/logo.png) A JavaScript parser and mangler/compressor toolkit for ES6+. *note*: You can support this project on patreon: <a target="_blank" rel="nofollow" href="https://www.patreon.com/fabiosantoscode"><img src="https://c5.patreon.com/external/logo/[email protected]" alt="patron" width="100px" height="auto"></a>. Check out PATRONS.md for our first-tier patrons. Terser recommends you use RollupJS to bundle your modules, as that produces smaller code overall. *Beautification* has been undocumented and is *being removed* from terser, we recommend you use [prettier](https://npmjs.com/package/prettier). [![Build Status](https://travis-ci.org/terser-js/terser.svg?branch=master)](https://travis-ci.org/terser-js/terser) Find the changelog in [CHANGELOG.md](https://github.com/terser-js/terser/blob/master/CHANGELOG.md) A JavaScript parser, mangler/compressor and beautifier toolkit for ES6+. Why choose terser? ------------------ `uglify-es` is [no longer maintained](https://github.com/mishoo/UglifyJS2/issues/3156#issuecomment-392943058) and `uglify-js` does not support ES6+. **`terser`** is a fork of `uglify-es` that retains API and CLI compatibility with `uglify-es` and `uglify-js@3`. Install ------- First make sure you have installed the latest version of [node.js](http://nodejs.org/) (You may need to restart your computer after this step). From NPM for use as a command line app: npm install terser -g From NPM for programmatic use: npm install terser # Command line usage terser [input files] [options] Terser can take multiple input files. It's recommended that you pass the input files first, then pass the options. Terser will parse input files in sequence and apply any compression options. The files are parsed in the same global scope, that is, a reference from a file to some variable/function declared in another file will be matched properly. If no input file is specified, Terser will read from STDIN. If you wish to pass your options before the input files, separate the two with a double dash to prevent input files being used as option arguments: terser --compress --mangle -- input.js ### Command line options ``` -h, --help Print usage information. `--help options` for details on available options. -V, --version Print version number. -p, --parse <options> Specify parser options: `acorn` Use Acorn for parsing. `bare_returns` Allow return outside of functions. Useful when minifying CommonJS modules and Userscripts that may be anonymous function wrapped (IIFE) by the .user.js engine `caller`. `expression` Parse a single expression, rather than a program (for parsing JSON). `spidermonkey` Assume input files are SpiderMonkey AST format (as JSON). -c, --compress [options] Enable compressor/specify compressor options: `pure_funcs` List of functions that can be safely removed when their return values are not used. -m, --mangle [options] Mangle names/specify mangler options: `reserved` List of names that should not be mangled. --mangle-props [options] Mangle properties/specify mangler options: `builtins` Mangle property names that overlaps with standard JavaScript globals. `debug` Add debug prefix and suffix. `domprops` Mangle property names that overlaps with DOM properties. `keep_quoted` Only mangle unquoted properties. `regex` Only mangle matched property names. `reserved` List of names that should not be mangled. -b, --beautify [options] Specify output options: `preamble` Preamble to prepend to the output. You can use this to insert a comment, for example for licensing information. This will not be parsed, but the source map will adjust for its presence. `quote_style` Quote style: 0 - auto 1 - single 2 - double 3 - original `wrap_iife` Wrap IIFEs in parenthesis. Note: you may want to disable `negate_iife` under compressor options. -o, --output <file> Output file path (default STDOUT). Specify `ast` or `spidermonkey` to write Terser or SpiderMonkey AST as JSON to STDOUT respectively. --comments [filter] Preserve copyright comments in the output. By default this works like Google Closure, keeping JSDoc-style comments that contain "@license" or "@preserve". You can optionally pass one of the following arguments to this flag: - "all" to keep all comments - a valid JS RegExp like `/foo/` or `/^!/` to keep only matching comments. Note that currently not *all* comments can be kept when compression is on, because of dead code removal or cascading statements into sequences. --config-file <file> Read `minify()` options from JSON file. -d, --define <expr>[=value] Global definitions. --ecma <version> Specify ECMAScript release: 5, 6, 7 or 8. -e, --enclose [arg[:value]] Embed output in a big function with configurable arguments and values. --ie8 Support non-standard Internet Explorer 8. Equivalent to setting `ie8: true` in `minify()` for `compress`, `mangle` and `output` options. By default Terser will not try to be IE-proof. --keep-classnames Do not mangle/drop class names. --keep-fnames Do not mangle/drop function names. Useful for code relying on Function.prototype.name. --module Input is an ES6 module. If `compress` or `mangle` is enabled then the `toplevel` option will be enabled. --name-cache <file> File to hold mangled name mappings. --safari10 Support non-standard Safari 10/11. Equivalent to setting `safari10: true` in `minify()` for `mangle` and `output` options. By default `terser` will not work around Safari 10/11 bugs. --source-map [options] Enable source map/specify source map options: `base` Path to compute relative paths from input files. `content` Input source map, useful if you're compressing JS that was generated from some other original code. Specify "inline" if the source map is included within the sources. `filename` Name and/or location of the output source. `includeSources` Pass this flag if you want to include the content of source files in the source map as sourcesContent property. `root` Path to the original source to be included in the source map. `url` If specified, path to the source map to append in `//# sourceMappingURL`. --timings Display operations run time on STDERR. --toplevel Compress and/or mangle variables in top level scope. --verbose Print diagnostic messages. --warn Print warning messages. --wrap <name> Embed everything in a big function, making the “exports” and “global” variables available. You need to pass an argument to this option to specify the name that your module will take when included in, say, a browser. ``` Specify `--output` (`-o`) to declare the output file. Otherwise the output goes to STDOUT. ## CLI source map options Terser can generate a source map file, which is highly useful for debugging your compressed JavaScript. To get a source map, pass `--source-map --output output.js` (source map will be written out to `output.js.map`). Additional options: - `--source-map "filename='<NAME>'"` to specify the name of the source map. - `--source-map "root='<URL>'"` to pass the URL where the original files can be found. - `--source-map "url='<URL>'"` to specify the URL where the source map can be found. Otherwise Terser assumes HTTP `X-SourceMap` is being used and will omit the `//# sourceMappingURL=` directive. For example: terser js/file1.js js/file2.js \ -o foo.min.js -c -m \ --source-map "root='http://foo.com/src',url='foo.min.js.map'" The above will compress and mangle `file1.js` and `file2.js`, will drop the output in `foo.min.js` and the source map in `foo.min.js.map`. The source mapping will refer to `http://foo.com/src/js/file1.js` and `http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` as the source map root, and the original files as `js/file1.js` and `js/file2.js`). ### Composed source map When you're compressing JS code that was output by a compiler such as CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd like to map back to the original code (i.e. CoffeeScript). Terser has an option to take an input source map. Assuming you have a mapping from CoffeeScript → compiled JS, Terser can generate a map from CoffeeScript → compressed JS by mapping every token in the compiled JS to its original location. To use this feature pass `--source-map "content='/path/to/input/source.map'"` or `--source-map "content=inline"` if the source map is included inline with the sources. ## CLI compress options You need to pass `--compress` (`-c`) to enable the compressor. Optionally you can pass a comma-separated list of [compress options](#compress-options). Options are in the form `foo=bar`, or just `foo` (the latter implies a boolean option that you want to set `true`; it's effectively a shortcut for `foo=true`). Example: terser file.js -c toplevel,sequences=false ## CLI mangle options To enable the mangler you need to pass `--mangle` (`-m`). The following (comma-separated) options are supported: - `toplevel` (default `false`) -- mangle names declared in the top level scope. - `eval` (default `false`) -- mangle names visible in scopes where `eval` or `with` are used. When mangling is enabled but you want to prevent certain names from being mangled, you can declare those names with `--mangle reserved` — pass a comma-separated list of names. For example: terser ... -m reserved=['$','require','exports'] to prevent the `require`, `exports` and `$` names from being changed. ### CLI mangling property names (`--mangle-props`) **Note:** THIS **WILL** BREAK YOUR CODE. A good rule of thumb is not to use this unless you know exactly what you're doing and how this works and read this section until the end. Mangling property names is a separate step, different from variable name mangling. Pass `--mangle-props` to enable it. The least dangerous way to use this is to use the `regex` option like so: ``` terser example.js -c -m --mangle-props regex=/_$/ ``` This will mangle all properties that start with an underscore. So you can use it to mangle internal methods. By default, it will mangle all properties in the input code with the exception of built in DOM properties and properties in core JavaScript classes, which is what will break your code if you don't: 1. Control all the code you're mangling 2. Avoid using a module bundler, as they usually will call Terser on each file individually, making it impossible to pass mangled objects between modules. 3. Avoid calling functions like `defineProperty` or `hasOwnProperty`, because they refer to object properties using strings and will break your code if you don't know what you are doing. An example: ```javascript // example.js var x = { baz_: 0, foo_: 1, calc: function() { return this.foo_ + this.baz_; } }; x.bar_ = 2; x["baz_"] = 3; console.log(x.calc()); ``` Mangle all properties (except for JavaScript `builtins`) (**very** unsafe): ```bash $ terser example.js -c -m --mangle-props ``` ```javascript var x={o:0,_:1,l:function(){return this._+this.o}};x.t=2,x.o=3,console.log(x.l()); ``` Mangle all properties except for `reserved` properties (still very unsafe): ```bash $ terser example.js -c -m --mangle-props reserved=[foo_,bar_] ``` ```javascript var x={o:0,foo_:1,_:function(){return this.foo_+this.o}};x.bar_=2,x.o=3,console.log(x._()); ``` Mangle all properties matching a `regex` (not as unsafe but still unsafe): ```bash $ terser example.js -c -m --mangle-props regex=/_$/ ``` ```javascript var x={o:0,_:1,calc:function(){return this._+this.o}};x.l=2,x.o=3,console.log(x.calc()); ``` Combining mangle properties options: ```bash $ terser example.js -c -m --mangle-props regex=/_$/,reserved=[bar_] ``` ```javascript var x={o:0,_:1,calc:function(){return this._+this.o}};x.bar_=2,x.o=3,console.log(x.calc()); ``` In order for this to be of any use, we avoid mangling standard JS names by default (`--mangle-props builtins` to override). A default exclusion file is provided in `tools/domprops.json` which should cover most standard JS and DOM properties defined in various browsers. Pass `--mangle-props domprops` to disable this feature. A regular expression can be used to define which property names should be mangled. For example, `--mangle-props regex=/^_/` will only mangle property names that start with an underscore. When you compress multiple files using this option, in order for them to work together in the end we need to ensure somehow that one property gets mangled to the same name in all of them. For this, pass `--name-cache filename.json` and Terser will maintain these mappings in a file which can then be reused. It should be initially empty. Example: ```bash $ rm -f /tmp/cache.json # start fresh $ terser file1.js file2.js --mangle-props --name-cache /tmp/cache.json -o part1.js $ terser file3.js file4.js --mangle-props --name-cache /tmp/cache.json -o part2.js ``` Now, `part1.js` and `part2.js` will be consistent with each other in terms of mangled property names. Using the name cache is not necessary if you compress all your files in a single call to Terser. ### Mangling unquoted names (`--mangle-props keep_quoted`) Using quoted property name (`o["foo"]`) reserves the property name (`foo`) so that it is not mangled throughout the entire script even when used in an unquoted style (`o.foo`). Example: ```javascript // stuff.js var o = { "foo": 1, bar: 3 }; o.foo += o.bar; console.log(o.foo); ``` ```bash $ terser stuff.js --mangle-props keep_quoted -c -m ``` ```javascript var o={foo:1,o:3};o.foo+=o.o,console.log(o.foo); ``` ### Debugging property name mangling You can also pass `--mangle-props debug` in order to mangle property names without completely obscuring them. For example the property `o.foo` would mangle to `o._$foo$_` with this option. This allows property mangling of a large codebase while still being able to debug the code and identify where mangling is breaking things. ```bash $ terser stuff.js --mangle-props debug -c -m ``` ```javascript var o={_$foo$_:1,_$bar$_:3};o._$foo$_+=o._$bar$_,console.log(o._$foo$_); ``` You can also pass a custom suffix using `--mangle-props debug=XYZ`. This would then mangle `o.foo` to `o._$foo$XYZ_`. You can change this each time you compile a script to identify how a property got mangled. One technique is to pass a random number on every compile to simulate mangling changing with different inputs (e.g. as you update the input script with new properties), and to help identify mistakes like writing mangled keys to storage. # API Reference Assuming installation via NPM, you can load Terser in your application like this: ```javascript var Terser = require("terser"); ``` Browser loading is also supported: ```html <script src="node_modules/source-map/dist/source-map.min.js"></script> <script src="dist/bundle.min.js"></script> ``` There is a single high level function, **`minify(code, options)`**, which will perform all minification [phases](#minify-options) in a configurable manner. By default `minify()` will enable the options [`compress`](#compress-options) and [`mangle`](#mangle-options). Example: ```javascript var code = "function add(first, second) { return first + second; }"; var result = Terser.minify(code); console.log(result.error); // runtime error, or `undefined` if no error console.log(result.code); // minified output: function add(n,d){return n+d} ``` You can `minify` more than one JavaScript file at a time by using an object for the first argument where the keys are file names and the values are source code: ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var result = Terser.minify(code); console.log(result.code); // function add(d,n){return d+n}console.log(add(3,7)); ``` The `toplevel` option: ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var options = { toplevel: true }; var result = Terser.minify(code, options); console.log(result.code); // console.log(3+7); ``` The `nameCache` option: ```javascript var options = { mangle: { toplevel: true, }, nameCache: {} }; var result1 = Terser.minify({ "file1.js": "function add(first, second) { return first + second; }" }, options); var result2 = Terser.minify({ "file2.js": "console.log(add(1 + 2, 3 + 4));" }, options); console.log(result1.code); // function n(n,r){return n+r} console.log(result2.code); // console.log(n(3,7)); ``` You may persist the name cache to the file system in the following way: ```javascript var cacheFileName = "/tmp/cache.json"; var options = { mangle: { properties: true, }, nameCache: JSON.parse(fs.readFileSync(cacheFileName, "utf8")) }; fs.writeFileSync("part1.js", Terser.minify({ "file1.js": fs.readFileSync("file1.js", "utf8"), "file2.js": fs.readFileSync("file2.js", "utf8") }, options).code, "utf8"); fs.writeFileSync("part2.js", Terser.minify({ "file3.js": fs.readFileSync("file3.js", "utf8"), "file4.js": fs.readFileSync("file4.js", "utf8") }, options).code, "utf8"); fs.writeFileSync(cacheFileName, JSON.stringify(options.nameCache), "utf8"); ``` An example of a combination of `minify()` options: ```javascript var code = { "file1.js": "function add(first, second) { return first + second; }", "file2.js": "console.log(add(1 + 2, 3 + 4));" }; var options = { toplevel: true, compress: { global_defs: { "@console.log": "alert" }, passes: 2 }, output: { beautify: false, preamble: "/* minified */" } }; var result = Terser.minify(code, options); console.log(result.code); // /* minified */ // alert(10);" ``` To produce warnings: ```javascript var code = "function f(){ var u; return 2 + 3; }"; var options = { warnings: true }; var result = Terser.minify(code, options); console.log(result.error); // runtime error, `undefined` in this case console.log(result.warnings); // [ 'Dropping unused variable u [0:1,18]' ] console.log(result.code); // function f(){return 5} ``` An error example: ```javascript var result = Terser.minify({"foo.js" : "if (0) else console.log(1);"}); console.log(JSON.stringify(result.error)); // {"message":"Unexpected token: keyword (else)","filename":"foo.js","line":1,"col":7,"pos":7} ``` Note: unlike `[email protected]`, the Terser API does not throw errors. To achieve a similar effect one could do the following: ```javascript var result = Terser.minify(code, options); if (result.error) throw result.error; ``` ## Minify options - `ecma` (default `undefined`) - pass `5`, `6`, `7` or `8` to override `parse`, `compress` and `output` options. - `warnings` (default `false`) — pass `true` to return compressor warnings in `result.warnings`. Use the value `"verbose"` for more detailed warnings. - `parse` (default `{}`) — pass an object if you wish to specify some additional [parse options](#parse-options). - `compress` (default `{}`) — pass `false` to skip compressing entirely. Pass an object to specify custom [compress options](#compress-options). - `mangle` (default `true`) — pass `false` to skip mangling names, or pass an object to specify [mangle options](#mangle-options) (see below). - `mangle.properties` (default `false`) — a subcategory of the mangle option. Pass an object to specify custom [mangle property options](#mangle-properties-options). - `module` (default `false`) — Use when minifying an ES6 module. "use strict" is implied and names can be mangled on the top scope. If `compress` or `mangle` is enabled then the `toplevel` option will be enabled. - `output` (default `null`) — pass an object if you wish to specify additional [output options](#output-options). The defaults are optimized for best compression. - `sourceMap` (default `false`) - pass an object if you wish to specify [source map options](#source-map-options). - `toplevel` (default `false`) - set to `true` if you wish to enable top level variable and function name mangling and to drop unused variables and functions. - `nameCache` (default `null`) - pass an empty object `{}` or a previously used `nameCache` object if you wish to cache mangled variable and property names across multiple invocations of `minify()`. Note: this is a read/write property. `minify()` will read the name cache state of this object and update it during minification so that it may be reused or externally persisted by the user. - `ie8` (default `false`) - set to `true` to support IE8. - `keep_classnames` (default: `undefined`) - pass `true` to prevent discarding or mangling of class names. Pass a regular expression to only keep class names matching that regex. - `keep_fnames` (default: `false`) - pass `true` to prevent discarding or mangling of function names. Pass a regular expression to only keep class names matching that regex. Useful for code relying on `Function.prototype.name`. If the top level minify option `keep_classnames` is `undefined` it will be overridden with the value of the top level minify option `keep_fnames`. - `safari10` (default: `false`) - pass `true` to work around Safari 10/11 bugs in loop scoping and `await`. See `safari10` options in [`mangle`](#mangle-options) and [`output`](#output-options) for details. ## Minify options structure ```javascript { parse: { // parse options }, compress: { // compress options }, mangle: { // mangle options properties: { // mangle property options } }, output: { // output options }, sourceMap: { // source map options }, ecma: 5, // specify one of: 5, 6, 7 or 8 keep_classnames: false, keep_fnames: false, ie8: false, module: false, nameCache: null, // or specify a name cache object safari10: false, toplevel: false, warnings: false, } ``` ### Source map options To generate a source map: ```javascript var result = Terser.minify({"file1.js": "var a = function() {};"}, { sourceMap: { filename: "out.js", url: "out.js.map" } }); console.log(result.code); // minified output console.log(result.map); // source map ``` Note that the source map is not saved in a file, it's just returned in `result.map`. The value passed for `sourceMap.url` is only used to set `//# sourceMappingURL=out.js.map` in `result.code`. The value of `filename` is only used to set `file` attribute (see [the spec][sm-spec]) in source map file. You can set option `sourceMap.url` to be `"inline"` and source map will be appended to code. You can also specify sourceRoot property to be included in source map: ```javascript var result = Terser.minify({"file1.js": "var a = function() {};"}, { sourceMap: { root: "http://example.com/src", url: "out.js.map" } }); ``` If you're compressing compiled JavaScript and have a source map for it, you can use `sourceMap.content`: ```javascript var result = Terser.minify({"compiled.js": "compiled code"}, { sourceMap: { content: "content from compiled.js.map", url: "minified.js.map" } }); // same as before, it returns `code` and `map` ``` If you're using the `X-SourceMap` header instead, you can just omit `sourceMap.url`. ## Parse options - `bare_returns` (default `false`) -- support top level `return` statements - `ecma` (default: `8`) -- specify one of `5`, `6`, `7` or `8`. Note: this setting is not presently enforced except for ES8 optional trailing commas in function parameter lists and calls with `ecma` `8`. - `html5_comments` (default `true`) - `shebang` (default `true`) -- support `#!command` as the first line ## Compress options - `arrows` (default: `true`) -- Converts `()=>{return x}` to `()=>x`. Class and object literal methods will also be converted to arrow expressions if the resultant code is shorter: `m(){return x}` becomes `m:()=>x`. - `arguments` (default: `false`) -- replace `arguments[index]` with function parameter name whenever possible. - `booleans` (default: `true`) -- various optimizations for boolean context, for example `!!a ? b : c → a ? b : c` - `booleans_as_integers` (default: `false`) -- Turn booleans into 0 and 1, also makes comparisons with booleans use `==` and `!=` instead of `===` and `!==`. - `collapse_vars` (default: `true`) -- Collapse single-use non-constant variables, side effects permitting. - `comparisons` (default: `true`) -- apply certain optimizations to binary nodes, e.g. `!(a <= b) → a > b` (only when `unsafe_comps`), attempts to negate binary nodes, e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. - `computed_props` (default: `true`) -- Transforms constant computed properties into regular ones: `{["computed"]: 1}` is converted to `{computed: 1}`. - `conditionals` (default: `true`) -- apply optimizations for `if`-s and conditional expressions - `dead_code` (default: `true`) -- remove unreachable code - `defaults` (default: `true`) -- Pass `false` to disable most default enabled `compress` transforms. Useful when you only want to enable a few `compress` options while disabling the rest. - `directives` (default: `true`) -- remove redundant or non-standard directives - `drop_console` (default: `false`) -- Pass `true` to discard calls to `console.*` functions. If you wish to drop a specific function call such as `console.info` and/or retain side effects from function arguments after dropping the function call then use `pure_funcs` instead. - `drop_debugger` (default: `true`) -- remove `debugger;` statements - `ecma` (default: `5`) -- Pass `6` or greater to enable `compress` options that will transform ES5 code into smaller ES6+ equivalent forms. - `evaluate` (default: `true`) -- attempt to evaluate constant expressions - `expression` (default: `false`) -- Pass `true` to preserve completion values from terminal statements without `return`, e.g. in bookmarklets. - `global_defs` (default: `{}`) -- see [conditional compilation](#conditional-compilation) - `hoist_funs` (default: `false`) -- hoist function declarations - `hoist_props` (default: `true`) -- hoist properties from constant object and array literals into regular variables subject to a set of constraints. For example: `var o={p:1, q:2}; f(o.p, o.q);` is converted to `f(1, 2);`. Note: `hoist_props` works best with `mangle` enabled, the `compress` option `passes` set to `2` or higher, and the `compress` option `toplevel` enabled. - `hoist_vars` (default: `false`) -- hoist `var` declarations (this is `false` by default because it seems to increase the size of the output in general) - `if_return` (default: `true`) -- optimizations for if/return and if/continue - `inline` (default: `true`) -- inline calls to function with simple/`return` statement: - `false` -- same as `0` - `0` -- disabled inlining - `1` -- inline simple functions - `2` -- inline functions with arguments - `3` -- inline functions with arguments and variables - `true` -- same as `3` - `join_vars` (default: `true`) -- join consecutive `var` statements - `keep_classnames` (default: `false`) -- Pass `true` to prevent the compressor from discarding class names. Pass a regular expression to only keep class names matching that regex. See also: the `keep_classnames` [mangle option](#mangle). - `keep_fargs` (default: `true`) -- Prevents the compressor from discarding unused function arguments. You need this for code which relies on `Function.length`. - `keep_fnames` (default: `false`) -- Pass `true` to prevent the compressor from discarding function names. Pass a regular expression to only keep class names matching that regex. Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames` [mangle option](#mangle). - `keep_infinity` (default: `false`) -- Pass `true` to prevent `Infinity` from being compressed into `1/0`, which may cause performance issues on Chrome. - `loops` (default: `true`) -- optimizations for `do`, `while` and `for` loops when we can statically determine the condition. - `module` (default `false`) -- Pass `true` when compressing an ES6 module. Strict mode is implied and the `toplevel` option as well. - `negate_iife` (default: `true`) -- negate "Immediately-Called Function Expressions" where the return value is discarded, to avoid the parens that the code generator would insert. - `passes` (default: `1`) -- The maximum number of times to run compress. In some cases more than one pass leads to further compressed code. Keep in mind more passes will take more time. - `properties` (default: `true`) -- rewrite property access using the dot notation, for example `foo["bar"] → foo.bar` - `pure_funcs` (default: `null`) -- You can pass an array of names and Terser will assume that those functions do not produce side effects. DANGER: will not check if the name is redefined in scope. An example case here, for instance `var q = Math.floor(a/b)`. If variable `q` is not used elsewhere, Terser will drop it, but will still keep the `Math.floor(a/b)`, not knowing what it does. You can pass `pure_funcs: [ 'Math.floor' ]` to let it know that this function won't produce any side effect, in which case the whole statement would get discarded. The current implementation adds some overhead (compression will be slower). - `pure_getters` (default: `"strict"`) -- If you pass `true` for this, Terser will assume that object property access (e.g. `foo.bar` or `foo["bar"]`) doesn't have any side effects. Specify `"strict"` to treat `foo.bar` as side-effect-free only when `foo` is certain to not throw, i.e. not `null` or `undefined`. - `reduce_funcs` (default: `true`) -- Allows single-use functions to be inlined as function expressions when permissible allowing further optimization. Enabled by default. Option depends on `reduce_vars` being enabled. Some code runs faster in the Chrome V8 engine if this option is disabled. Does not negatively impact other major browsers. - `reduce_vars` (default: `true`) -- Improve optimization on variables assigned with and used as constant values. - `sequences` (default: `true`) -- join consecutive simple statements using the comma operator. May be set to a positive integer to specify the maximum number of consecutive comma sequences that will be generated. If this option is set to `true` then the default `sequences` limit is `200`. Set option to `false` or `0` to disable. The smallest `sequences` length is `2`. A `sequences` value of `1` is grandfathered to be equivalent to `true` and as such means `200`. On rare occasions the default sequences limit leads to very slow compress times in which case a value of `20` or less is recommended. - `side_effects` (default: `true`) -- Pass `false` to disable potentially dropping functions marked as "pure". A function call is marked as "pure" if a comment annotation `/*@__PURE__*/` or `/*#__PURE__*/` immediately precedes the call. For example: `/*@__PURE__*/foo();` - `switches` (default: `true`) -- de-duplicate and remove unreachable `switch` branches - `toplevel` (default: `false`) -- drop unreferenced functions (`"funcs"`) and/or variables (`"vars"`) in the top level scope (`false` by default, `true` to drop both unreferenced functions and variables) - `top_retain` (default: `null`) -- prevent specific toplevel functions and variables from `unused` removal (can be array, comma-separated, RegExp or function. Implies `toplevel`) - `typeofs` (default: `true`) -- Transforms `typeof foo == "undefined"` into `foo === void 0`. Note: recommend to set this value to `false` for IE10 and earlier versions due to known issues. - `unsafe` (default: `false`) -- apply "unsafe" transformations ([details](#the-unsafe-compress-option)). - `unsafe_arrows` (default: `false`) -- Convert ES5 style anonymous function expressions to arrow functions if the function body does not reference `this`. Note: it is not always safe to perform this conversion if code relies on the the function having a `prototype`, which arrow functions lack. This transform requires that the `ecma` compress option is set to `6` or greater. - `unsafe_comps` (default: `false`) -- Reverse `<` and `<=` to `>` and `>=` to allow improved compression. This might be unsafe when an at least one of two operands is an object with computed values due the use of methods like `get`, or `valueOf`. This could cause change in execution order after operands in the comparison are switching. Compression only works if both `comparisons` and `unsafe_comps` are both set to true. - `unsafe_Function` (default: `false`) -- compress and mangle `Function(args, code)` when both `args` and `code` are string literals. - `unsafe_math` (default: `false`) -- optimize numerical expressions like `2 * x * 3` into `6 * x`, which may give imprecise floating point results. - `unsafe_methods` (default: false) -- Converts `{ m: function(){} }` to `{ m(){} }`. `ecma` must be set to `6` or greater to enable this transform. If `unsafe_methods` is a RegExp then key/value pairs with keys matching the RegExp will be converted to concise methods. Note: if enabled there is a risk of getting a "`<method name>` is not a constructor" TypeError should any code try to `new` the former function. - `unsafe_proto` (default: `false`) -- optimize expressions like `Array.prototype.slice.call(a)` into `[].slice.call(a)` - `unsafe_regexp` (default: `false`) -- enable substitutions of variables with `RegExp` values the same way as if they are constants. - `unsafe_undefined` (default: `false`) -- substitute `void 0` if there is a variable named `undefined` in scope (variable name will be mangled, typically reduced to a single character) - `unused` (default: `true`) -- drop unreferenced functions and variables (simple direct variable assignments do not count as references unless set to `"keep_assign"`) - `warnings` (default: `false`) -- display warnings when dropping unreachable code or unused declarations etc. ## Mangle options - `eval` (default `false`) -- Pass `true` to mangle names visible in scopes where `eval` or `with` are used. - `keep_classnames` (default `false`) -- Pass `true` to not mangle class names. Pass a regular expression to only keep class names matching that regex. See also: the `keep_classnames` [compress option](#compress-options). - `keep_fnames` (default `false`) -- Pass `true` to not mangle function names. Pass a regular expression to only keep class names matching that regex. Useful for code relying on `Function.prototype.name`. See also: the `keep_fnames` [compress option](#compress-options). - `module` (default `false`) -- Pass `true` an ES6 modules, where the toplevel scope is not the global scope. Implies `toplevel`. - `reserved` (default `[]`) -- Pass an array of identifiers that should be excluded from mangling. Example: `["foo", "bar"]`. - `toplevel` (default `false`) -- Pass `true` to mangle names declared in the top level scope. - `safari10` (default `false`) -- Pass `true` to work around the Safari 10 loop iterator [bug](https://bugs.webkit.org/show_bug.cgi?id=171041) "Cannot declare a let variable twice". See also: the `safari10` [output option](#output-options). Examples: ```javascript // test.js var globalVar; function funcName(firstLongName, anotherLongName) { var myVariable = firstLongName + anotherLongName; } ``` ```javascript var code = fs.readFileSync("test.js", "utf8"); Terser.minify(code).code; // 'function funcName(a,n){}var globalVar;' Terser.minify(code, { mangle: { reserved: ['firstLongName'] } }).code; // 'function funcName(firstLongName,a){}var globalVar;' Terser.minify(code, { mangle: { toplevel: true } }).code; // 'function n(n,a){}var a;' ``` ### Mangle properties options - `builtins` (default: `false`) -- Use `true` to allow the mangling of builtin DOM properties. Not recommended to override this setting. - `debug` (default: `false`) -— Mangle names with the original name still present. Pass an empty string `""` to enable, or a non-empty string to set the debug suffix. - `keep_quoted` (default: `false`) -— Only mangle unquoted property names. - `regex` (default: `null`) -— Pass a RegExp literal to only mangle property names matching the regular expression. - `reserved` (default: `[]`) -- Do not mangle property names listed in the `reserved` array. ## Output options The code generator tries to output shortest code possible by default. In case you want beautified output, pass `--beautify` (`-b`). Optionally you can pass additional arguments that control the code output: - `ascii_only` (default `false`) -- escape Unicode characters in strings and regexps (affects directives with non-ascii characters becoming invalid) - `beautify` (default `true`) -- whether to actually beautify the output. Passing `-b` will set this to true, but you might need to pass `-b` even when you want to generate minified code, in order to specify additional arguments, so you can use `-b beautify=false` to override it. - `braces` (default `false`) -- always insert braces in `if`, `for`, `do`, `while` or `with` statements, even if their body is a single statement. - `comments` (default `false`) -- pass `true` or `"all"` to preserve all comments, `"some"` to preserve some comments, a regular expression string (e.g. `/^!/`) or a function. - `ecma` (default `5`) -- set output printing mode. Set `ecma` to `6` or greater to emit shorthand object properties - i.e.: `{a}` instead of `{a: a}`. The `ecma` option will only change the output in direct control of the beautifier. Non-compatible features in the abstract syntax tree will still be output as is. For example: an `ecma` setting of `5` will **not** convert ES6+ code to ES5. - `indent_level` (default `4`) - `indent_start` (default `0`) -- prefix all lines by that many spaces - `inline_script` (default `true`) -- escape HTML comments and the slash in occurrences of `</script>` in strings - `keep_quoted_props` (default `false`) -- when turned on, prevents stripping quotes from property names in object literals. - `max_line_len` (default `false`) -- maximum line length (for minified code) - `preamble` (default `null`) -- when passed it must be a string and it will be prepended to the output literally. The source map will adjust for this text. Can be used to insert a comment containing licensing information, for example. - `quote_keys` (default `false`) -- pass `true` to quote all keys in literal objects - `quote_style` (default `0`) -- preferred quote style for strings (affects quoted property names and directives as well): - `0` -- prefers double quotes, switches to single quotes when there are more double quotes in the string itself. `0` is best for gzip size. - `1` -- always use single quotes - `2` -- always use double quotes - `3` -- always use the original quotes - `safari10` (default `false`) -- set this option to `true` to work around the [Safari 10/11 await bug](https://bugs.webkit.org/show_bug.cgi?id=176685). See also: the `safari10` [mangle option](#mangle-options). - `semicolons` (default `true`) -- separate statements with semicolons. If you pass `false` then whenever possible we will use a newline instead of a semicolon, leading to more readable output of minified code (size before gzip could be smaller; size after gzip insignificantly larger). - `shebang` (default `true`) -- preserve shebang `#!` in preamble (bash scripts) - `webkit` (default `false`) -- enable workarounds for WebKit bugs. PhantomJS users should set this option to `true`. - `wrap_iife` (default `false`) -- pass `true` to wrap immediately invoked function expressions. See [#640](https://github.com/mishoo/UglifyJS2/issues/640) for more details. # Miscellaneous ### Keeping copyright notices or other comments You can pass `--comments` to retain certain comments in the output. By default it will keep JSDoc-style comments that contain "@preserve", "@license" or "@cc_on" (conditional compilation for IE). You can pass `--comments all` to keep all the comments, or a valid JavaScript regexp to keep only comments that match this regexp. For example `--comments /^!/` will keep comments like `/*! Copyright Notice */`. Note, however, that there might be situations where comments are lost. For example: ```javascript function f() { /** @preserve Foo Bar */ function g() { // this function is never called } return something(); } ``` Even though it has "@preserve", the comment will be lost because the inner function `g` (which is the AST node to which the comment is attached to) is discarded by the compressor as not referenced. The safest comments where to place copyright information (or other info that needs to be kept in the output) are comments attached to toplevel nodes. ### The `unsafe` `compress` option It enables some transformations that *might* break code logic in certain contrived cases, but should be fine for most code. It assumes that standard built-in ECMAScript functions and classes have not been altered or replaced. You might want to try it on your own code; it should reduce the minified size. Some examples of the optimizations made when this option is enabled: - `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[ 1, 2, 3 ]` - `new Object()` → `{}` - `String(exp)` or `exp.toString()` → `"" + exp` - `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` - `"foo bar".substr(4)` → `"bar"` ### Conditional compilation You can use the `--define` (`-d`) switch in order to declare global variables that Terser will assume to be constants (unless defined in scope). For example if you pass `--define DEBUG=false` then, coupled with dead code removal Terser will discard the following from the output: ```javascript if (DEBUG) { console.log("debug stuff"); } ``` You can specify nested constants in the form of `--define env.DEBUG=false`. Terser will warn about the condition being always false and about dropping unreachable code; for now there is no option to turn off only this specific warning, you can pass `warnings=false` to turn off *all* warnings. Another way of doing that is to declare your globals as constants in a separate file and include it into the build. For example you can have a `build/defines.js` file with the following: ```javascript var DEBUG = false; var PRODUCTION = true; // etc. ``` and build your code like this: terser build/defines.js js/foo.js js/bar.js... -c Terser will notice the constants and, since they cannot be altered, it will evaluate references to them to the value itself and drop unreachable code as usual. The build will contain the `const` declarations if you use them. If you are targeting < ES6 environments which does not support `const`, using `var` with `reduce_vars` (enabled by default) should suffice. ### Conditional compilation API You can also use conditional compilation via the programmatic API. With the difference that the property name is `global_defs` and is a compressor property: ```javascript var result = Terser.minify(fs.readFileSync("input.js", "utf8"), { compress: { dead_code: true, global_defs: { DEBUG: false } } }); ``` To replace an identifier with an arbitrary non-constant expression it is necessary to prefix the `global_defs` key with `"@"` to instruct Terser to parse the value as an expression: ```javascript Terser.minify("alert('hello');", { compress: { global_defs: { "@alert": "console.log" } } }).code; // returns: 'console.log("hello");' ``` Otherwise it would be replaced as string literal: ```javascript Terser.minify("alert('hello');", { compress: { global_defs: { "alert": "console.log" } } }).code; // returns: '"console.log"("hello");' ``` ### Using native Terser AST with `minify()` ```javascript // example: parse only, produce native Terser AST var result = Terser.minify(code, { parse: {}, compress: false, mangle: false, output: { ast: true, code: false // optional - faster if false } }); // result.ast contains native Terser AST ``` ```javascript // example: accept native Terser AST input and then compress and mangle // to produce both code and native AST. var result = Terser.minify(ast, { compress: {}, mangle: {}, output: { ast: true, code: true // optional - faster if false } }); // result.ast contains native Terser AST // result.code contains the minified code in string form. ``` ### Working with Terser AST Traversal and transformation of the native AST can be performed through [`TreeWalker`](https://github.com/fabiosantoscode/terser/blob/master/lib/ast.js) and [`TreeTransformer`](https://github.com/fabiosantoscode/terser/blob/master/lib/transform.js) respectively. Largely compatible native AST examples can be found in the original UglifyJS documentation. See: [tree walker](http://lisperator.net/uglifyjs/walk) and [tree transform](http://lisperator.net/uglifyjs/transform). ### ESTree / SpiderMonkey AST Terser has its own abstract syntax tree format; for [practical reasons](http://lisperator.net/blog/uglifyjs-why-not-switching-to-spidermonkey-ast/) we can't easily change to using the SpiderMonkey AST internally. However, Terser now has a converter which can import a SpiderMonkey AST. For example [Acorn][acorn] is a super-fast parser that produces a SpiderMonkey AST. It has a small CLI utility that parses one file and dumps the AST in JSON on the standard output. To use Terser to mangle and compress that: acorn file.js | terser -p spidermonkey -m -c The `-p spidermonkey` option tells Terser that all input files are not JavaScript, but JS code described in SpiderMonkey AST in JSON. Therefore we don't use our own parser in this case, but just transform that AST into our internal AST. ### Use Acorn for parsing More for fun, I added the `-p acorn` option which will use Acorn to do all the parsing. If you pass this option, Terser will `require("acorn")`. Acorn is really fast (e.g. 250ms instead of 380ms on some 650K code), but converting the SpiderMonkey tree that Acorn produces takes another 150ms so in total it's a bit more than just using Terser's own parser. [acorn]: https://github.com/ternjs/acorn [sm-spec]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k ### Terser Fast Minify Mode It's not well known, but whitespace removal and symbol mangling accounts for 95% of the size reduction in minified code for most JavaScript - not elaborate code transforms. One can simply disable `compress` to speed up Terser builds by 3 to 4 times. | d3.js | size | gzip size | time (s) | | --- | ---: | ---: | ---: | | original | 451,131 | 108,733 | - | | [email protected] mangle=false, compress=false | 316,600 | 85,245 | 0.82 | | [email protected] mangle=true, compress=false | 220,216 | 72,730 | 1.45 | | [email protected] mangle=true, compress=true | 212,046 | 70,954 | 5.87 | | [email protected] | 210,713 | 72,140 | 12.64 | | [email protected] | 210,321 | 72,242 | 48.67 | | [email protected] | 210,421 | 72,238 | 14.17 | To enable fast minify mode from the CLI use: ``` terser file.js -m ``` To enable fast minify mode with the API use: ```js Terser.minify(code, { compress: false, mangle: true }); ``` #### Source maps and debugging Various `compress` transforms that simplify, rearrange, inline and remove code are known to have an adverse effect on debugging with source maps. This is expected as code is optimized and mappings are often simply not possible as some code no longer exists. For highest fidelity in source map debugging disable the `compress` option and just use `mangle`. ### Compiler assumptions To allow for better optimizations, the compiler makes various assumptions: - `.toString()` and `.valueOf()` don't have side effects, and for built-in objects they have not been overridden. - `undefined`, `NaN` and `Infinity` have not been externally redefined. - `arguments.callee`, `arguments.caller` and `Function.prototype.caller` are not used. - The code doesn't expect the contents of `Function.prototype.toString()` or `Error.prototype.stack` to be anything in particular. - Getting and setting properties on a plain object does not cause other side effects (using `.watch()` or `Proxy`). - Object properties can be added, removed and modified (not prevented with `Object.defineProperty()`, `Object.defineProperties()`, `Object.freeze()`, `Object.preventExtensions()` or `Object.seal()`). ### Build Tools and Adaptors using Terser https://www.npmjs.com/browse/depended/terser ### Replacing `uglify-es` with `terser` in a project using `yarn` A number of JS bundlers and uglify wrappers are still using buggy versions of `uglify-es` and have not yet upgraded to `terser`. If you are using `yarn` you can add the following alias to your project's `package.json` file: ```js "resolutions": { "uglify-es": "npm:terser" } ``` to use `terser` instead of `uglify-es` in all deeply nested dependencies without changing any code. Note: for this change to take effect you must run the following commands to remove the existing `yarn` lock file and reinstall all packages: ``` $ rm -rf node_modules yarn.lock $ yarn ``` # Reporting issues In the terser CLI we use [source-map-support](https://npmjs.com/source-map-support) to produce good error stacks. In your own app, you're expected to enable source-map-support (read their docs) to have nice stack traces that will make good issues. # README.md Patrons: *note*: You can support this project on patreon: <a target="_blank" rel="nofollow" href="https://www.patreon.com/terser_ecmacomp_maintainer"><img src="https://c5.patreon.com/external/logo/[email protected]" alt="patron" width="100px" height="auto"></a>. Check out PATRONS.md for our first-tier patrons. * CKEditor ![](https://c10.patreonusercontent.com/3/eyJoIjoxMDAsInciOjEwMH0%3D/patreon-media/p/user/15452278/f8548dcf48d740619071e8d614459280/1?token-time=2145916800&token-hash=SIQ54PhIPHv3M7CVz9LxS8_8v4sOw4H304HaXsXj8MM%3D) * 38elements ![](https://c10.patreonusercontent.com/3/eyJ3IjoyMDB9/patreon-media/p/user/12501844/88e7fc5dd62d45c6a5626533bbd48cfb/1?token-time=2145916800&token-hash=c3AsQ5T0IQWic0zKxFHu-bGGQJkXQFvafvJ4bPerFR4%3D) Like FS streams, but with stat on them, and supporting directories and symbolic links, as well as normal files. Also, you can use this to set the stats on a file, even if you don't change its contents, or to create a symlink, etc. So, for example, you can "write" a directory, and it'll call `mkdir`. You can specify a uid and gid, and it'll call `chown`. You can specify a `mtime` and `atime`, and it'll call `utimes`. You can call it a symlink and provide a `linkpath` and it'll call `symlink`. Note that it won't automatically resolve symbolic links. So, if you call `fstream.Reader('/some/symlink')` then you'll get an object that stats and then ends immediately (since it has no data). To follow symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: true })`. There are various checks to make sure that the bytes emitted are the same as the intended size, if the size is set. ## Examples ```javascript fstream .Writer({ path: "path/to/file" , mode: 0755 , size: 6 }) .write("hello\n") .end() ``` This will create the directories if they're missing, and then write `hello\n` into the file, chmod it to 0755, and assert that 6 bytes have been written when it's done. ```javascript fstream .Writer({ path: "path/to/file" , mode: 0755 , size: 6 , flags: "a" }) .write("hello\n") .end() ``` You can pass flags in, if you want to append to a file. ```javascript fstream .Writer({ path: "path/to/symlink" , linkpath: "./file" , SymbolicLink: true , mode: "0755" // octal strings supported }) .end() ``` If isSymbolicLink is a function, it'll be called, and if it returns true, then it'll treat it as a symlink. If it's not a function, then any truish value will make a symlink, or you can set `type: 'SymbolicLink'`, which does the same thing. Note that the linkpath is relative to the symbolic link location, not the parent dir or cwd. ```javascript fstream .Reader("path/to/dir") .pipe(fstream.Writer("path/to/other/dir")) ``` This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other dir exists and isn't a directory, then it'll emit an error. It'll also set the uid, gid, mode, etc. to be identical. In this way, it's more like `rsync -a` than simply a copy. node-gyp ========= ## Node.js native addon build tool `node-gyp` is a cross-platform command-line tool written in Node.js for compiling native addon modules for Node.js. It bundles the [gyp](https://gyp.gsrc.io) project used by the Chromium team and takes away the pain of dealing with the various differences in build platforms. It is the replacement to the `node-waf` program which is removed for node `v0.8`. If you have a native addon for node that still has a `wscript` file, then you should definitely add a `binding.gyp` file to support the latest versions of node. Multiple target versions of node are supported (i.e. `0.8`, ..., `4`, `5`, `6`, etc.), regardless of what version of node is actually installed on your system (`node-gyp` downloads the necessary development files or headers for the target version). ## Features * Easy to use, consistent interface * Same commands to build your module on every platform * Supports multiple target versions of Node Installation ------------ You can install with `npm`: ``` bash $ npm install -g node-gyp ``` You will also need to install: ### On Unix * `python` (`v2.7` recommended, `v3.x.x` is __*not*__ supported) * `make` * A proper C/C++ compiler toolchain, like [GCC](https://gcc.gnu.org) ### On macOS * `python` (`v2.7` recommended, `v3.x.x` is __*not*__ supported) (already installed on macOS) * [Xcode](https://developer.apple.com/xcode/download/) * You also need to install the `Command Line Tools` via Xcode. You can find this under the menu `Xcode -> Preferences -> Locations` (or by running `xcode-select --install` in your Terminal) * This step will install `gcc` and the related toolchain containing `make` ### On Windows #### Option 1 Install all the required tools and configurations using Microsoft's [windows-build-tools](https://github.com/felixrieseberg/windows-build-tools) using `npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator). #### Option 2 Install tools and configuration manually: * Install Visual C++ Build Environment: [Visual Studio Build Tools](https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=BuildTools) (using "Visual C++ build tools" workload) or [Visual Studio 2017 Community](https://visualstudio.microsoft.com/pl/thank-you-downloading-visual-studio/?sku=Community) (using the "Desktop development with C++" workload) * Install [Python 2.7](https://www.python.org/downloads/) (`v3.x.x` is not supported), and run `npm config set python python2.7` (or see below for further instructions on specifying the proper Python version and path.) * Launch cmd, `npm config set msvs_version 2017` If the above steps didn't work for you, please visit [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules) for additional tips. If you have multiple Python versions installed, you can identify which Python version `node-gyp` uses by setting the '--python' variable: ``` bash $ node-gyp --python /path/to/python2.7 ``` If `node-gyp` is called by way of `npm` *and* you have multiple versions of Python installed, then you can set `npm`'s 'python' config key to the appropriate value: ``` bash $ npm config set python /path/to/executable/python2.7 ``` How to Use ---------- To compile your native addon, first go to its root directory: ``` bash $ cd my_node_addon ``` The next step is to generate the appropriate project build files for the current platform. Use `configure` for that: ``` bash $ node-gyp configure ``` Auto-detection fails for Visual C++ Build Tools 2015, so `--msvs_version=2015` needs to be added (not needed when run by npm as configured above): ``` bash $ node-gyp configure --msvs_version=2015 ``` __Note__: The `configure` step looks for the `binding.gyp` file in the current directory to process. See below for instructions on creating the `binding.gyp` file. Now you will have either a `Makefile` (on Unix platforms) or a `vcxproj` file (on Windows) in the `build/` directory. Next invoke the `build` command: ``` bash $ node-gyp build ``` Now you have your compiled `.node` bindings file! The compiled bindings end up in `build/Debug/` or `build/Release/`, depending on the build mode. At this point you can require the `.node` file with Node and run your tests! __Note:__ To create a _Debug_ build of the bindings file, pass the `--debug` (or `-d`) switch when running either the `configure`, `build` or `rebuild` command. The "binding.gyp" file ---------------------- Previously when node had `node-waf` you had to write a `wscript` file. The replacement for that is the `binding.gyp` file, which describes the configuration to build your module in a JSON-like format. This file gets placed in the root of your package, alongside the `package.json` file. A barebones `gyp` file appropriate for building a node addon looks like: ``` python { "targets": [ { "target_name": "binding", "sources": [ "src/binding.cc" ] } ] } ``` Some additional resources for addons and writing `gyp` files: * ["Going Native" a nodeschool.io tutorial](http://nodeschool.io/#goingnative) * ["Hello World" node addon example](https://github.com/nodejs/node/tree/master/test/addons/hello-world) * [gyp user documentation](https://gyp.gsrc.io/docs/UserDocumentation.md) * [gyp input format reference](https://gyp.gsrc.io/docs/InputFormatReference.md) * [*"binding.gyp" files out in the wild* wiki page](https://github.com/nodejs/node-gyp/wiki/%22binding.gyp%22-files-out-in-the-wild) Commands -------- `node-gyp` responds to the following commands: | **Command** | **Description** |:--------------|:--------------------------------------------------------------- | `help` | Shows the help dialog | `build` | Invokes `make`/`msbuild.exe` and builds the native addon | `clean` | Removes the `build` directory if it exists | `configure` | Generates project build files for the current platform | `rebuild` | Runs `clean`, `configure` and `build` all in a row | `install` | Installs node header files for the given version | `list` | Lists the currently installed node header versions | `remove` | Removes the node header files for the given version Command Options -------- `node-gyp` accepts the following command options: | **Command** | **Description** |:----------------------------------|:------------------------------------------ | `-j n`, `--jobs n` | Run make in parallel | `--target=v6.2.1` | Node version to build for (default=process.version) | `--silly`, `--loglevel=silly` | Log all progress to console | `--verbose`, `--loglevel=verbose` | Log most progress to console | `--silent`, `--loglevel=silent` | Don't log anything to console | `debug`, `--debug` | Make Debug build (default=Release) | `--release`, `--no-debug` | Make Release build | `-C $dir`, `--directory=$dir` | Run command in different directory | `--make=$make` | Override make command (e.g. gmake) | `--thin=yes` | Enable thin static libraries | `--arch=$arch` | Set target architecture (e.g. ia32) | `--tarball=$path` | Get headers from a local tarball | `--devdir=$path` | SDK download directory (default=~/.node-gyp) | `--ensure` | Don't reinstall headers if already present | `--dist-url=$url` | Download header tarball from custom URL | `--proxy=$url` | Set HTTP proxy for downloading header tarball | `--cafile=$cafile` | Override default CA chain (to download tarball) | `--nodedir=$path` | Set the path to the node source code | `--python=$path` | Set path to the python (2) binary | `--msvs_version=$version` | Set Visual Studio version (win) | `--solution=$solution` | Set Visual Studio Solution version (win) Configuration -------- __`node-gyp` responds to environment variables or `npm` configuration__ 1. Environment variables take the form `npm_config_OPTION_NAME` for any of the options listed above (dashes in option names should be replaced by underscores). These work also when `node-gyp` is invoked directly: `$ export npm_config_devdir=/tmp/.gyp` or on Windows `> set npm_config_devdir=c:\temp\.gyp` 2. As `npm` configuration, variables take the form `OPTION_NAME`. This way only works when `node-gyp` is executed by `npm`: `$ npm config set [--global] devdir /tmp/.gyp` `$ npm i buffertools` License ------- (The MIT License) Copyright (c) 2012 Nathan Rajlich &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [python-v2.7.10]: https://www.python.org/downloads/release/python-2710/ [msvc2013]: https://www.microsoft.com/en-gb/download/details.aspx?id=44914 [win7sdk]: https://www.microsoft.com/en-us/download/details.aspx?id=8279 [compiler update for the Windows SDK 7.1]: https://www.microsoft.com/en-us/download/details.aspx?id=4422 validate-npm-package-license ============================ Give me a string and I'll tell you if it's a valid npm package license string. ```javascript var valid = require('validate-npm-package-license'); ``` SPDX license identifiers are valid license strings: ```javascript var assert = require('assert'); var validSPDXExpression = { validForNewPackages: true, validForOldPackages: true, spdx: true }; assert.deepEqual(valid('MIT'), validSPDXExpression); assert.deepEqual(valid('BSD-2-Clause'), validSPDXExpression); assert.deepEqual(valid('Apache-2.0'), validSPDXExpression); assert.deepEqual(valid('ISC'), validSPDXExpression); ``` The function will return a warning and suggestion for nearly-correct license identifiers: ```javascript assert.deepEqual( valid('Apache 2.0'), { validForOldPackages: false, validForNewPackages: false, warnings: [ 'license should be ' + 'a valid SPDX license expression (without "LicenseRef"), ' + '"UNLICENSED", or ' + '"SEE LICENSE IN <filename>"', 'license is similar to the valid expression "Apache-2.0"' ] } ); ``` SPDX expressions are valid, too ... ```javascript // Simple SPDX license expression for dual licensing assert.deepEqual( valid('(GPL-3.0-only OR BSD-2-Clause)'), validSPDXExpression ); ``` ... except if they contain `LicenseRef`: ```javascript var warningAboutLicenseRef = { validForOldPackages: false, validForNewPackages: false, spdx: true, warnings: [ 'license should be ' + 'a valid SPDX license expression (without "LicenseRef"), ' + '"UNLICENSED", or ' + '"SEE LICENSE IN <filename>"', ] }; assert.deepEqual( valid('LicenseRef-Made-Up'), warningAboutLicenseRef ); assert.deepEqual( valid('(MIT OR LicenseRef-Made-Up)'), warningAboutLicenseRef ); ``` If you can't describe your licensing terms with standardized SPDX identifiers, put the terms in a file in the package and point users there: ```javascript assert.deepEqual( valid('SEE LICENSE IN LICENSE.txt'), { validForNewPackages: true, validForOldPackages: true, inFile: 'LICENSE.txt' } ); assert.deepEqual( valid('SEE LICENSE IN license.md'), { validForNewPackages: true, validForOldPackages: true, inFile: 'license.md' } ); ``` If there aren't any licensing terms, use `UNLICENSED`: ```javascript var unlicensed = { validForNewPackages: true, validForOldPackages: true, unlicensed: true }; assert.deepEqual(valid('UNLICENSED'), unlicensed); assert.deepEqual(valid('UNLICENCED'), unlicensed); ``` # minimatch A minimal matching utility. [![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. It works by converting glob expressions into JavaScript `RegExp` objects. ## Usage ```javascript var minimatch = require("minimatch") minimatch("bar.foo", "*.foo") // true! minimatch("bar.foo", "*.bar") // false! minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! ``` ## Features Supports these glob features: * Brace Expansion * Extended glob matching * "Globstar" `**` matching See: * `man sh` * `man bash` * `man 3 fnmatch` * `man 5 gitignore` ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. ```javascript var Minimatch = require("minimatch").Minimatch var mm = new Minimatch(pattern, options) ``` ### Properties * `pattern` The original pattern the minimatch object represents. * `options` The options supplied to the constructor. * `set` A 2-dimensional array of regexp or string expressions. Each row in the array corresponds to a brace-expanded pattern. Each item in the row corresponds to a single path-part. For example, the pattern `{a,b/c}/d` would expand to a set of patterns like: [ [ a, d ] , [ b, c, d ] ] If a portion of the pattern doesn't have any "magic" in it (that is, it's something like `"foo"` rather than `fo*o?`), then it will be left as a string rather than converted to a regular expression. * `regexp` Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. * `negate` True if the pattern is negated. * `comment` True if the pattern is a comment. * `empty` True if the pattern is `""`. ### Methods * `makeRe` Generate the `regexp` member if necessary, and return it. Will return `false` if the pattern is invalid. * `match(fname)` Return true if the filename matches the pattern, or false otherwise. * `matchOne(fileArray, patternArray, partial)` Take a `/`-split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. All other methods are internal, and will be called as necessary. ### minimatch(path, pattern, options) Main export. Tests a path against the pattern using the options. ```javascript var isJS = minimatch(file, "*.js", { matchBase: true }) ``` ### minimatch.filter(pattern, options) Returns a function that tests its supplied argument, suitable for use with `Array.filter`. Example: ```javascript var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) ``` ### minimatch.match(list, pattern, options) Match against the list of files, in the style of fnmatch or glob. If nothing is matched, and options.nonull is set, then return a list containing the pattern itself. ```javascript var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) ``` ### minimatch.makeRe(pattern, options) Make a regular expression object from the pattern. ## Options All options are `false` by default. ### debug Dump a ton of stuff to stderr. ### nobrace Do not expand `{a,b}` and `{1..3}` brace sets. ### noglobstar Disable `**` matching against multiple folder names. ### dot Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` is set. ### noext Disable "extglob" style patterns like `+(a|b)`. ### nocase Perform a case-insensitive match. ### nonull When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. ### matchBase If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. ### nocomment Suppress the behavior of treating `#` at the start of a pattern as a comment. ### nonegate Suppress the behavior of treating a leading `!` character as negation. ### flipNegate Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) ## Comparisons to other fnmatch/glob implementations While strict compliance with the existing standards is a worthwhile goal, some discrepancies exist between minimatch and other implementations, and are intentional. If the pattern starts with a `!` character, then it is negated. Set the `nonegate` flag to suppress this behavior, and treat leading `!` characters normally. This is perhaps relevant if you wish to start the pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` characters at the start of a pattern will negate the pattern multiple times. If a pattern starts with `#`, then it is treated as a comment, and will not match anything. Use `\#` to match a literal `#` at the start of a line, or set the `nocomment` flag to suppress this behavior. The double-star character `**` is supported by default, unless the `noglobstar` flag is set. This is supported in the manner of bsdglob and bash 4.1, where `**` only has special significance if it is the only thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but `a/**b` will not. If an escaped pattern has no matches, and the `nonull` flag is set, then minimatch.match returns the pattern as-provided, rather than interpreting the character escapes. For example, `minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than `"*a?"`. This is akin to setting the `nullglob` option in bash, except that it does not resolve escaped pattern characters. If brace expansion is not disabled, then it is performed before any other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Why use this? 1. [it's fast](#benchmarks) | [optimizations](#optimizations) 2. [better type checking](#better-type-checking) ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Release history ### v4.0.0 **Added** * `promise` support ### v5.0.0 **Added** * `Set Iterator` and `Map Iterator` support **Fixed** * Now returns `generatorfunction` for generator functions ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` 4. There is no reason to make the code in a microlib as terse as possible, just to win points for making it shorter. It's always better to favor performant code over terse code. You will always only be using a single `require()` statement to use the library anyway, regardless of how the code is written. ## Better type checking kind-of is more correct than other type checking libs I've looked at. For example, here are some differing results from other popular libs: ### [typeof](https://github.com/CodingFu/typeof) lib Incorrectly tests instances of custom constructors (pretty common): ```js var typeOf = require('typeof'); function Test() {} console.log(typeOf(new Test())); //=> 'test' ``` Returns `object` instead of `arguments`: ```js function foo() { console.log(typeOf(arguments)) //=> 'object' } foo(); ``` ### [type-of](https://github.com/ForbesLindesay/type-of) lib Incorrectly returns `object` for generator functions, buffers, `Map`, `Set`, `WeakMap` and `WeakSet`: ```js function * foo() {} console.log(typeOf(foo)); //=> 'object' console.log(typeOf(new Buffer(''))); //=> 'object' console.log(typeOf(new Map())); //=> 'object' console.log(typeOf(new Set())); //=> 'object' console.log(typeOf(new WeakMap())); //=> 'object' console.log(typeOf(new WeakSet())); //=> 'object' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). <details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` <details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` <details> ### Related projects You might also be interested in these projects: * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 82 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [aretecode](https://github.com/aretecode) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | | 1 | [charlike](https://github.com/charlike) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on October 13, 2017._ # md5.js [![NPM Package](https://img.shields.io/npm/v/md5.js.svg?style=flat-square)](https://www.npmjs.org/package/md5.js) [![Build Status](https://img.shields.io/travis/crypto-browserify/md5.js.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/md5.js) [![Dependency status](https://img.shields.io/david/crypto-browserify/md5.js.svg?style=flat-square)](https://david-dm.org/crypto-browserify/md5.js#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `md5` on pure JavaScript. From [NIST SP 800-131A][1]: *md5 is no longer acceptable where collision resistance is required such as digital signatures.* ## Example ```js var MD5 = require('md5.js') console.log(new MD5().update('42').digest('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 var md5stream = new MD5() md5stream.end('42') console.log(md5stream.read().toString('hex')) // => a1d0c6e83f027327d8461063f4ac58a6 ``` ## LICENSE [MIT](LICENSE) [1]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![chat][chat]][chat-url] <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> <h1>Style Loader</h1> <p>Adds CSS to the DOM by injecting a <code>&lt;style&gt;</code> tag</p> </div> <h2 align="center">Install</h2> ```bash npm install style-loader --save-dev ``` <h2 align="center">Usage</h2> It's recommended to combine `style-loader` with the [`css-loader`](https://github.com/webpack/css-loader) **component.js** ```js import style from './file.css' ``` **webpack.config.js** ```js { module: { rules: [ { test: /\.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" } ] } ] } } ``` #### `Locals (CSS Modules)` When using [local scoped CSS](https://github.com/webpack/css-loader#css-scope) the module exports the generated identifiers (locals). **component.js** ```js import style from './file.css' style.className === "z849f98ca812" ``` ### `Url` It's also possible to add a URL `<link href="path/to/file.css" rel="stylesheet">` instead of inlining the CSS `{String}` with `<style></style>` tag. ```js import url from 'file.css' ``` **webpack.config.js** ```js { module: { rules: [ { test: /\.css$/, use: [ { loader: "style-loader/url" }, { loader: "file-loader" } ] } ] } } ``` ```html <link rel="stylesheet" href="path/to/file.css"> ``` > ℹ️ Source maps and assets referenced with `url`: when style loader is used with `{ options: { sourceMap: true } }` option, the CSS modules will be generated as `Blob`s, so relative paths don't work (they would be relative to `chrome:blob` or `chrome:devtools`). In order for assets to maintain correct paths setting `output.publicPath` property of webpack configuration must be set, so that absolute paths are generated. Alternatively you can enable the `convertToAbsoluteUrls` option mentioned above. ### `Useable` The `style-loader` injects the styles lazily making them useable on-demand via `style.use()` / `style.unuse()` By convention the `Reference Counter API` should be bound to `.useable.css` and the `.css` should be loaded with basic `style-loader` usage.(similar to other file types, i.e. `.useable.less` and `.less`). **webpack.config.js** ```js { module: { rules: [ { test: /\.css$/, use: [ { loader: "style-loader" }, { loader: "css-loader" }, ], }, { test: /\.useable\.css$/, use: [ { loader: "style-loader/useable" }, { loader: "css-loader" }, ], }, ], }, } ``` #### `Reference Counter API` **component.js** ```js import style from './file.css' style.use(); // = style.ref(); style.unuse(); // = style.unref(); ``` Styles are not added on `import/require()`, but instead on call to `use`/`ref`. Styles are removed from page if `unuse`/`unref` is called exactly as often as `use`/`ref`. > ⚠️ Behavior is undefined when `unuse`/`unref` is called more often than `use`/`ref`. Don't do that. <h2 align="center">Options</h2> |Name|Type|Default|Description| |:--:|:--:|:-----:|:----------| |**`hmr`**|`{Boolean}`|`true`|Enable/disable Hot Module Replacement (HMR), if disabled no HMR Code will be added (good for non local development/production)| |**`base`** |`{Number}`|`true`|Set module ID base (DLLPlugin)| |**`attrs`**|`{Object}`|`{}`|Add custom attrs to `<style></style>`| |**`transform`** |`{Function}`|`false`|Transform/Conditionally load CSS by passing a transform/condition function| |**`insertAt`**|`{String\|Object}`|`bottom`|Inserts `<style></style>` at the given position| |**`insertInto`**|`{String\|Function}`|`<head>`|Inserts `<style></style>` into the given position| |**`singleton`**|`{Boolean}`|`undefined`|Reuses a single `<style></style>` element, instead of adding/removing individual elements for each required module.| |**`sourceMap`**|`{Boolean}`|`false`|Enable/Disable Sourcemaps| |**`convertToAbsoluteUrls`**|`{Boolean}`|`false`|Converts relative URLs to absolute urls, when source maps are enabled| ### `hmr` Enable/disable Hot Module Replacement (HMR), if disabled no HMR Code will be added. This could be used for non local development and production. **webpack.config.js** ```js { loader: 'style-loader', options: { hmr: false } } ``` ### `base` This setting is primarily used as a workaround for [css clashes](https://github.com/webpack-contrib/style-loader/issues/163) when using one or more [DllPlugin](https://robertknight.github.io/posts/webpack-dll-plugins/)'s. `base` allows you to prevent either the *app*'s css (or *DllPlugin2*'s css) from overwriting *DllPlugin1*'s css by specifying a css module id base which is greater than the range used by *DllPlugin1* e.g.: **webpack.dll1.config.js** ```js { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ``` **webpack.dll2.config.js** ```js { test: /\.css$/, use: [ { loader: 'style-loader', options: { base: 1000 } }, 'css-loader' ] } ``` **webpack.app.config.js** ``` { test: /\.css$/, use: [ { loader: 'style-loader', options: { base: 2000 } }, 'css-loader' ] } ``` ### `attrs` If defined, style-loader will attach given attributes with their values on `<style>` / `<link>` element. **component.js** ```js import style from './file.css' ``` **webpack.config.js** ```js { test: /\.css$/, use: [ { loader: 'style-loader', options: { attrs: { id: 'id' } } } { loader: 'css-loader' } ] } ``` ```html <style id="id"></style> ``` #### `Url` **component.js** ```js import link from './file.css' ``` **webpack.config.js** ```js { test: /\.css$/, use: [ { loader: 'style-loader/url', options: { attrs: { id: 'id' } } } { loader: 'file-loader' } ] } ``` ### `transform` A `transform` is a function that can modify the css just before it is loaded into the page by the style-loader. This function will be called on the css that is about to be loaded and the return value of the function will be loaded into the page instead of the original css. If the return value of the `transform` function is falsy, the css will not be loaded into the page at all. > ⚠️ In case you are using ES Module syntax in `tranform.js` then, you **need to transpile** it or otherwise it will throw an `{Error}`. **webpack.config.js** ```js { loader: 'style-loader', options: { transform: 'path/to/transform.js' } } ``` **transform.js** ```js module.exports = function (css) { // Here we can change the original css const transformed = css.replace('.classNameA', '.classNameB') return transformed } ``` #### `Conditional` **webpack.config.js** ```js { loader: 'style-loader', options: { transform: 'path/to/conditional.js' } } ``` **conditional.js** ```js module.exports = function (css) { // If the condition is matched load [and transform] the CSS if (css.includes('something I want to check')) { return css; } // If a falsy value is returned, the CSS won't be loaded return false } ``` ### `insertAt` By default, the style-loader appends `<style>` elements to the end of the style target, which is the `<head>` tag of the page unless specified by `insertInto`. This will cause CSS created by the loader to take priority over CSS already present in the target. To insert style elements at the beginning of the target, set this query parameter to 'top', e.g **webpack.config.js** ```js { loader: 'style-loader', options: { insertAt: 'top' } } ``` A new `<style>` element can be inserted before a specific element by passing an object, e.g. **webpack.config.js** ```js { loader: 'style-loader', options: { insertAt: { before: '#id' } } } ``` ### `insertInto` By default, the style-loader inserts the `<style>` elements into the `<head>` tag of the page. If you want the tags to be inserted somewhere else you can specify a CSS selector for that element here. If you target an [IFrame](https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement) make sure you have sufficient access rights, the styles will be injected into the content document head. You can also pass function to override default behavior and insert styles in your container, e.g **webpack.config.js** ```js { loader: 'style-loader', options: { insertInto: () => document.querySelector("#root"), } } ``` Using function you can insert the styles into a [ShadowRoot](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot), e.g **webpack.config.js** ```js { loader: 'style-loader', options: { insertInto: () => document.querySelector("#root").shadowRoot, } } ``` ### `singleton` If defined, the style-loader will reuse a single `<style></style>` element, instead of adding/removing individual elements for each required module. > ℹ️ This option is on by default in IE9, which has strict limitations on the number of style tags allowed on a page. You can enable or disable it with the singleton option. **webpack.config.js** ```js { loader: 'style-loader', options: { singleton: true } } ``` ### `sourceMap` Enable/Disable source map loading **webpack.config.js** ```js { loader: 'style-loader', options: { sourceMap: true } } ``` ### `convertToAbsoluteUrls` If convertToAbsoluteUrls and sourceMaps are both enabled, relative urls will be converted to absolute urls right before the css is injected into the page. This resolves [an issue](https://github.com/webpack/style-loader/pull/96) where relative resources fail to load when source maps are enabled. You can enable it with the convertToAbsoluteUrls option. **webpack.config.js** ```js { loader: 'style-loader', options: { sourceMap: true, convertToAbsoluteUrls: true } } ``` <h2 align="center">Maintainers</h2> <table> <tbody> <tr> <td align="center"> <a href="https://github.com/bebraw"> <img width="150" height="150" src="https://github.com/bebraw.png?v=3&s=150"> </br> Juho Vepsäläinen </a> </td> <td align="center"> <a href="https://github.com/d3viant0ne"> <img width="150" height="150" src="https://github.com/d3viant0ne.png?v=3&s=150"> </br> Joshua Wiens </a> </td> <td align="center"> <a href="https://github.com/sapegin"> <img width="150" height="150" src="https://github.com/sapegin.png?v=3&s=150"> </br> Artem Sapegin </a> </td> <td align="center"> <a href="https://github.com/michael-ciniawsky"> <img width="150" height="150" src="https://github.com/michael-ciniawsky.png?v=3&s=150"> </br> Michael Ciniawsky </a> </td> <td align="center"> <a href="https://github.com/evilebottnawi"> <img width="150" height="150" src="https://github.com/evilebottnawi.png?v=3&s=150"> </br> Alexander Krasnoyarov </a> </td> </tr> <tr> <td align="center"> <a href="https://github.com/sokra"> <img width="150" height="150" src="https://github.com/sokra.png?v=3&s=150"> </br> Tobias Koppers </a> </td> <td align="center"> <a href="https://github.com/SpaceK33z"> <img width="150" height="150" src="https://github.com/SpaceK33z.png?v=3&s=150"> </br> Kees Kluskens </a> </td> <tr> <tbody> </table> [npm]: https://img.shields.io/npm/v/style-loader.svg [npm-url]: https://npmjs.com/package/style-loader [node]: https://img.shields.io/node/v/style-loader.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack/style-loader.svg [deps-url]: https://david-dm.org/webpack/file-loader [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack This folder contains entry points for all `core-js` features with dependencies. It's the recommended way for usage only required features. # ansi-colors [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/ansi-colors.svg?style=flat)](https://www.npmjs.com/package/ansi-colors) [![NPM monthly downloads](https://img.shields.io/npm/dm/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![NPM total downloads](https://img.shields.io/npm/dt/ansi-colors.svg?style=flat)](https://npmjs.org/package/ansi-colors) [![Linux Build Status](https://img.shields.io/travis/doowb/ansi-colors.svg?style=flat&label=Travis)](https://travis-ci.org/doowb/ansi-colors) > Easily add ANSI colors to your text and symbols in the terminal. A faster drop-in replacement for chalk, kleur and turbocolor (without the dependencies and rendering bugs). Please consider following this project's author, [Brian Woodward](https://github.com/doowb), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save ansi-colors ``` ![image](https://user-images.githubusercontent.com/383994/39635445-8a98a3a6-4f8b-11e8-89c1-068c45d4fff8.png) ## Why use this? ansi-colors is _the fastest Node.js library for terminal styling_. A more performant drop-in replacement for chalk, with no dependencies. * _Blazing fast_ - Fastest terminal styling library in node.js, 10-20x faster than chalk! * _Drop-in replacement_ for [chalk](https://github.com/chalk/chalk). * _No dependencies_ (Chalk has 7 dependencies in its tree!) * _Safe_ - Does not modify the `String.prototype` like [colors](https://github.com/Marak/colors.js). * Supports [nested colors](#nested-colors), **and does not have the [nested styling bug](#nested-styling-bug) that is present in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur)**. * Supports [chained colors](#chained-colors). * [Toggle color support](#toggle-color-support) on or off. ## Usage ```js const c = require('ansi-colors'); console.log(c.red('This is a red string!')); console.log(c.green('This is a red string!')); console.log(c.cyan('This is a cyan string!')); console.log(c.yellow('This is a yellow string!')); ``` ![image](https://user-images.githubusercontent.com/383994/39653848-a38e67da-4fc0-11e8-89ae-98c65ebe9dcf.png) ## Chained colors ```js console.log(c.bold.red('this is a bold red message')); console.log(c.bold.yellow.italic('this is a bold yellow italicized message')); console.log(c.green.bold.underline('this is a bold green underlined message')); ``` ![image](https://user-images.githubusercontent.com/383994/39635780-7617246a-4f8c-11e8-89e9-05216cc54e38.png) ## Nested colors ```js console.log(c.yellow(`foo ${c.red.bold('red')} bar ${c.cyan('cyan')} baz`)); ``` ![image](https://user-images.githubusercontent.com/383994/39635817-8ed93d44-4f8c-11e8-8afd-8c3ea35f5fbe.png) ### Nested styling bug `ansi-colors` does not have the nested styling bug found in [colorette](https://github.com/jorgebucaran/colorette), [chalk](https://github.com/chalk/chalk), and [kleur](https://github.com/lukeed/kleur). ```js const { bold, red } = require('ansi-styles'); console.log(bold(`foo ${red.dim('bar')} baz`)); const colorette = require('colorette'); console.log(colorette.bold(`foo ${colorette.red(colorette.dim('bar'))} baz`)); const kleur = require('kleur'); console.log(kleur.bold(`foo ${kleur.red.dim('bar')} baz`)); const chalk = require('chalk'); console.log(chalk.bold(`foo ${chalk.red.dim('bar')} baz`)); ``` **Results in the following** (sans icons and labels) ![image](https://user-images.githubusercontent.com/383994/47280326-d2ee0580-d5a3-11e8-9611-ea6010f0a253.png) ## Toggle color support Easily enable/disable colors. ```js const c = require('ansi-colors'); // disable colors manually c.enabled = false; // or use a library to automatically detect support c.enabled = require('color-support').hasBasic; console.log(c.red('I will only be colored red if the terminal supports colors')); ``` ## Strip ANSI codes Use the `.unstyle` method to strip ANSI codes from a string. ```js console.log(c.unstyle(c.blue.bold('foo bar baz'))); //=> 'foo bar baz' ``` ## Available styles **Note** that bright and bright-background colors are not always supported. | Colors | Background Colors | Bright Colors | Bright Background Colors | | ------- | ----------------- | ------------- | ------------------------ | | black | bgBlack | blackBright | bgBlackBright | | red | bgRed | redBright | bgRedBright | | green | bgGreen | greenBright | bgGreenBright | | yellow | bgYellow | yellowBright | bgYellowBright | | blue | bgBlue | blueBright | bgBlueBright | | magenta | bgMagenta | magentaBright | bgMagentaBright | | cyan | bgCyan | cyanBright | bgCyanBright | | white | bgWhite | whiteBright | bgWhiteBright | | gray | | | | | grey | | | | _(`gray` is the U.S. spelling, `grey` is more commonly used in the Canada and U.K.)_ ### Style modifiers * dim * **bold** * hidden * _italic_ * underline * inverse * ~~strikethrough~~ * reset ## Performance **Libraries tested** * ansi-colors v3.0.4 * chalk v2.4.1 ### Mac > MacBook Pro, Intel Core i7, 2.3 GHz, 16 GB. **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.915ms` * chalk - `12.437ms` **Benchmarks** ``` # All Colors ansi-colors x 173,851 ops/sec ±0.42% (91 runs sampled) chalk x 9,944 ops/sec ±2.53% (81 runs sampled))) # Chained colors ansi-colors x 20,791 ops/sec ±0.60% (88 runs sampled) chalk x 2,111 ops/sec ±2.34% (83 runs sampled) # Nested colors ansi-colors x 59,304 ops/sec ±0.98% (92 runs sampled) chalk x 4,590 ops/sec ±2.08% (82 runs sampled) ``` ### Windows > Windows 10, Intel Core i7-7700k CPU @ 4.2 GHz, 32 GB **Load time** Time it takes to load the first time `require()` is called: * ansi-colors - `1.494ms` * chalk - `11.523ms` **Benchmarks** ``` # All Colors ansi-colors x 193,088 ops/sec ±0.51% (95 runs sampled)) chalk x 9,612 ops/sec ±3.31% (77 runs sampled))) # Chained colors ansi-colors x 26,093 ops/sec ±1.13% (94 runs sampled) chalk x 2,267 ops/sec ±2.88% (80 runs sampled)) # Nested colors ansi-colors x 67,747 ops/sec ±0.49% (93 runs sampled) chalk x 4,446 ops/sec ±3.01% (82 runs sampled)) ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [ansi-wrap](https://www.npmjs.com/package/ansi-wrap): Create ansi colors by passing the open and close codes. | [homepage](https://github.com/jonschlinkert/ansi-wrap "Create ansi colors by passing the open and close codes.") * [strip-color](https://www.npmjs.com/package/strip-color): Strip ANSI color codes from a string. No dependencies. | [homepage](https://github.com/jonschlinkert/strip-color "Strip ANSI color codes from a string. No dependencies.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 42 | [doowb](https://github.com/doowb) | | 38 | [jonschlinkert](https://github.com/jonschlinkert) | | 6 | [lukeed](https://github.com/lukeed) | | 2 | [Silic0nS0ldier](https://github.com/Silic0nS0ldier) | | 1 | [dwieeb](https://github.com/dwieeb) | | 1 | [jorgebucaran](https://github.com/jorgebucaran) | | 1 | [madhavarshney](https://github.com/madhavarshney) | | 1 | [chapterjason](https://github.com/chapterjason) | ### Author **Brian Woodward** * [GitHub Profile](https://github.com/doowb) * [Twitter Profile](https://twitter.com/doowb) * [LinkedIn Profile](https://linkedin.com/in/woodwardbrian) Please consider supporting me on Patreon, or [start your own Patreon page](https://patreon.com/invite/bxpbvm)! <a href="https://www.patreon.com/jonschlinkert"> <img src="https://c5.patreon.com/external/logo/[email protected]" height="50"> </a> ### License Copyright © 2019, [Brian Woodward](https://github.com/doowb). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 03, 2019._ unique-filename =============== Generate a unique filename for use in temporary directories or caches. ``` var uniqueFilename = require('unique-filename') // returns something like: /tmp/912ec803b2ce49e4a541068d495ab570 var randomTmpfile = uniqueFilename(os.tmpdir()) // returns something like: /tmp/my-test-912ec803b2ce49e4a541068d495ab570 var randomPrefixedTmpfile = uniqueFilename(os.tmpdir(), 'my-test') var uniqueTmpfile = uniqueFilename('/tmp', 'testing', '/my/thing/to/uniq/on') ``` ### uniqueFilename(*dir*, *fileprefix*, *uniqstr*) → String Returns the full path of a unique filename that looks like: `dir/prefix-7ddd44c0` or `dir/7ddd44c0` *dir* – The path you want the filename in. `os.tmpdir()` is a good choice for this. *fileprefix* – A string to append prior to the unique part of the filename. The parameter is required if *uniqstr* is also passed in but is otherwise optional and can be `undefined`/`null`/`''`. If present and not empty then this string plus a hyphen are prepended to the unique part. *uniqstr* – Optional, if not passed the unique part of the resulting filename will be random. If passed in it will be generated from this string in a reproducable way. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # SPDY Server for node.js [![Build Status](https://travis-ci.org/spdy-http2/node-spdy.svg?branch=master)](http://travis-ci.org/spdy-http2/node-spdy) [![NPM version](https://badge.fury.io/js/spdy.svg)](http://badge.fury.io/js/spdy) [![dependencies Status](https://david-dm.org/spdy-http2/node-spdy/status.svg?style=flat-square)](https://david-dm.org/spdy-http2/node-spdy) [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/) [![Waffle](https://img.shields.io/badge/track-waffle-blue.svg?style=flat-square)](https://waffle.io/spdy-http2/node-spdy) With this module you can create [HTTP2][0] / [SPDY][1] servers in node.js with natural http module interface and fallback to regular https (for browsers that don't support neither HTTP2, nor SPDY yet). This module named `spdy` but it [provides](https://github.com/indutny/node-spdy/issues/269#issuecomment-239014184) support for both http/2 (h2) and spdy (2,3,3.1). Also, `spdy` is compatible with Express. ## Usage ### Examples Server: ```javascript var spdy = require('spdy'), fs = require('fs'); var options = { // Private key key: fs.readFileSync(__dirname + '/keys/spdy-key.pem'), // Fullchain file or cert file (prefer the former) cert: fs.readFileSync(__dirname + '/keys/spdy-fullchain.pem'), // **optional** SPDY-specific options spdy: { protocols: [ 'h2', 'spdy/3.1', ..., 'http/1.1' ], plain: false, // **optional** // Parse first incoming X_FORWARDED_FOR frame and put it to the // headers of every request. // NOTE: Use with care! This should not be used without some proxy that // will *always* send X_FORWARDED_FOR 'x-forwarded-for': true, connection: { windowSize: 1024 * 1024, // Server's window size // **optional** if true - server will send 3.1 frames on 3.0 *plain* spdy autoSpdy31: false } } }; var server = spdy.createServer(options, function(req, res) { res.writeHead(200); res.end('hello world!'); }); server.listen(3000); ``` Client: ```javascript var spdy = require('spdy'); var https = require('https'); var agent = spdy.createAgent({ host: 'www.google.com', port: 443, // Optional SPDY options spdy: { plain: false, ssl: true, // **optional** send X_FORWARDED_FOR 'x-forwarded-for': '127.0.0.1' } }); https.get({ host: 'www.google.com', agent: agent }, function(response) { console.log('yikes'); // Here it goes like with any other node.js HTTP request // ... // And once we're done - we may close TCP connection to server // NOTE: All non-closed requests will die! agent.close(); }).end(); ``` Please note that if you use a custom agent, by default all connection-level errors will result in an uncaught exception. To handle these errors subscribe to the `error` event and re-emit the captured error: ```javascript var agent = spdy.createAgent({ host: 'www.google.com', port: 443 }).once('error', function (err) { this.emit(err); }); ``` #### Push streams It is possible to initiate [PUSH_PROMISE][5] to send content to clients _before_ the client requests it. ```javascript spdy.createServer(options, function(req, res) { var stream = res.push('/main.js', { status: 200, // optional method: 'GET', // optional request: { accept: '*/*' }, response: { 'content-type': 'application/javascript' } }); stream.on('error', function() { }); stream.end('alert("hello from push stream!");'); res.end('<script src="/main.js"></script>'); }).listen(3000); ``` [PUSH_PROMISE][5] may be sent using the `push()` method on the current response object. The signature of the `push()` method is: `.push('/some/relative/url', { request: {...}, response: {...} }, callback)` Second argument contains headers for both PUSH_PROMISE and emulated response. `callback` will receive two arguments: `err` (if any error is happened) and a [Duplex][4] stream as the second argument. Client usage: ```javascript var agent = spdy.createAgent({ /* ... */ }); var req = http.get({ host: 'www.google.com', agent: agent }, function(response) { }); req.on('push', function(stream) { stream.on('error', function(err) { // Handle error }); // Read data from stream }); ``` NOTE: You're responsible for the `stream` object once given it in `.push()` callback or `push` event. Hence ignoring `error` event on it will result in uncaught exception and crash your program. #### Trailing headers Server usage: ```javascript function (req, res) { // Send trailing headers to client res.addTrailers({ header1: 'value1', header2: 'value2' }); // On client's trailing headers req.on('trailers', function(headers) { // ... }); } ``` Client usage: ```javascript var req = http.request({ agent: spdyAgent, /* ... */ }).function (res) { // On server's trailing headers res.on('trailers', function(headers) { // ... }); }); req.write('stuff'); req.addTrailers({ /* ... */ }); req.end(); ``` #### Options All options supported by [tls][2] work with node-spdy. Additional options may be passed via `spdy` sub-object: * `plain` - if defined, server will ignore NPN and ALPN data and choose whether to use spdy or plain http by looking at first data packet. * `ssl` - if `false` and `options.plain` is `true`, `http.Server` will be used as a `base` class for created server. * `maxChunk` - if set and non-falsy, limits number of bytes sent in one DATA chunk. Setting it to non-zero value is recommended if you care about interleaving of outgoing data from multiple different streams. (defaults to 8192) * `protocols` - list of NPN/ALPN protocols to use (default is: `['h2','spdy/3.1', 'spdy/3', 'spdy/2','http/1.1', 'http/1.0']`) * `protocol` - use specific protocol if no NPN/ALPN ex In addition, * `maxStreams` - set "[maximum concurrent streams][3]" protocol option ### API API is compatible with `http` and `https` module, but you can use another function as base class for SPDYServer. ```javascript spdy.createServer( [base class constructor, i.e. https.Server], { /* keys and options */ }, // <- the only one required argument [request listener] ).listen([port], [host], [callback]); ``` Request listener will receive two arguments: `request` and `response`. They're both instances of `http`'s `IncomingMessage` and `OutgoingMessage`. But three custom properties are added to both of them: `isSpdy`, `spdyVersion`. `isSpdy` is `true` when the request was processed using HTTP2/SPDY protocols, it is `false` in case of HTTP/1.1 fallback. `spdyVersion` is either of: `2`, `3`, `3.1`, or `4` (for HTTP2). #### Contributors * [Fedor Indutny](https://github.com/indutny) * [Chris Strom](https://github.com/eee-c) * [François de Metz](https://github.com/francois2metz) * [Ilya Grigorik](https://github.com/igrigorik) * [Roberto Peon](https://github.com/grmocg) * [Tatsuhiro Tsujikawa](https://github.com/tatsuhiro-t) * [Jesse Cravens](https://github.com/jessecravens) #### LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: https://http2.github.io/ [1]: http://www.chromium.org/spdy [2]: http://nodejs.org/docs/latest/api/tls.html#tls.createServer [3]: https://httpwg.github.io/specs/rfc7540.html#SETTINGS_MAX_CONCURRENT_STREAMS [4]: https://iojs.org/api/stream.html#stream_class_stream_duplex [5]: https://httpwg.github.io/specs/rfc7540.html#PUSH_PROMISE # Handle Thing [![Build Status](https://travis-ci.org/spdy-http2/handle-thing.svg?branch=master)](http://travis-ci.org/spdy-http2/handle-thing) [![NPM version](https://badge.fury.io/js/handle-thing.svg)](http://badge.fury.io/js/handle-thing) [![dependencies Status](https://david-dm.org/spdy-http2/handle-thing/status.svg?style=flat-square)](https://david-dm.org/spdy-http2/handle-thing) [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/) [![Waffle](https://img.shields.io/badge/track-waffle-blue.svg?style=flat-square)](https://waffle.io/spdy-http2/node-spdy) > Wrap Streams2 instance into a HandleWrap. The right thing when you need it ## Usage ### Examples `soon™` ### API `soon™` ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. SockJS-node Echo example ======================== To run this example, first install dependencies: npm install And run a server: node server.js That will spawn an http server at http://127.0.0.1:9999/ which will serve both html (served from the current directory) and also SockJS server (under the [/echo](http://127.0.0.1:9999/echo) path). <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] # webpack-dev-server Use [webpack](https://webpack.js.org) with a development server that provides live reloading. This should be used for **development only**. It uses [webpack-dev-middleware][middleware-url] under the hood, which provides fast in-memory access to the webpack assets. ## Table of Contents 1. [Getting Started](#getting-started) 2. [Usage](#usage) 3. [Browser Support](#browser-support) 4. [Support](#support) 5. [Contributing](#contributing) 6. [Maintainers](#maintainers) 7. [Attribution](#attribution) 8. [License](#license) ## Getting Started First things first, install the module: ```console npm install webpack-dev-server --save-dev ``` _Note: While you can install and run webpack-dev-server globally, we recommend installing it locally. webpack-dev-server will always use a local installation over a global one._ ## Usage There are two main, recommended methods of using the module: ### With the CLI The easiest way to use it is with the CLI. In the directory where your `webpack.config.js` is, run: ```console node_modules/.bin/webpack-dev-server ``` _**Note**: Many CLI options are available with `webpack-dev-server`. Explore this [link](https://webpack.js.org/configuration/dev-server/)._ ### With NPM Scripts NPM package.json scripts are a convenient and useful means to run locally installed binaries without having to be concerned about their full paths. Simply define a script as such: ```json "scripts": { "start:dev": "webpack-dev-server" } ``` And run the following in your terminal/console: ```console npm run start:dev ``` NPM will automagically reference the binary in `node_modules` for you, and execute the file or command. ### The Result Either method will start a server instance and begin listening for connections from `localhost` on port `8080`. webpack-dev-server is configured by default to support live-reload of files as you edit your assets while the server is running. See [**the documentation**][docs-url] for more use cases and options. ## Browser Support While `webpack-dev-server` transpiles the client (browser) scripts to an ES5 state, the project only officially supports the _last two versions of major browsers_. We simply don't have the resources to support every whacky browser out there. If you find a bug with an obscure / old browser, we would actively welcome a Pull Request to resolve the bug. ## Support We do our best to keep Issues in the repository focused on bugs, features, and needed modifications to the code for the module. Because of that, we ask users with general support, "how-to", or "why isn't this working" questions to try one of the other support channels that are available. Your first-stop-shop for support for webpack-dev-server should by the excellent [documentation][docs-url] for the module. If you see an opportunity for improvement of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a pull request. From there, we encourage users to visit the [webpack Gitter chat][chat-url] and talk to the fine folks there. If your quest for answers comes up dry in chat, head over to [StackOverflow][stack-url] and do a quick search or open a new question. Remember; It's always much easier to answer questions that include your `webpack.config.js` and relevant files! If you're twitter-savvy you can tweet [#webpack][hash-url] with your question and someone should be able to reach out and lend a hand. If you have discovered a :bug:, have a feature suggestion, or would like to see a modification, please feel free to create an issue on Github. _Note: The issue template isn't optional, so please be sure not to remove it, and please fill it out completely._ ## Contributing We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved. ## Attribution This project is heavily inspired by [peerigon/nof5](https://github.com/peerigon/nof5). ## License #### [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/webpack-dev-server.svg [npm-url]: https://npmjs.com/package/webpack-dev-server [node]: https://img.shields.io/node/v/webpack-dev-server.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack/webpack-dev-server.svg [deps-url]: https://david-dm.org/webpack/webpack-dev-server [tests]: http://img.shields.io/travis/webpack/webpack-dev-server.svg [tests-url]: https://travis-ci.org/webpack/webpack-dev-server [cover]: https://codecov.io/gh/webpack/webpack-dev-server/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack/webpack-dev-server [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack [docs-url]: https://webpack.js.org/configuration/dev-server/#devserver [hash-url]: https://twitter.com/search?q=webpack [middleware-url]: https://github.com/webpack/webpack-dev-middleware [stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-server [uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin [wjo-url]: https://github.com/webpack/webpack.js.org atob === | **atob** | [btoa](https://git.coolaj86.com/coolaj86/btoa.js) | [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js) | Sponsored by [ppl](https://ppl.family) Uses `Buffer` to emulate the exact functionality of the browser's atob. Note: Unicode may be handled incorrectly (like the browser). It turns base64-encoded <strong>a</strong>scii data back **to** <strong>b</strong>inary. ```javascript (function () { "use strict"; var atob = require('atob'); var b64 = "SGVsbG8sIFdvcmxkIQ=="; var bin = atob(b64); console.log(bin); // "Hello, World!" }()); ``` ### Need Unicode and Binary Support in the Browser? Check out [unibabel.js](https://git.coolaj86.com/coolaj86/unibabel.js) Changelog ======= * v2.1.0 address a few issues and PRs, update URLs * v2.0.0 provide browser version for ios web workers * v1.2.0 provide (empty) browser version * v1.1.3 add MIT license * v1.1.2 node only LICENSE ======= Code copyright 2012-2018 AJ ONeal Dual-licensed MIT and Apache-2.0 Docs copyright 2012-2018 AJ ONeal Docs released under [Creative Commons](https://git.coolaj86.com/coolaj86/atob.js/blob/master/LICENSE.DOCS). ansi-html [![NPM version](https://badge.fury.io/js/ansi-html.svg)](http://badge.fury.io/js/ansi-html) [![Build Status](https://travis-ci.org/Tjatse/ansi-html.svg?branch=master)](https://travis-ci.org/Tjatse/ansi-html) ========= An elegant lib that converts the chalked (ANSI) text to HTML. # Coverage - All styles of [chalk](https://github.com/sindresorhus/chalk) (100%) and [colors](https://github.com/Marak/colors.js). - There are over **150** randomized test cases under `test`. # Installation ``` $ npm install ansi-html ``` # Usage ```javascript var ansiHTML = require('ansi-html'); var str = ansiHTML('[ANSI_TEXT]'); ``` e.g.: ```javascript var chalk = require('chalk'); var str = chalk.bold.red('foo') + ' bar'; console.log('[ANSI]', str) console.log('[HTML]', ansiHTML(str)); ``` See complete examples under `test` / `examples` directory. # Set Colors ```javascript ansiHTML.setColors({ reset: ['555', '666'], // FOREGROUND-COLOR or [FOREGROUND-COLOR] or [, BACKGROUND-COLOR] or [FOREGROUND-COLOR, BACKGROUND-COLOR] black: 'aaa', // String red: 'bbb', green: 'ccc', yellow: 'ddd', blue: 'eee', magenta: 'fff', cyan: '999', lightgrey: '888', darkgrey: '777' }); ``` # Reset ```javascript ansiHTML.reset(); ``` # Exposed Tags ```javascript var openTags = ansiHTML.tags.open; var closeTags = ansiHTML.tags.close; ``` # Test ``` $ npm install -l $ npm test ``` # repeat-element [![NPM version](https://img.shields.io/npm/v/repeat-element.svg?style=flat)](https://www.npmjs.com/package/repeat-element) [![NPM monthly downloads](https://img.shields.io/npm/dm/repeat-element.svg?style=flat)](https://npmjs.org/package/repeat-element) [![NPM total downloads](https://img.shields.io/npm/dt/repeat-element.svg?style=flat)](https://npmjs.org/package/repeat-element) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/repeat-element.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/repeat-element) > Create an array by repeating the given value n times. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save repeat-element ``` ## Usage ```js const repeat = require('repeat-element'); repeat('a', 5); //=> ['a', 'a', 'a', 'a', 'a'] repeat('a', 1); //=> ['a'] repeat('a', 0); //=> [] repeat(null, 5) //» [ null, null, null, null, null ] repeat({some: 'object'}, 5) //» [ { some: 'object' }, // { some: 'object' }, // { some: 'object' }, // { some: 'object' }, // { some: 'object' } ] repeat(5, 5) //» [ 5, 5, 5, 5, 5 ] ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Contributors | **Commits** | **Contributor** | | --- | --- | | 17 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [LinusU](https://github.com/LinusU) | | 1 | [architectcodes](https://github.com/architectcodes) | ### Author **Jon Schlinkert** * [GitHub Profile](https://github.com/jonschlinkert) * [Twitter Profile](https://twitter.com/jonschlinkert) * [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) ### License Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on August 19, 2018._ # is-extendable [![NPM version](https://img.shields.io/npm/v/is-extendable.svg?style=flat)](https://www.npmjs.com/package/is-extendable) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-extendable.svg?style=flat)](https://npmjs.org/package/is-extendable) [![NPM total downloads](https://img.shields.io/npm/dt/is-extendable.svg?style=flat)](https://npmjs.org/package/is-extendable) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-extendable.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-extendable) > Returns true if a value is a plain object, array or function. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extendable ``` ## Usage ```js var isExtendable = require('is-extendable'); ``` Returns true if the value is any of the following: * array * plain object * function ## Notes All objects in JavaScript can have keys, but it's a pain to check for this, since we ether need to verify that the value is not `null` or `undefined` and: * the value is not a primitive, or * that the object is a plain object, function or array Also note that an `extendable` object is not the same as an [extensible object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), which is one that (in es6) is not sealed, frozen, or marked as non-extensible using `preventExtensions`. ## Release history ### v1.0.0 - 2017/07/20 **Breaking changes** * No longer considers date, regex or error objects to be extendable ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [is-equal-shallow](https://www.npmjs.com/package/is-equal-shallow): Does a shallow comparison of two objects, returning false if the keys or values differ. | [homepage](https://github.com/jonschlinkert/is-equal-shallow "Does a shallow comparison of two objects, returning false if the keys or values differ.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 20, 2017._ <div align="center"> <a href="https://github.com/webpack/webpack-cli"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> <h1 align="center">webpack CLI</h1> <p align="center"> The official CLI of webpack </p> <br> [![npm](https://img.shields.io/npm/v/webpack-cli.svg)](https://www.npmjs.com/package/webpack-cli) [![Build Status](https://travis-ci.org/webpack/webpack-cli.svg)](https://travis-ci.org/webpack/webpack-cli) [![Build2 Status](https://dev.azure.com/webpack/webpack/_apis/build/status/webpack.webpack-cli)](https://dev.azure.com/webpack/webpack/_build/latest?definitionId=4) [![deps][deps]][deps-url] [![Code Climate](https://codeclimate.com/github/webpack/webpack-cli/badges/gpa.svg)](https://codeclimate.com/github/webpack/webpack-cli) [![chat on gitter](https://badges.gitter.im/webpack/webpack.svg)](https://gitter.im/webpack/webpack) [![Install Size](https://packagephobia.now.sh/badge?p=webpack-cli)](https://packagephobia.now.sh/result?p=webpack-cli) [![npm](https://img.shields.io/npm/dw/webpack-cli.svg)](https://www.npmjs.com/package/webpack-cli) [![lerna](https://img.shields.io/badge/maintained%20with-lerna-cc00ff.svg)](https://lernajs.io/) * [About](#about) - [How to install](#how-to-install) * [Getting Started](#getting-started) * [webpack CLI Scaffolds](#webpack-cli-scaffolds) * Commands - [`webpack-cli init`](./packages/init/README.md#webpack-cli-init) - [`webpack-cli add`](./packages/add/README.md#webpack-cli-add) - [`webpack-cli info`](./packages/info/README.md#webpack-cli-info) - [`webpack-cli migrate`](./packages/migrate/README.md#webpack-cli-migrate) - [`webpack-cli remove`](./packages/remove/README.md#webpack-cli-remove) - [`webpack-cli generate-plugin`](./packages/generate-plugin/README.md#webpack-cli-generate-plugin) - [`webpack-cli generate-loader`](./packages/generate-loader/README.md#webpack-cli-generate-loader) - [`webpack-cli serve`](./packages/serve/README.md#webpack-cli-serve) - [`webpack-cli update`](./packages/update/README.md#webpack-cli-update) * [webpack.config.js](https://webpack.js.org/concepts/configuration/) * [Contributing and Internal Documentation](#contributing-and-internal-documentation) ## About webpack CLI provides a flexible set of commands for developers to increase speed when setting up a custom webpack project. As of webpack v4, webpack is not expecting a configuration file, but often developers want to create a more custom webpack configuration based on their use-cases and needs. webpack CLI addresses these needs by providing a set of tools to improve the setup of custom webpack configuration. ### How to install When you have followed the [Getting Started](https://webpack.js.org/guides/getting-started/) guide of webpack then webpack CLI is already installed! Otherwise `npm install --save-dev webpack-cli` or `yarn add webpack-cli --dev` will install it. ### Commands Supporting developers is an important task for webpack CLI. Thus, webpack CLI provides different commands for many common tasks. We organize webpack CLI as a [multi-package repository](https://github.com/lerna/lerna). Every command has a dedicated subfolder in the `packages` Folder. ## Getting started When you have followed the [Getting Started](https://webpack.js.org/guides/getting-started/) guide of webpack then webpack CLI is already installed! Otherwise, you would need to install webpack CLI and the packages you want to use. If we want to use the `init` functionality to create a new `webpack.config.js` configuration file: ```sh npm i webpack-cli @webpack-cli/init npx webpack-cli init ``` You will answer many questions when running the `init` so webpack CLI can provide the best fitting configuration. ## webpack CLI Scaffolds With v3 of webpack CLI, we introduced scaffolding as an integral part of the CLI. Our goal is to simplify the creation of webpack configurations for different purposes. Additionally, sharing such solutions with the community is beneficial and with webpack webpack's we want to allow this. We provide `webpack-scaffold` as a utility suite for creating these scaffolds. It contains functions that could be of use for creating an scaffold yourself. You can read more about [Scaffolding](./SCAFFOLDING.md) or check out the example project [How do I compose a webpack-scaffold?](https://github.com/evenstensberg/webpack-scaffold-demo). ## Contributing and Internal Documentation The webpack family welcomes any contributor, small or big. We are happy to elaborate, guide you through the source code and find issues you might want to work on! To get started have a look at our [documentation on contributing](./.github/CONTRIBUTING.md). [deps]: https://img.shields.io/david/webpack/webpack.svg [deps-url]: https://david-dm.org/webpack/webpack-cli # npmlog The logger util that npm uses. This logger is very basic. It does the logging for npm. It supports custom levels and colored output. By default, logs are written to stderr. If you want to send log messages to outputs other than streams, then you can change the `log.stream` member, or you can just listen to the events that it emits, and do whatever you want with them. # Installation ```console npm install npmlog --save ``` # Basic Usage ```javascript var log = require('npmlog') // additional stuff ---------------------------+ // message ----------+ | // prefix ----+ | | // level -+ | | | // v v v v log.info('fyi', 'I have a kitty cat: %j', myKittyCat) ``` ## log.level * {String} The level to display logs at. Any logs at or above this level will be displayed. The special level `silent` will prevent anything from being displayed ever. ## log.record * {Array} An array of all the log messages that have been entered. ## log.maxRecordSize * {Number} The maximum number of records to keep. If log.record gets bigger than 10% over this value, then it is sliced down to 90% of this value. The reason for the 10% window is so that it doesn't have to resize a large array on every log entry. ## log.prefixStyle * {Object} A style object that specifies how prefixes are styled. (See below) ## log.headingStyle * {Object} A style object that specifies how the heading is styled. (See below) ## log.heading * {String} Default: "" If set, a heading that is printed at the start of every line. ## log.stream * {Stream} Default: `process.stderr` The stream where output is written. ## log.enableColor() Force colors to be used on all messages, regardless of the output stream. ## log.disableColor() Disable colors on all messages. ## log.enableProgress() Enable the display of log activity spinner and progress bar ## log.disableProgress() Disable the display of a progress bar ## log.enableUnicode() Force the unicode theme to be used for the progress bar. ## log.disableUnicode() Disable the use of unicode in the progress bar. ## log.setGaugeTemplate(template) Set a template for outputting the progress bar. See the [gauge documentation] for details. [gauge documentation]: https://npmjs.com/package/gauge ## log.setGaugeThemeset(themes) Select a themeset to pick themes from for the progress bar. See the [gauge documentation] for details. ## log.pause() Stop emitting messages to the stream, but do not drop them. ## log.resume() Emit all buffered messages that were written while paused. ## log.log(level, prefix, message, ...) * `level` {String} The level to emit the message at * `prefix` {String} A string prefix. Set to "" to skip. * `message...` Arguments to `util.format` Emit a log message at the specified level. ## log\[level](prefix, message, ...) For example, * log.silly(prefix, message, ...) * log.verbose(prefix, message, ...) * log.info(prefix, message, ...) * log.http(prefix, message, ...) * log.warn(prefix, message, ...) * log.error(prefix, message, ...) Like `log.log(level, prefix, message, ...)`. In this way, each level is given a shorthand, so you can do `log.info(prefix, message)`. ## log.addLevel(level, n, style, disp) * `level` {String} Level indicator * `n` {Number} The numeric level * `style` {Object} Object with fg, bg, inverse, etc. * `disp` {String} Optional replacement for `level` in the output. Sets up a new level with a shorthand function and so forth. Note that if the number is `Infinity`, then setting the level to that will cause all log messages to be suppressed. If the number is `-Infinity`, then the only way to show it is to enable all log messages. ## log.newItem(name, todo, weight) * `name` {String} Optional; progress item name. * `todo` {Number} Optional; total amount of work to be done. Default 0. * `weight` {Number} Optional; the weight of this item relative to others. Default 1. This adds a new `are-we-there-yet` item tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `Tracker` object. ## log.newStream(name, todo, weight) This adds a new `are-we-there-yet` stream tracker to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerStream` object. ## log.newGroup(name, weight) This adds a new `are-we-there-yet` tracker group to the progress tracker. The object returned has the `log[level]` methods but is otherwise an `are-we-there-yet` `TrackerGroup` object. # Events Events are all emitted with the message object. * `log` Emitted for all messages * `log.<level>` Emitted for all messages with the `<level>` level. * `<prefix>` Messages with prefixes also emit their prefix as an event. # Style Objects Style objects can have the following fields: * `fg` {String} Color for the foreground text * `bg` {String} Color for the background * `bold`, `inverse`, `underline` {Boolean} Set the associated property * `bell` {Boolean} Make a noise (This is pretty annoying, probably.) # Message Objects Every log event is emitted with a message object, and the `log.record` list contains all of them that have been created. They have the following fields: * `id` {Number} * `level` {String} * `prefix` {String} * `message` {String} Result of `util.format()` * `messageRaw` {Array} Arguments to `util.format()` # Blocking TTYs We use [`set-blocking`](https://npmjs.com/package/set-blocking) to set stderr and stdout blocking if they are tty's and have the setBlocking call. This is a work around for an issue in early versions of Node.js 6.x, which made stderr and stdout non-blocking on OSX. (They are always blocking Windows and were never blocking on Linux.) `npmlog` needs them to be blocking so that it can allow output to stdout and stderr to be interlaced. # is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-glob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-glob) > Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-glob ``` You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). ## Usage ```js var isGlob = require('is-glob'); ``` **True** Patterns that have glob characters or regex patterns will return `true`: ```js isGlob('!foo.js'); isGlob('*.js'); isGlob('**/abc.js'); isGlob('abc/*.js'); isGlob('abc/(aaa|bbb).js'); isGlob('abc/[a-z].js'); isGlob('abc/{a,b}.js'); isGlob('abc/?.js'); //=> true ``` Extglobs ```js isGlob('abc/@(a).js'); isGlob('abc/!(a).js'); isGlob('abc/+(a).js'); isGlob('abc/*(a).js'); isGlob('abc/?(a).js'); //=> true ``` **False** Escaped globs or extglobs return `false`: ```js isGlob('abc/\\@(a).js'); isGlob('abc/\\!(a).js'); isGlob('abc/\\+(a).js'); isGlob('abc/\\*(a).js'); isGlob('abc/\\?(a).js'); isGlob('\\!foo.js'); isGlob('\\*.js'); isGlob('\\*\\*/abc.js'); isGlob('abc/\\*.js'); isGlob('abc/\\(aaa|bbb).js'); isGlob('abc/\\[a-z].js'); isGlob('abc/\\{a,b}.js'); isGlob('abc/\\?.js'); //=> false ``` Patterns that do not have glob patterns return `false`: ```js isGlob('abc.js'); isGlob('abc/def/ghi.js'); isGlob('foo.js'); isGlob('abc/@.js'); isGlob('abc/+.js'); isGlob(); isGlob(null); //=> false ``` Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): ```js isGlob(['**/*.js']); isGlob(['foo.js']); //=> false ``` ## About ### Related projects * [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") * [base](https://www.npmjs.com/package/base): base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting… [more](https://github.com/node-base/base) | [homepage](https://github.com/node-base/base "base is the foundation for creating modular, unit testable and highly pluggable node.js applications, starting with a handful of common methods, like `set`, `get`, `del` and `use`.") * [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") * [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor**<br/> | | --- | --- | | 40 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [tuvistavie](https://github.com/tuvistavie) | ### Building docs _(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ To generate the readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install -g verb verb-generate-readme && verb ``` ### Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ### License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/is-glob/blob/master/LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ # EE First [![NPM version][npm-image]][npm-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![Gittip][gittip-image]][gittip-url] Get the first event in a set of event emitters and event pairs, then clean up after itself. ## Install ```sh $ npm install ee-first ``` ## API ```js var first = require('ee-first') ``` ### first(arr, listener) Invoke `listener` on the first event from the list specified in `arr`. `arr` is an array of arrays, with each array in the format `[ee, ...event]`. `listener` will be called only once, the first time any of the given events are emitted. If `error` is one of the listened events, then if that fires first, the `listener` will be given the `err` argument. The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the first argument emitted from an `error` event, if applicable; `ee` is the event emitter that fired; `event` is the string event name that fired; and `args` is an array of the arguments that were emitted on the event. ```js var ee1 = new EventEmitter() var ee2 = new EventEmitter() first([ [ee1, 'close', 'end', 'error'], [ee2, 'error'] ], function (err, ee, event, args) { // listener invoked }) ``` #### .cancel() The group of listeners can be cancelled before being invoked and have all the event listeners removed from the underlying event emitters. ```js var thunk = first([ [ee1, 'close', 'end', 'error'], [ee2, 'error'] ], function (err, ee, event, args) { // listener invoked }) // cancel and clean up thunk.cancel() ``` [npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square [npm-url]: https://npmjs.org/package/ee-first [github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square [github-url]: https://github.com/jonathanong/ee-first/tags [travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square [travis-url]: https://travis-ci.org/jonathanong/ee-first [coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square [coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master [license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square [license-url]: LICENSE.md [downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square [downloads-url]: https://npmjs.org/package/ee-first [gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square [gittip-url]: https://www.gittip.com/jonathanong/ # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` ## Install Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Usage > es5, browser and es6 ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Boolean(true)); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf(new Number(42)); //=> 'number' kindOf('str'); //=> 'string' kindOf(new String('str')); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([]); //=> 'array' kindOf([1, 2, 3]); //=> 'array' kindOf(new Array()); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'function' kindOf(new Function()); //=> 'function' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). Note that performaces is slower for es6 features `Map`, `WeakMap`, `Set` and `WeakSet`. ```bash #1: array current x 23,329,397 ops/sec ±0.82% (94 runs sampled) lib-type-of x 4,170,273 ops/sec ±0.55% (94 runs sampled) lib-typeof x 9,686,935 ops/sec ±0.59% (98 runs sampled) #2: boolean current x 27,197,115 ops/sec ±0.85% (94 runs sampled) lib-type-of x 3,145,791 ops/sec ±0.73% (97 runs sampled) lib-typeof x 9,199,562 ops/sec ±0.44% (99 runs sampled) #3: date current x 20,190,117 ops/sec ±0.86% (92 runs sampled) lib-type-of x 5,166,970 ops/sec ±0.74% (94 runs sampled) lib-typeof x 9,610,821 ops/sec ±0.50% (96 runs sampled) #4: function current x 23,855,460 ops/sec ±0.60% (97 runs sampled) lib-type-of x 5,667,740 ops/sec ±0.54% (100 runs sampled) lib-typeof x 10,010,644 ops/sec ±0.44% (100 runs sampled) #5: null current x 27,061,047 ops/sec ±0.97% (96 runs sampled) lib-type-of x 13,965,573 ops/sec ±0.62% (97 runs sampled) lib-typeof x 8,460,194 ops/sec ±0.61% (97 runs sampled) #6: number current x 25,075,682 ops/sec ±0.53% (99 runs sampled) lib-type-of x 2,266,405 ops/sec ±0.41% (98 runs sampled) lib-typeof x 9,821,481 ops/sec ±0.45% (99 runs sampled) #7: object current x 3,348,980 ops/sec ±0.49% (99 runs sampled) lib-type-of x 3,245,138 ops/sec ±0.60% (94 runs sampled) lib-typeof x 9,262,952 ops/sec ±0.59% (99 runs sampled) #8: regex current x 21,284,827 ops/sec ±0.72% (96 runs sampled) lib-type-of x 4,689,241 ops/sec ±0.43% (100 runs sampled) lib-typeof x 8,957,593 ops/sec ±0.62% (98 runs sampled) #9: string current x 25,379,234 ops/sec ±0.58% (96 runs sampled) lib-type-of x 3,635,148 ops/sec ±0.76% (93 runs sampled) lib-typeof x 9,494,134 ops/sec ±0.49% (98 runs sampled) #10: undef current x 27,459,221 ops/sec ±1.01% (93 runs sampled) lib-type-of x 14,360,433 ops/sec ±0.52% (99 runs sampled) lib-typeof x 23,202,868 ops/sec ±0.59% (94 runs sampled) ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` ## About ### Related projects * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 59 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on May 16, 2017._ Like `chown -R`. Takes the same arguments as `fs.chown()` iMurmurHash.js ============== An incremental implementation of the MurmurHash3 (32-bit) hashing algorithm for JavaScript based on [Gary Court's implementation](https://github.com/garycourt/murmurhash-js) with [kazuyukitanimura's modifications](https://github.com/kazuyukitanimura/murmurhash-js). This version works significantly faster than the non-incremental version if you need to hash many small strings into a single hash, since string concatenation (to build the single string to pass the non-incremental version) is fairly costly. In one case tested, using the incremental version was about 50% faster than concatenating 5-10 strings and then hashing. Installation ------------ To use iMurmurHash in the browser, [download the latest version](https://raw.github.com/jensyt/imurmurhash-js/master/imurmurhash.min.js) and include it as a script on your site. ```html <script type="text/javascript" src="/scripts/imurmurhash.min.js"></script> <script> // Your code here, access iMurmurHash using the global object MurmurHash3 </script> ``` --- To use iMurmurHash in Node.js, install the module using NPM: ```bash npm install imurmurhash ``` Then simply include it in your scripts: ```javascript MurmurHash3 = require('imurmurhash'); ``` Quick Example ------------- ```javascript // Create the initial hash var hashState = MurmurHash3('string'); // Incrementally add text hashState.hash('more strings'); hashState.hash('even more strings'); // All calls can be chained if desired hashState.hash('and').hash('some').hash('more'); // Get a result hashState.result(); // returns 0xe4ccfe6b ``` Functions --------- ### MurmurHash3 ([string], [seed]) Get a hash state object, optionally initialized with the given _string_ and _seed_. _Seed_ must be a positive integer if provided. Calling this function without the `new` keyword will return a cached state object that has been reset. This is safe to use as long as the object is only used from a single thread and no other hashes are created while operating on this one. If this constraint cannot be met, you can use `new` to create a new state object. For example: ```javascript // Use the cached object, calling the function again will return the same // object (but reset, so the current state would be lost) hashState = MurmurHash3(); ... // Create a new object that can be safely used however you wish. Calling the // function again will simply return a new state object, and no state loss // will occur, at the cost of creating more objects. hashState = new MurmurHash3(); ``` Both methods can be mixed however you like if you have different use cases. --- ### MurmurHash3.prototype.hash (string) Incrementally add _string_ to the hash. This can be called as many times as you want for the hash state object, including after a call to `result()`. Returns `this` so calls can be chained. --- ### MurmurHash3.prototype.result () Get the result of the hash as a 32-bit positive integer. This performs the tail and finalizer portions of the algorithm, but does not store the result in the state object. This means that it is perfectly safe to get results and then continue adding strings via `hash`. ```javascript // Do the whole string at once MurmurHash3('this is a test string').result(); // 0x70529328 // Do part of the string, get a result, then the other part var m = MurmurHash3('this is a'); m.result(); // 0xbfc4f834 m.hash(' test string').result(); // 0x70529328 (same as above) ``` --- ### MurmurHash3.prototype.reset ([seed]) Reset the state object for reuse, optionally using the given _seed_ (defaults to 0 like the constructor). Returns `this` so calls can be chained. --- License (MIT) ------------- Copyright (c) 2013 Gary Court, Jens Taylor Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #object.getownpropertydescriptors <sup>[![Version Badge][npm-version-svg]][package-url]</sup> [![Build Status][travis-svg]][travis-url] [![dependency status][deps-svg]][deps-url] [![dev dependency status][dev-deps-svg]][dev-deps-url] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][npm-badge-png]][package-url] [![browser support][testling-svg]][testling-url] An ES2017 spec-compliant shim for `Object.getOwnPropertyDescriptors` that works in ES5. Invoke its "shim" method to shim `Object.getOwnPropertyDescriptors` if it is unavailable, and if `Object.getOwnPropertyDescriptor` is available. This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://github.com/tc39/ecma262/pull/582). ## Example ```js var getDescriptors = require('object.getownpropertydescriptors'); var assert = require('assert'); var obj = { normal: Infinity }; var enumDescriptor = { enumerable: false, writable: false, configurable: true, value: true }; var writableDescriptor = { enumerable: true, writable: true, configurable: true, value: 42 }; var symbol = Symbol(); var symDescriptor = { enumerable: true, writable: true, configurable: false, value: [symbol] }; Object.defineProperty(obj, 'enumerable', enumDescriptor); Object.defineProperty(obj, 'writable', writableDescriptor); Object.defineProperty(obj, 'symbol', symDescriptor); var descriptors = getDescriptors(obj); assert.deepEqual(descriptors, { normal: { enumerable: true, writable: true, configurable: true, value: Infinity }, enumerable: enumDescriptor, writable: writableDescriptor, symbol: symDescriptor }); ``` ```js var getDescriptors = require('object.getownpropertydescriptors'); var assert = require('assert'); /* when Object.getOwnPropertyDescriptors is not present */ delete Object.getOwnPropertyDescriptors; var shimmedDescriptors = getDescriptors.shim(); assert.equal(shimmedDescriptors, getDescriptors); assert.deepEqual(shimmedDescriptors(obj), getDescriptors(obj)); ``` ```js var getDescriptors = require('object.getownpropertydescriptors'); var assert = require('assert'); /* when Object.getOwnPropertyDescriptors is present */ var shimmedDescriptors = getDescriptors.shim(); assert.notEqual(shimmedDescriptors, getDescriptors); assert.deepEqual(shimmedDescriptors(obj), getDescriptors(obj)); ``` ## Tests Simply clone the repo, `npm install`, and run `npm test` [package-url]: https://npmjs.org/package/object.getownpropertydescriptors [npm-version-svg]: http://versionbadg.es/ljharb/object.getownpropertydescriptors.svg [travis-svg]: https://travis-ci.org/ljharb/object.getownpropertydescriptors.svg [travis-url]: https://travis-ci.org/ljharb/object.getownpropertydescriptors [deps-svg]: https://david-dm.org/ljharb/object.getownpropertydescriptors.svg [deps-url]: https://david-dm.org/ljharb/object.getownpropertydescriptors [dev-deps-svg]: https://david-dm.org/ljharb/object.getownpropertydescriptors/dev-status.svg [dev-deps-url]: https://david-dm.org/ljharb/object.getownpropertydescriptors#info=devDependencies [testling-svg]: https://ci.testling.com/ljharb/object.getownpropertydescriptors.png [testling-url]: https://ci.testling.com/ljharb/object.getownpropertydescriptors [npm-badge-png]: https://nodei.co/npm/object.getownpropertydescriptors.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/object.getownpropertydescriptors.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/object.getownpropertydescriptors.svg [downloads-url]: http://npm-stat.com/charts.html?package=object.getownpropertydescriptors # is-data-descriptor [![NPM version](https://img.shields.io/npm/v/is-data-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-data-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-data-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-data-descriptor) > Returns true if a value has the characteristics of a valid JavaScript data descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-data-descriptor ``` ## Usage ```js var isDataDesc = require('is-data-descriptor'); ``` ## Examples `true` when the descriptor has valid properties with valid values. ```js // `value` can be anything isDataDesc({value: 'foo'}) isDataDesc({value: function() {}}) isDataDesc({value: true}) //=> true ``` `false` when not an object ```js isDataDesc('a') //=> false isDataDesc(null) //=> false isDataDesc([]) //=> false ``` `false` when the object has invalid properties ```js isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', get: function(){}}) //=> false isDataDesc({get: function(){}, value: 'foo'}) //=> false ``` `false` when a value is not the correct type ```js isDataDesc({value: 'foo', enumerable: 'foo'}) //=> false isDataDesc({value: 'foo', configurable: 'foo'}) //=> false isDataDesc({value: 'foo', writable: 'foo'}) //=> false ``` ## Valid properties The only valid data descriptor properties are the following: * `configurable` (required) * `enumerable` (required) * `value` (optional) * `writable` (optional) To be a valid data descriptor, either `value` or `writable` must be defined. **Invalid properties** A descriptor may have additional _invalid_ properties (an error will **not** be thrown). ```js var foo = {}; Object.defineProperty(foo, 'bar', { enumerable: true, whatever: 'blah', // invalid, but doesn't cause an error get: function() { return 'baz'; } }); console.log(foo.bar); //=> 'baz' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 21 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # `react-is` This package allows you to test arbitrary values and see if they're a particular React element type. ## Installation ```sh # Yarn yarn add react-is # NPM npm install react-is ``` ## Usage ### Determining if a Component is Valid ```js import React from "react"; import * as ReactIs from "react-is"; class ClassComponent extends React.Component { render() { return React.createElement("div"); } } const StatelessComponent = () => React.createElement("div"); const ForwardRefComponent = React.forwardRef((props, ref) => React.createElement(Component, { forwardedRef: ref, ...props }) ); const Context = React.createContext(false); ReactIs.isValidElementType("div"); // true ReactIs.isValidElementType(ClassComponent); // true ReactIs.isValidElementType(StatelessComponent); // true ReactIs.isValidElementType(ForwardRefComponent); // true ReactIs.isValidElementType(Context.Provider); // true ReactIs.isValidElementType(Context.Consumer); // true ReactIs.isValidElementType(React.createFactory("div")); // true ``` ### Determining an Element's Type #### ConcurrentMode ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isConcurrentMode(<React.unstable_ConcurrentMode />); // true ReactIs.typeOf(<React.unstable_ConcurrentMode />) === ReactIs.ConcurrentMode; // true ``` #### Context ```js import React from "react"; import * as ReactIs from 'react-is'; const ThemeContext = React.createContext("blue"); ReactIs.isContextConsumer(<ThemeContext.Consumer />); // true ReactIs.isContextProvider(<ThemeContext.Provider />); // true ReactIs.typeOf(<ThemeContext.Provider />) === ReactIs.ContextProvider; // true ReactIs.typeOf(<ThemeContext.Consumer />) === ReactIs.ContextConsumer; // true ``` #### Element ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isElement(<div />); // true ReactIs.typeOf(<div />) === ReactIs.Element; // true ``` #### Fragment ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isFragment(<></>); // true ReactIs.typeOf(<></>) === ReactIs.Fragment; // true ``` #### Portal ```js import React from "react"; import ReactDOM from "react-dom"; import * as ReactIs from 'react-is'; const div = document.createElement("div"); const portal = ReactDOM.createPortal(<div />, div); ReactIs.isPortal(portal); // true ReactIs.typeOf(portal) === ReactIs.Portal; // true ``` #### StrictMode ```js import React from "react"; import * as ReactIs from 'react-is'; ReactIs.isStrictMode(<React.StrictMode />); // true ReactIs.typeOf(<React.StrictMode />) === ReactIs.StrictMode; // true ``` killable ======== Keeps track of a server's open sockets so they can be destroyed at a moment's notice. This way, the server connection can be killed very fast. Installation ------------ ``` npm install killable ``` Example usage ------------- Using express: ('server' in the example is just an ``http.server``, so other frameworks or pure Node should work just as well.) ```javascript var killable = require('killable'); var app = require('express')(); var server; app.route('/', function (req, res, next) { res.send('Server is going down NOW!'); server.kill(function () { //the server is down when this is called. That won't take long. }); }); var server = app.listen(8080); killable(server); ``` API --- The ``killable`` module is callable. When you call it on a Node ``http.Server`` object, it will add a ``server.kill()`` method on it. It returns the server object. ``server.kill([callback])`` closes all open sockets and calls ``server.close()``, to which the ``callback`` is passed on. Inspired by: http://stackoverflow.com/a/14636625 License ------- ISC # isarray `Array#isArray` for older browsers. [![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) [![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) [![browser support](https://ci.testling.com/juliangruber/isarray.png) ](https://ci.testling.com/juliangruber/isarray) ## Usage ```js var isArray = require('isarray'); console.log(isArray([])); // => true console.log(isArray({})); // => false ``` ## Installation With [npm](http://npmjs.org) do ```bash $ npm install isarray ``` Then bundle for the browser with [browserify](https://github.com/substack/browserify). With [component](http://component.io) do ```bash $ component install juliangruber/isarray ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. are-we-there-yet ---------------- Track complex hiearchies of asynchronous task completion statuses. This is intended to give you a way of recording and reporting the progress of the big recursive fan-out and gather type workflows that are so common in async. What you do with this completion data is up to you, but the most common use case is to feed it to one of the many progress bar modules. Most progress bar modules include a rudamentary version of this, but my needs were more complex. Usage ===== ```javascript var TrackerGroup = require("are-we-there-yet").TrackerGroup var top = new TrackerGroup("program") var single = top.newItem("one thing", 100) single.completeWork(20) console.log(top.completed()) // 0.2 fs.stat("file", function(er, stat) { if (er) throw er var stream = top.newStream("file", stat.size) console.log(top.completed()) // now 0.1 as single is 50% of the job and is 20% complete // and 50% * 20% == 10% fs.createReadStream("file").pipe(stream).on("data", function (chunk) { // do stuff with chunk }) top.on("change", function (name) { // called each time a chunk is read from "file" // top.completed() will start at 0.1 and fill up to 0.6 as the file is read }) }) ``` Shared Methods ============== * var completed = tracker.completed() Implemented in: `Tracker`, `TrackerGroup`, `TrackerStream` Returns the ratio of completed work to work to be done. Range of 0 to 1. * tracker.finish() Implemented in: `Tracker`, `TrackerGroup` Marks the tracker as completed. With a TrackerGroup this marks all of its components as completed. Marks all of the components of this tracker as finished, which in turn means that `tracker.completed()` for this will now be 1. This will result in one or more `change` events being emitted. Events ====== All tracker objects emit `change` events with the following arguments: ``` function (name, completed, tracker) ``` `name` is the name of the tracker that originally emitted the event, or if it didn't have one, the first containing tracker group that had one. `completed` is the percent complete (as returned by `tracker.completed()` method). `tracker` is the tracker object that you are listening for events on. TrackerGroup ============ * var tracker = new TrackerGroup(**name**) * **name** *(optional)* - The name of this tracker group, used in change notifications if the component updating didn't have a name. Defaults to undefined. Creates a new empty tracker aggregation group. These are trackers whose completion status is determined by the completion status of other trackers. * tracker.addUnit(**otherTracker**, **weight**) * **otherTracker** - Any of the other are-we-there-yet tracker objects * **weight** *(optional)* - The weight to give the tracker, defaults to 1. Adds the **otherTracker** to this aggregation group. The weight determines how long you expect this tracker to take to complete in proportion to other units. So for instance, if you add one tracker with a weight of 1 and another with a weight of 2, you're saying the second will take twice as long to complete as the first. As such, the first will account for 33% of the completion of this tracker and the second will account for the other 67%. Returns **otherTracker**. * var subGroup = tracker.newGroup(**name**, **weight**) The above is exactly equivalent to: ```javascript var subGroup = tracker.addUnit(new TrackerGroup(name), weight) ``` * var subItem = tracker.newItem(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subItem = tracker.addUnit(new Tracker(name, todo), weight) ``` * var subStream = tracker.newStream(**name**, **todo**, **weight**) The above is exactly equivalent to: ```javascript var subStream = tracker.addUnit(new TrackerStream(name, todo), weight) ``` * console.log( tracker.debug() ) Returns a tree showing the completion of this tracker group and all of its children, including recursively entering all of the children. Tracker ======= * var tracker = new Tracker(**name**, **todo**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **todo** *(optional)* The amount of work todo (a number). Defaults to 0. Ordinarily these are constructed as a part of a tracker group (via `newItem`). * var completed = tracker.completed() Returns the ratio of completed work to work to be done. Range of 0 to 1. If total work to be done is 0 then it will return 0. * tracker.addWork(**todo**) * **todo** A number to add to the amount of work to be done. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. * tracker.completeWork(**completed**) * **completed** A number to add to the work complete Increase the amount of work complete, thus increasing the completion percentage. Will never increase the work completed past the amount of work todo. That is, percentages > 100% are not allowed. Triggers a `change` event. * tracker.finish() Marks this tracker as finished, tracker.completed() will now be 1. Triggers a `change` event. TrackerStream ============= * var tracker = new TrackerStream(**name**, **size**, **options**) * **name** *(optional)* The name of this counter to report in change events. Defaults to undefined. * **size** *(optional)* The number of bytes being sent through this stream. * **options** *(optional)* A hash of stream options The tracker stream object is a pass through stream that updates an internal tracker object each time a block passes through. It's intended to track downloads, file extraction and other related activities. You use it by piping your data source into it and then using it as your data source. If your data has a length attribute then that's used as the amount of work completed when the chunk is passed through. If it does not (eg, object streams) then each chunk counts as completing 1 unit of work, so your size should be the total number of objects being streamed. * tracker.addWork(**todo**) * **todo** Increase the expected overall size by **todo** bytes. Increases the amount of work to be done, thus decreasing the completion percentage. Triggers a `change` event. tunnel-agent ============ HTTP proxy tunneling agent. Formerly part of mikeal/request, now a standalone module. # global-modules [![NPM version](https://img.shields.io/npm/v/global-modules.svg?style=flat)](https://www.npmjs.com/package/global-modules) [![NPM monthly downloads](https://img.shields.io/npm/dm/global-modules.svg?style=flat)](https://npmjs.org/package/global-modules) [![NPM total downloads](https://img.shields.io/npm/dt/global-modules.svg?style=flat)](https://npmjs.org/package/global-modules) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/global-modules.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/global-modules) > The directory used by npm for globally installed npm modules. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save global-modules ``` ## Usage ```js var globalModules = require('global-modules'); console.log(globalModules); //=> '/usr/local/lib/node_modules' ``` _(Note that this path might be different based on OS or user defined configuration settings)_ ## About ### Related projects * [git-config-path](https://www.npmjs.com/package/git-config-path): Resolve the path to the user's local or global .gitconfig. | [homepage](https://github.com/jonschlinkert/git-config-path "Resolve the path to the user's local or global .gitconfig.") * [global-prefix](https://www.npmjs.com/package/global-prefix): Get the npm global path prefix. | [homepage](https://github.com/jonschlinkert/global-prefix "Get the npm global path prefix.") * [homedir-polyfill](https://www.npmjs.com/package/homedir-polyfill): Node.js os.homedir polyfill for older versions of node.js. | [homepage](https://github.com/doowb/homedir-polyfill "Node.js os.homedir polyfill for older versions of node.js.") * [npm-paths](https://www.npmjs.com/package/npm-paths): Returns an array of unique "npm" directories based on the user's platform and environment. | [homepage](https://github.com/jonschlinkert/npm-paths "Returns an array of unique "npm" directories based on the user's platform and environment.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 14 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [jason-chang](https://github.com/jason-chang) | | 1 | [Kikobeats](https://github.com/Kikobeats) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 28, 2017._ # spdy-transport [![Build Status](https://travis-ci.org/spdy-http2/spdy-transport.svg?branch=master)](http://travis-ci.org/spdy-http2/spdy-transport) [![NPM version](https://badge.fury.io/js/spdy-transport.svg)](http://badge.fury.io/js/spdy-transport) [![dependencies Status](https://david-dm.org/spdy-http2/spdy-transport/status.svg?style=flat-square)](https://david-dm.org/spdy-http2/spdy-transport) [![Standard - JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/) [![Waffle](https://img.shields.io/badge/track-waffle-blue.svg?style=flat-square)](https://waffle.io/spdy-http2/node-spdy) > SPDY/HTTP2 generic transport implementation. ## Usage ```javascript var transport = require('spdy-transport'); // NOTE: socket is some stream or net.Socket instance, may be an argument // of `net.createServer`'s connection handler. var server = transport.connection.create(socket, { protocol: 'http2', isServer: true }); server.on('stream', function(stream) { console.log(stream.method, stream.path, stream.headers); stream.respond(200, { header: 'value' }); stream.on('readable', function() { var chunk = stream.read(); if (!chunk) return; console.log(chunk); }); stream.on('end', function() { console.log('end'); }); // And other node.js Stream APIs // ... }); ``` ## LICENSE This software is licensed under the MIT License. Copyright Fedor Indutny, 2015. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [0]: http://json.org/ [1]: http://github.com/indutny/bud-backend [2]: https://github.com/nodejs/io.js [3]: https://github.com/libuv/libuv [4]: http://openssl.org/ oauth-sign ========== OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module. ## Supported Method Signatures - HMAC-SHA1 - HMAC-SHA256 - RSA-SHA1 - PLAINTEXT # Forge [![npm package](https://nodei.co/npm/node-forge.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/node-forge/) [![Build status](https://img.shields.io/travis/digitalbazaar/forge.svg?branch=master)](https://travis-ci.org/digitalbazaar/forge) A native implementation of [TLS][] (and various other cryptographic tools) in [JavaScript][]. Introduction ------------ The Forge software is a fully native implementation of the [TLS][] protocol in JavaScript, a set of cryptography utilities, and a set of tools for developing Web Apps that utilize many network resources. Performance ------------ Forge is fast. Benchmarks against other popular JavaScript cryptography libraries can be found here: * http://dominictarr.github.io/crypto-bench/ * http://cryptojs.altervista.org/test/simulate-threading-speed_test.html Documentation ------------- * [Introduction](#introduction) * [Performance](#performance) * [Installation](#installation) * [Testing](#testing) * [Contributing](#contributing) ### API * [Options](#options) ### Transports * [TLS](#tls) * [HTTP](#http) * [SSH](#ssh) * [XHR](#xhr) * [Sockets](#socket) ### Ciphers * [CIPHER](#cipher) * [AES](#aes) * [DES](#des) * [RC2](#rc2) ### PKI * [ED25519](#ed25519) * [RSA](#rsa) * [RSA-KEM](#rsakem) * [X.509](#x509) * [PKCS#5](#pkcs5) * [PKCS#7](#pkcs7) * [PKCS#8](#pkcs8) * [PKCS#10](#pkcs10) * [PKCS#12](#pkcs12) * [ASN.1](#asn) ### Message Digests * [SHA1](#sha1) * [SHA256](#sha256) * [SHA384](#sha384) * [SHA512](#sha512) * [MD5](#md5) * [HMAC](#hmac) ### Utilities * [Prime](#prime) * [PRNG](#prng) * [Tasks](#task) * [Utilities](#util) * [Logging](#log) * [Debugging](#debug) * [Flash Networking Support](#flash) ### Other * [Security Considerations](#security-considerations) * [Library Background](#library-background) * [Contact](#contact) * [Donations](#donations) --------------------------------------- Installation ------------ **Note**: Please see the [Security Considerations](#security-considerations) section before using packaging systems and pre-built files. Forge uses a [CommonJS][] module structure with a build process for browser bundles. The older [0.6.x][] branch with standalone files is available but will not be regularly updated. ### Node.js If you want to use forge with [Node.js][], it is available through `npm`: https://npmjs.org/package/node-forge Installation: npm install node-forge You can then use forge as a regular module: ```js var forge = require('node-forge'); ``` The npm package includes pre-built `forge.min.js`, `forge.all.min.js`, and `prime.worker.min.js` using the [UMD][] format. ### Bundle / Bower Each release is published in a separate repository as pre-built and minimized basic forge bundles using the [UMD][] format. https://github.com/digitalbazaar/forge-dist This bundle can be used in many environments. In particular it can be installed with [Bower][]: bower install forge ### jsDelivr CDN To use it via [jsDelivr](https://www.jsdelivr.com/package/npm/node-forge) include this in your html: ```html <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/forge.min.js"></script> ``` ### unpkg CDN To use it via [unpkg](https://unpkg.com/#/) include this in your html: ```html <script src="https://unpkg.com/[email protected]/dist/forge.min.js"></script> ``` ### Development Requirements The core JavaScript has the following requirements to build and test: * Building a browser bundle: * Node.js * npm * Testing * Node.js * npm * Chrome, Firefox, Safari (optional) Some special networking features can optionally use a Flash component. See the [Flash README](./flash/README.md) for details. ### Building for a web browser To create single file bundles for use with browsers run the following: npm install npm run build This will create single non-minimized and minimized files that can be included in the browser: dist/forge.js dist/forge.min.js A bundle that adds some utilities and networking support is also available: dist/forge.all.js dist/forge.all.min.js Include the file via: ```html <script src="YOUR_SCRIPT_PATH/forge.js"></script> ``` or ```html <script src="YOUR_SCRIPT_PATH/forge.min.js"></script> ``` The above bundles will synchronously create a global 'forge' object. **Note**: These bundles will not include any WebWorker scripts (eg: `dist/prime.worker.js`), so these will need to be accessible from the browser if any WebWorkers are used. ### Building a custom browser bundle The build process uses [webpack][] and the [config](./webpack.config.js) file can be modified to generate a file or files that only contain the parts of forge you need. [Browserify][] override support is also present in `package.json`. Testing ------- See the [testing README](./tests/README.md) for full details. ### Prepare to run tests npm install ### Running automated tests with Node.js Forge natively runs in a [Node.js][] environment: npm test ### Running automated tests with PhantomJS Automated testing is done via [Karma][]. By default it will run the tests in a headless manner with PhantomJS. npm run test-karma Is 'mocha' reporter output too verbose? Other reporters are available. Try 'dots', 'progress', or 'tap'. npm run test-karma -- --reporters progress By default [webpack][] is used. [Browserify][] can also be used. BUNDLER=browserify npm run test-karma ### Running automated tests with one or more browsers You can also specify one or more browsers to use. npm run test-karma -- --browsers Chrome,Firefox,Safari,PhantomJS The reporter option and `BUNDLER` environment variable can also be used. ### Running manual tests in a browser Testing in a browser uses [webpack][] to combine forge and all tests and then loading the result in a browser. A simple web server is provided that will output the HTTP or HTTPS URLs to load. It also will start a simple Flash Policy Server. Unit tests and older legacy tests are provided. Custom ports can be used by running `node tests/server.js` manually. To run the unit tests in a browser a special forge build is required: npm run test-build To run legacy browser based tests the main forge build is required: npm run build The tests are run with a custom server that prints out the URLs to use: npm run test-server ### Running other tests There are some other random tests and benchmarks available in the tests directory. ### Coverage testing To perform coverage testing of the unit tests, run the following. The results will be put in the `coverage/` directory. Note that coverage testing can slow down some tests considerably. npm install npm run coverage Contributing ------------ Any contributions (eg: PRs) that are accepted will be brought under the same license used by the rest of the Forge project. This license allows Forge to be used under the terms of either the BSD License or the GNU General Public License (GPL) Version 2. See: [LICENSE](https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE) If a contribution contains 3rd party source code with its own license, it may retain it, so long as that license is compatible with the Forge license. API --- <a name="options" /> ### Options If at any time you wish to disable the use of native code, where available, for particular forge features like its secure random number generator, you may set the ```forge.options.usePureJavaScript``` flag to ```true```. It is not recommended that you set this flag as native code is typically more performant and may have stronger security properties. It may be useful to set this flag to test certain features that you plan to run in environments that are different from your testing environment. To disable native code when including forge in the browser: ```js // run this *after* including the forge script forge.options.usePureJavaScript = true; ``` To disable native code when using Node.js: ```js var forge = require('node-forge'); forge.options.usePureJavaScript = true; ``` Transports ---------- <a name="tls" /> ### TLS Provides a native javascript client and server-side [TLS][] implementation. __Examples__ ```js // create TLS client var client = forge.tls.createConnection({ server: false, caStore: /* Array of PEM-formatted certs or a CA store object */, sessionCache: {}, // supported cipher suites in order of preference cipherSuites: [ forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], virtualHost: 'example.com', verify: function(connection, verified, depth, certs) { if(depth === 0) { var cn = certs[0].subject.getField('CN').value; if(cn !== 'example.com') { verified = { alert: forge.tls.Alert.Description.bad_certificate, message: 'Certificate common name does not match hostname.' }; } } return verified; }, connected: function(connection) { console.log('connected'); // send message to server connection.prepare(forge.util.encodeUtf8('Hi server!')); /* NOTE: experimental, start heartbeat retransmission timer myHeartbeatTimer = setInterval(function() { connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); }, 5*60*1000);*/ }, /* provide a client-side cert if you want getCertificate: function(connection, hint) { return myClientCertificate; }, /* the private key for the client-side cert if provided */ getPrivateKey: function(connection, cert) { return myClientPrivateKey; }, tlsDataReady: function(connection) { // TLS data (encrypted) is ready to be sent to the server sendToServerSomehow(connection.tlsData.getBytes()); // if you were communicating with the server below, you'd do: // server.process(connection.tlsData.getBytes()); }, dataReady: function(connection) { // clear data from the server is ready console.log('the server sent: ' + forge.util.decodeUtf8(connection.data.getBytes())); // close connection connection.close(); }, /* NOTE: experimental heartbeatReceived: function(connection, payload) { // restart retransmission timer, look at payload clearInterval(myHeartbeatTimer); myHeartbeatTimer = setInterval(function() { connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); }, 5*60*1000); payload.getBytes(); },*/ closed: function(connection) { console.log('disconnected'); }, error: function(connection, error) { console.log('uh oh', error); } }); // start the handshake process client.handshake(); // when encrypted TLS data is received from the server, process it client.process(encryptedBytesFromServer); // create TLS server var server = forge.tls.createConnection({ server: true, caStore: /* Array of PEM-formatted certs or a CA store object */, sessionCache: {}, // supported cipher suites in order of preference cipherSuites: [ forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], // require a client-side certificate if you want verifyClient: true, verify: function(connection, verified, depth, certs) { if(depth === 0) { var cn = certs[0].subject.getField('CN').value; if(cn !== 'the-client') { verified = { alert: forge.tls.Alert.Description.bad_certificate, message: 'Certificate common name does not match expected client.' }; } } return verified; }, connected: function(connection) { console.log('connected'); // send message to client connection.prepare(forge.util.encodeUtf8('Hi client!')); /* NOTE: experimental, start heartbeat retransmission timer myHeartbeatTimer = setInterval(function() { connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); }, 5*60*1000);*/ }, getCertificate: function(connection, hint) { return myServerCertificate; }, getPrivateKey: function(connection, cert) { return myServerPrivateKey; }, tlsDataReady: function(connection) { // TLS data (encrypted) is ready to be sent to the client sendToClientSomehow(connection.tlsData.getBytes()); // if you were communicating with the client above you'd do: // client.process(connection.tlsData.getBytes()); }, dataReady: function(connection) { // clear data from the client is ready console.log('the client sent: ' + forge.util.decodeUtf8(connection.data.getBytes())); // close connection connection.close(); }, /* NOTE: experimental heartbeatReceived: function(connection, payload) { // restart retransmission timer, look at payload clearInterval(myHeartbeatTimer); myHeartbeatTimer = setInterval(function() { connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); }, 5*60*1000); payload.getBytes(); },*/ closed: function(connection) { console.log('disconnected'); }, error: function(connection, error) { console.log('uh oh', error); } }); // when encrypted TLS data is received from the client, process it server.process(encryptedBytesFromClient); ``` Connect to a TLS server using node's net.Socket: ```js var socket = new net.Socket(); var client = forge.tls.createConnection({ server: false, verify: function(connection, verified, depth, certs) { // skip verification for testing console.log('[tls] server certificate verified'); return true; }, connected: function(connection) { console.log('[tls] connected'); // prepare some data to send (note that the string is interpreted as // 'binary' encoded, which works for HTTP which only uses ASCII, use // forge.util.encodeUtf8(str) otherwise client.prepare('GET / HTTP/1.0\r\n\r\n'); }, tlsDataReady: function(connection) { // encrypted data is ready to be sent to the server var data = connection.tlsData.getBytes(); socket.write(data, 'binary'); // encoding should be 'binary' }, dataReady: function(connection) { // clear data from the server is ready var data = connection.data.getBytes(); console.log('[tls] data received from the server: ' + data); }, closed: function() { console.log('[tls] disconnected'); }, error: function(connection, error) { console.log('[tls] error', error); } }); socket.on('connect', function() { console.log('[socket] connected'); client.handshake(); }); socket.on('data', function(data) { client.process(data.toString('binary')); // encoding should be 'binary' }); socket.on('end', function() { console.log('[socket] disconnected'); }); // connect to google.com socket.connect(443, 'google.com'); // or connect to gmail's imap server (but don't send the HTTP header above) //socket.connect(993, 'imap.gmail.com'); ``` <a name="http" /> ### HTTP Provides a native [JavaScript][] mini-implementation of an http client that uses pooled sockets. __Examples__ ```js // create an HTTP GET request var request = forge.http.createRequest({method: 'GET', path: url.path}); // send the request somewhere sendSomehow(request.toString()); // receive response var buffer = forge.util.createBuffer(); var response = forge.http.createResponse(); var someAsyncDataHandler = function(bytes) { if(!response.bodyReceived) { buffer.putBytes(bytes); if(!response.headerReceived) { if(response.readHeader(buffer)) { console.log('HTTP response header: ' + response.toString()); } } if(response.headerReceived && !response.bodyReceived) { if(response.readBody(buffer)) { console.log('HTTP response body: ' + response.body); } } } }; ``` <a name="ssh" /> ### SSH Provides some SSH utility functions. __Examples__ ```js // encodes (and optionally encrypts) a private RSA key as a Putty PPK file forge.ssh.privateKeyToPutty(privateKey, passphrase, comment); // encodes a public RSA key as an OpenSSH file forge.ssh.publicKeyToOpenSSH(key, comment); // encodes a private RSA key as an OpenSSH file forge.ssh.privateKeyToOpenSSH(privateKey, passphrase); // gets the SSH public key fingerprint in a byte buffer forge.ssh.getPublicKeyFingerprint(key); // gets a hex-encoded, colon-delimited SSH public key fingerprint forge.ssh.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); ``` <a name="xhr" /> ### XHR Provides an XmlHttpRequest implementation using forge.http as a backend. __Examples__ ```js // TODO ``` <a name="socket" /> ### Sockets Provides an interface to create and use raw sockets provided via Flash. __Examples__ ```js // TODO ``` Ciphers ------- <a name="cipher" /> ### CIPHER Provides a basic API for block encryption and decryption. There is built-in support for the ciphers: [AES][], [3DES][], and [DES][], and for the modes of operation: [ECB][], [CBC][], [CFB][], [OFB][], [CTR][], and [GCM][]. These algorithms are currently supported: * AES-ECB * AES-CBC * AES-CFB * AES-OFB * AES-CTR * AES-GCM * 3DES-ECB * 3DES-CBC * DES-ECB * DES-CBC When using an [AES][] algorithm, the key size will determine whether AES-128, AES-192, or AES-256 is used (all are supported). When a [DES][] algorithm is used, the key size will determine whether [3DES][] or regular [DES][] is used. Use a [3DES][] algorithm to enforce Triple-DES. __Examples__ ```js // generate a random key and IV // Note: a key size of 16 bytes will use AES-128, 24 => AES-192, 32 => AES-256 var key = forge.random.getBytesSync(16); var iv = forge.random.getBytesSync(16); /* alternatively, generate a password-based 16-byte key var salt = forge.random.getBytesSync(128); var key = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); */ // encrypt some bytes using CBC mode // (other modes include: ECB, CFB, OFB, CTR, and GCM) // Note: CBC and ECB modes use PKCS#7 padding as default var cipher = forge.cipher.createCipher('AES-CBC', key); cipher.start({iv: iv}); cipher.update(forge.util.createBuffer(someBytes)); cipher.finish(); var encrypted = cipher.output; // outputs encrypted hex console.log(encrypted.toHex()); // decrypt some bytes using CBC mode // (other modes include: CFB, OFB, CTR, and GCM) var decipher = forge.cipher.createDecipher('AES-CBC', key); decipher.start({iv: iv}); decipher.update(encrypted); var result = decipher.finish(); // check 'result' for true/false // outputs decrypted hex console.log(decipher.output.toHex()); // decrypt bytes using CBC mode and streaming // Performance can suffer for large multi-MB inputs due to buffer // manipulations. Stream processing in chunks can offer significant // improvement. CPU intensive update() calls could also be performed with // setImmediate/setTimeout to avoid blocking the main browser UI thread (not // shown here). Optimal block size depends on the JavaScript VM and other // factors. Encryption can use a simple technique for increased performance. var encryptedBytes = encrypted.bytes(); var decipher = forge.cipher.createDecipher('AES-CBC', key); decipher.start({iv: iv}); var length = encryptedBytes.length; var chunkSize = 1024 * 64; var index = 0; var decrypted = ''; do { decrypted += decipher.output.getBytes(); var buf = forge.util.createBuffer(encryptedBytes.substr(index, chunkSize)); decipher.update(buf); index += chunkSize; } while(index < length); var result = decipher.finish(); assert(result); decrypted += decipher.output.getBytes(); console.log(forge.util.bytesToHex(decrypted)); // encrypt some bytes using GCM mode var cipher = forge.cipher.createCipher('AES-GCM', key); cipher.start({ iv: iv, // should be a 12-byte binary-encoded string or byte buffer additionalData: 'binary-encoded string', // optional tagLength: 128 // optional, defaults to 128 bits }); cipher.update(forge.util.createBuffer(someBytes)); cipher.finish(); var encrypted = cipher.output; var tag = cipher.mode.tag; // outputs encrypted hex console.log(encrypted.toHex()); // outputs authentication tag console.log(tag.toHex()); // decrypt some bytes using GCM mode var decipher = forge.cipher.createDecipher('AES-GCM', key); decipher.start({ iv: iv, additionalData: 'binary-encoded string', // optional tagLength: 128, // optional, defaults to 128 bits tag: tag // authentication tag from encryption }); decipher.update(encrypted); var pass = decipher.finish(); // pass is false if there was a failure (eg: authentication tag didn't match) if(pass) { // outputs decrypted hex console.log(decipher.output.toHex()); } ``` Using forge in Node.js to match openssl's "enc" command line tool (**Note**: OpenSSL "enc" uses a non-standard file format with a custom key derivation function and a fixed iteration count of 1, which some consider less secure than alternatives such as [OpenPGP](https://tools.ietf.org/html/rfc4880)/[GnuPG](https://www.gnupg.org/)): ```js var forge = require('node-forge'); var fs = require('fs'); // openssl enc -des3 -in input.txt -out input.enc function encrypt(password) { var input = fs.readFileSync('input.txt', {encoding: 'binary'}); // 3DES key and IV sizes var keySize = 24; var ivSize = 8; // get derived bytes // Notes: // 1. If using an alternative hash (eg: "-md sha1") pass // "forge.md.sha1.create()" as the final parameter. // 2. If using "-nosalt", set salt to null. var salt = forge.random.getBytesSync(8); // var md = forge.md.sha1.create(); // "-md sha1" var derivedBytes = forge.pbe.opensslDeriveBytes( password, salt, keySize + ivSize/*, md*/); var buffer = forge.util.createBuffer(derivedBytes); var key = buffer.getBytes(keySize); var iv = buffer.getBytes(ivSize); var cipher = forge.cipher.createCipher('3DES-CBC', key); cipher.start({iv: iv}); cipher.update(forge.util.createBuffer(input, 'binary')); cipher.finish(); var output = forge.util.createBuffer(); // if using a salt, prepend this to the output: if(salt !== null) { output.putBytes('Salted__'); // (add to match openssl tool output) output.putBytes(salt); } output.putBuffer(cipher.output); fs.writeFileSync('input.enc', output.getBytes(), {encoding: 'binary'}); } // openssl enc -d -des3 -in input.enc -out input.dec.txt function decrypt(password) { var input = fs.readFileSync('input.enc', {encoding: 'binary'}); // parse salt from input input = forge.util.createBuffer(input, 'binary'); // skip "Salted__" (if known to be present) input.getBytes('Salted__'.length); // read 8-byte salt var salt = input.getBytes(8); // Note: if using "-nosalt", skip above parsing and use // var salt = null; // 3DES key and IV sizes var keySize = 24; var ivSize = 8; var derivedBytes = forge.pbe.opensslDeriveBytes( password, salt, keySize + ivSize); var buffer = forge.util.createBuffer(derivedBytes); var key = buffer.getBytes(keySize); var iv = buffer.getBytes(ivSize); var decipher = forge.cipher.createDecipher('3DES-CBC', key); decipher.start({iv: iv}); decipher.update(input); var result = decipher.finish(); // check 'result' for true/false fs.writeFileSync( 'input.dec.txt', decipher.output.getBytes(), {encoding: 'binary'}); } ``` <a name="aes" /> ### AES Provides [AES][] encryption and decryption in [CBC][], [CFB][], [OFB][], [CTR][], and [GCM][] modes. See [CIPHER](#cipher) for examples. <a name="des" /> ### DES Provides [3DES][] and [DES][] encryption and decryption in [ECB][] and [CBC][] modes. See [CIPHER](#cipher) for examples. <a name="rc2" /> ### RC2 __Examples__ ```js // generate a random key and IV var key = forge.random.getBytesSync(16); var iv = forge.random.getBytesSync(8); // encrypt some bytes var cipher = forge.rc2.createEncryptionCipher(key); cipher.start(iv); cipher.update(forge.util.createBuffer(someBytes)); cipher.finish(); var encrypted = cipher.output; // outputs encrypted hex console.log(encrypted.toHex()); // decrypt some bytes var cipher = forge.rc2.createDecryptionCipher(key); cipher.start(iv); cipher.update(encrypted); cipher.finish(); // outputs decrypted hex console.log(cipher.output.toHex()); ``` PKI --- Provides [X.509][] certificate support, ED25519 key generation and signing/verifying, and RSA public and private key encoding, decoding, encryption/decryption, and signing/verifying. <a name="ed25519" /> ### ED25519 Special thanks to [TweetNaCl.js][] for providing the bulk of the implementation. __Examples__ ```js var ed25519 = forge.pki.ed25519; // generate a random ED25519 keypair var keypair = ed25519.generateKeyPair(); // `keypair.publicKey` is a node.js Buffer or Uint8Array // `keypair.privateKey` is a node.js Buffer or Uint8Array // generate a random ED25519 keypair based on a random 32-byte seed var seed = forge.random.getBytesSync(32); var keypair = ed25519.generateKeyPair({seed: seed}); // generate a random ED25519 keypair based on a "password" 32-byte seed var password = 'Mai9ohgh6ahxee0jutheew0pungoozil'; var seed = new forge.util.ByteBuffer(password, 'utf8'); var keypair = ed25519.generateKeyPair({seed: seed}); // sign a UTF-8 message var signature = ED25519.sign({ message: 'test', // also accepts `binary` if you want to pass a binary string encoding: 'utf8', // node.js Buffer, Uint8Array, forge ByteBuffer, binary string privateKey: privateKey }); // `signature` is a node.js Buffer or Uint8Array // sign a message passed as a buffer var signature = ED25519.sign({ // also accepts a forge ByteBuffer or Uint8Array message: new Buffer('test', 'utf8'), privateKey: privateKey }); // sign a message digest (shorter "message" == better performance) var md = forge.md.sha256.create(); md.update('test', 'utf8'); var signature = ED25519.sign({ md: md, privateKey: privateKey }); // verify a signature on a UTF-8 message var verified = ED25519.verify({ message: 'test', encoding: 'utf8', // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string signature: signature, // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string publicKey: publicKey }); // `verified` is true/false // sign a message passed as a buffer var verified = ED25519.verify({ // also accepts a forge ByteBuffer or Uint8Array message: new Buffer('test', 'utf8'), // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string signature: signature, // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string publicKey: publicKey }); // verify a signature on a message digest var md = forge.md.sha256.create(); md.update('test', 'utf8'); var verified = ED25519.verify({ md: md, // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string signature: signature, // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string publicKey: publicKey }); ``` <a name="rsa" /> ### RSA __Examples__ ```js var rsa = forge.pki.rsa; // generate an RSA key pair synchronously // *NOT RECOMMENDED* -- can be significantly slower than async and will not // use native APIs if available. var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001}); // generate an RSA key pair asynchronously (uses web workers if available) // use workers: -1 to run a fast core estimator to optimize # of workers // *RECOMMENDED* - can be significantly faster than sync -- and will use // native APIs if available. rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) { // keypair.privateKey, keypair.publicKey }); // generate an RSA key pair in steps that attempt to run for a specified period // of time on the main JS thread var state = rsa.createKeyPairGenerationState(2048, 0x10001); var step = function() { // run for 100 ms if(!rsa.stepKeyPairGenerationState(state, 100)) { setTimeout(step, 1); } else { // done, turn off progress indicator, use state.keys } }; // turn on progress indicator, schedule generation to run setTimeout(step); // sign data with a private key and output DigestInfo DER-encoded bytes // (defaults to RSASSA PKCS#1 v1.5) var md = forge.md.sha1.create(); md.update('sign this', 'utf8'); var signature = privateKey.sign(md); // verify data with a public key // (defaults to RSASSA PKCS#1 v1.5) var verified = publicKey.verify(md.digest().bytes(), signature); // sign data using RSASSA-PSS where PSS uses a SHA-1 hash, a SHA-1 based // masking function MGF1, and a 20 byte salt var md = forge.md.sha1.create(); md.update('sign this', 'utf8'); var pss = forge.pss.create({ md: forge.md.sha1.create(), mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), saltLength: 20 // optionally pass 'prng' with a custom PRNG implementation // optionalls pass 'salt' with a forge.util.ByteBuffer w/custom salt }); var signature = privateKey.sign(md, pss); // verify RSASSA-PSS signature var pss = forge.pss.create({ md: forge.md.sha1.create(), mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), saltLength: 20 // optionally pass 'prng' with a custom PRNG implementation }); var md = forge.md.sha1.create(); md.update('sign this', 'utf8'); publicKey.verify(md.digest().getBytes(), signature, pss); // encrypt data with a public key (defaults to RSAES PKCS#1 v1.5) var encrypted = publicKey.encrypt(bytes); // decrypt data with a private key (defaults to RSAES PKCS#1 v1.5) var decrypted = privateKey.decrypt(encrypted); // encrypt data with a public key using RSAES PKCS#1 v1.5 var encrypted = publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5'); // decrypt data with a private key using RSAES PKCS#1 v1.5 var decrypted = privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5'); // encrypt data with a public key using RSAES-OAEP var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP'); // decrypt data with a private key using RSAES-OAEP var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP'); // encrypt data with a public key using RSAES-OAEP/SHA-256 var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { md: forge.md.sha256.create() }); // decrypt data with a private key using RSAES-OAEP/SHA-256 var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { md: forge.md.sha256.create() }); // encrypt data with a public key using RSAES-OAEP/SHA-256/MGF1-SHA-1 // compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { md: forge.md.sha256.create(), mgf1: { md: forge.md.sha1.create() } }); // decrypt data with a private key using RSAES-OAEP/SHA-256/MGF1-SHA-1 // compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { md: forge.md.sha256.create(), mgf1: { md: forge.md.sha1.create() } }); ``` <a name="rsakem" /> ### RSA-KEM __Examples__ ```js // generate an RSA key pair asynchronously (uses web workers if available) // use workers: -1 to run a fast core estimator to optimize # of workers forge.rsa.generateKeyPair({bits: 2048, workers: -1}, function(err, keypair) { // keypair.privateKey, keypair.publicKey }); // generate and encapsulate a 16-byte secret key var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); var kem = forge.kem.rsa.create(kdf1); var result = kem.encrypt(keypair.publicKey, 16); // result has 'encapsulation' and 'key' // encrypt some bytes var iv = forge.random.getBytesSync(12); var someBytes = 'hello world!'; var cipher = forge.cipher.createCipher('AES-GCM', result.key); cipher.start({iv: iv}); cipher.update(forge.util.createBuffer(someBytes)); cipher.finish(); var encrypted = cipher.output.getBytes(); var tag = cipher.mode.tag.getBytes(); // send 'encrypted', 'iv', 'tag', and result.encapsulation to recipient // decrypt encapsulated 16-byte secret key var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); var kem = forge.kem.rsa.create(kdf1); var key = kem.decrypt(keypair.privateKey, result.encapsulation, 16); // decrypt some bytes var decipher = forge.cipher.createDecipher('AES-GCM', key); decipher.start({iv: iv, tag: tag}); decipher.update(forge.util.createBuffer(encrypted)); var pass = decipher.finish(); // pass is false if there was a failure (eg: authentication tag didn't match) if(pass) { // outputs 'hello world!' console.log(decipher.output.getBytes()); } ``` <a name="x509" /> ### X.509 __Examples__ ```js var pki = forge.pki; // convert a PEM-formatted public key to a Forge public key var publicKey = pki.publicKeyFromPem(pem); // convert a Forge public key to PEM-format var pem = pki.publicKeyToPem(publicKey); // convert an ASN.1 SubjectPublicKeyInfo to a Forge public key var publicKey = pki.publicKeyFromAsn1(subjectPublicKeyInfo); // convert a Forge public key to an ASN.1 SubjectPublicKeyInfo var subjectPublicKeyInfo = pki.publicKeyToAsn1(publicKey); // gets a SHA-1 RSAPublicKey fingerprint a byte buffer pki.getPublicKeyFingerprint(key); // gets a SHA-1 SubjectPublicKeyInfo fingerprint a byte buffer pki.getPublicKeyFingerprint(key, {type: 'SubjectPublicKeyInfo'}); // gets a hex-encoded, colon-delimited SHA-1 RSAPublicKey public key fingerprint pki.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); // gets a hex-encoded, colon-delimited SHA-1 SubjectPublicKeyInfo public key fingerprint pki.getPublicKeyFingerprint(key, { type: 'SubjectPublicKeyInfo', encoding: 'hex', delimiter: ':' }); // gets a hex-encoded, colon-delimited MD5 RSAPublicKey public key fingerprint pki.getPublicKeyFingerprint(key, { md: forge.md.md5.create(), encoding: 'hex', delimiter: ':' }); // creates a CA store var caStore = pki.createCaStore([/* PEM-encoded cert */, ...]); // add a certificate to the CA store caStore.addCertificate(certObjectOrPemString); // gets the issuer (its certificate) for the given certificate var issuerCert = caStore.getIssuer(subjectCert); // verifies a certificate chain against a CA store pki.verifyCertificateChain(caStore, chain, customVerifyCallback); // signs a certificate using the given private key cert.sign(privateKey); // signs a certificate using SHA-256 instead of SHA-1 cert.sign(privateKey, forge.md.sha256.create()); // verifies an issued certificate using the certificates public key var verified = issuer.verify(issued); // generate a keypair and create an X.509v3 certificate var keys = pki.rsa.generateKeyPair(2048); var cert = pki.createCertificate(); cert.publicKey = keys.publicKey; // alternatively set public key from a csr //cert.publicKey = csr.publicKey; // NOTE: serialNumber is the hex encoded value of an ASN.1 INTEGER. // Conforming CAs should ensure serialNumber is: // - no more than 20 octets // - non-negative (prefix a '00' if your value starts with a '1' bit) cert.serialNumber = '01'; cert.validity.notBefore = new Date(); cert.validity.notAfter = new Date(); cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1); var attrs = [{ name: 'commonName', value: 'example.org' }, { name: 'countryName', value: 'US' }, { shortName: 'ST', value: 'Virginia' }, { name: 'localityName', value: 'Blacksburg' }, { name: 'organizationName', value: 'Test' }, { shortName: 'OU', value: 'Test' }]; cert.setSubject(attrs); // alternatively set subject from a csr //cert.setSubject(csr.subject.attributes); cert.setIssuer(attrs); cert.setExtensions([{ name: 'basicConstraints', cA: true }, { name: 'keyUsage', keyCertSign: true, digitalSignature: true, nonRepudiation: true, keyEncipherment: true, dataEncipherment: true }, { name: 'extKeyUsage', serverAuth: true, clientAuth: true, codeSigning: true, emailProtection: true, timeStamping: true }, { name: 'nsCertType', client: true, server: true, email: true, objsign: true, sslCA: true, emailCA: true, objCA: true }, { name: 'subjectAltName', altNames: [{ type: 6, // URI value: 'http://example.org/webid#me' }, { type: 7, // IP ip: '127.0.0.1' }] }, { name: 'subjectKeyIdentifier' }]); /* alternatively set extensions from a csr var extensions = csr.getAttribute({name: 'extensionRequest'}).extensions; // optionally add more extensions extensions.push.apply(extensions, [{ name: 'basicConstraints', cA: true }, { name: 'keyUsage', keyCertSign: true, digitalSignature: true, nonRepudiation: true, keyEncipherment: true, dataEncipherment: true }]); cert.setExtensions(extensions); */ // self-sign certificate cert.sign(keys.privateKey); // convert a Forge certificate to PEM var pem = pki.certificateToPem(cert); // convert a Forge certificate from PEM var cert = pki.certificateFromPem(pem); // convert an ASN.1 X.509x3 object to a Forge certificate var cert = pki.certificateFromAsn1(obj); // convert a Forge certificate to an ASN.1 X.509v3 object var asn1Cert = pki.certificateToAsn1(cert); ``` <a name="pkcs5" /> ### PKCS#5 Provides the password-based key-derivation function from [PKCS#5][]. __Examples__ ```js // generate a password-based 16-byte key // note an optional message digest can be passed as the final parameter var salt = forge.random.getBytesSync(128); var derivedKey = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); // generate key asynchronously // note an optional message digest can be passed before the callback forge.pkcs5.pbkdf2('password', salt, numIterations, 16, function(err, derivedKey) { // do something w/derivedKey }); ``` <a name="pkcs7" /> ### PKCS#7 Provides cryptographically protected messages from [PKCS#7][]. __Examples__ ```js // convert a message from PEM var p7 = forge.pkcs7.messageFromPem(pem); // look at p7.recipients // find a recipient by the issuer of a certificate var recipient = p7.findRecipient(cert); // decrypt p7.decrypt(p7.recipients[0], privateKey); // create a p7 enveloped message var p7 = forge.pkcs7.createEnvelopedData(); // add a recipient var cert = forge.pki.certificateFromPem(certPem); p7.addRecipient(cert); // set content p7.content = forge.util.createBuffer('Hello'); // encrypt p7.encrypt(); // convert message to PEM var pem = forge.pkcs7.messageToPem(p7); // create a degenerate PKCS#7 certificate container // (CRLs not currently supported, only certificates) var p7 = forge.pkcs7.createSignedData(); p7.addCertificate(certOrCertPem1); p7.addCertificate(certOrCertPem2); var pem = forge.pkcs7.messageToPem(p7); // create PKCS#7 signed data with authenticatedAttributes // attributes include: PKCS#9 content-type, message-digest, and signing-time var p7 = forge.pkcs7.createSignedData(); p7.content = forge.util.createBuffer('Some content to be signed.', 'utf8'); p7.addCertificate(certOrCertPem); p7.addSigner({ key: privateKeyAssociatedWithCert, certificate: certOrCertPem, digestAlgorithm: forge.pki.oids.sha256, authenticatedAttributes: [{ type: forge.pki.oids.contentType, value: forge.pki.oids.data }, { type: forge.pki.oids.messageDigest // value will be auto-populated at signing time }, { type: forge.pki.oids.signingTime, // value can also be auto-populated at signing time value: new Date() }] }); p7.sign(); var pem = forge.pkcs7.messageToPem(p7); ``` <a name="pkcs8" /> ### PKCS#8 __Examples__ ```js var pki = forge.pki; // convert a PEM-formatted private key to a Forge private key var privateKey = pki.privateKeyFromPem(pem); // convert a Forge private key to PEM-format var pem = pki.privateKeyToPem(privateKey); // convert an ASN.1 PrivateKeyInfo or RSAPrivateKey to a Forge private key var privateKey = pki.privateKeyFromAsn1(rsaPrivateKey); // convert a Forge private key to an ASN.1 RSAPrivateKey var rsaPrivateKey = pki.privateKeyToAsn1(privateKey); // wrap an RSAPrivateKey ASN.1 object in a PKCS#8 ASN.1 PrivateKeyInfo var privateKeyInfo = pki.wrapRsaPrivateKey(rsaPrivateKey); // convert a PKCS#8 ASN.1 PrivateKeyInfo to PEM var pem = pki.privateKeyInfoToPem(privateKeyInfo); // encrypts a PrivateKeyInfo and outputs an EncryptedPrivateKeyInfo var encryptedPrivateKeyInfo = pki.encryptPrivateKeyInfo( privateKeyInfo, 'password', { algorithm: 'aes256', // 'aes128', 'aes192', 'aes256', '3des' }); // decrypts an ASN.1 EncryptedPrivateKeyInfo var privateKeyInfo = pki.decryptPrivateKeyInfo( encryptedPrivateKeyInfo, 'password'); // converts an EncryptedPrivateKeyInfo to PEM var pem = pki.encryptedPrivateKeyToPem(encryptedPrivateKeyInfo); // converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format var encryptedPrivateKeyInfo = pki.encryptedPrivateKeyFromPem(pem); // wraps and encrypts a Forge private key and outputs it in PEM format var pem = pki.encryptRsaPrivateKey(privateKey, 'password'); // encrypts a Forge private key and outputs it in PEM format using OpenSSL's // proprietary legacy format + encapsulated PEM headers (DEK-Info) var pem = pki.encryptRsaPrivateKey(privateKey, 'password', {legacy: true}); // decrypts a PEM-formatted, encrypted private key var privateKey = pki.decryptRsaPrivateKey(pem, 'password'); // sets an RSA public key from a private key var publicKey = pki.setRsaPublicKey(privateKey.n, privateKey.e); ``` <a name="pkcs10" /> ### PKCS#10 Provides certification requests or certificate signing requests (CSR) from [PKCS#10][]. __Examples__ ```js // generate a key pair var keys = forge.pki.rsa.generateKeyPair(1024); // create a certification request (CSR) var csr = forge.pki.createCertificationRequest(); csr.publicKey = keys.publicKey; csr.setSubject([{ name: 'commonName', value: 'example.org' }, { name: 'countryName', value: 'US' }, { shortName: 'ST', value: 'Virginia' }, { name: 'localityName', value: 'Blacksburg' }, { name: 'organizationName', value: 'Test' }, { shortName: 'OU', value: 'Test' }]); // set (optional) attributes csr.setAttributes([{ name: 'challengePassword', value: 'password' }, { name: 'unstructuredName', value: 'My Company, Inc.' }, { name: 'extensionRequest', extensions: [{ name: 'subjectAltName', altNames: [{ // 2 is DNS type type: 2, value: 'test.domain.com' }, { type: 2, value: 'other.domain.com', }, { type: 2, value: 'www.domain.net' }] }] }]); // sign certification request csr.sign(keys.privateKey); // verify certification request var verified = csr.verify(); // convert certification request to PEM-format var pem = forge.pki.certificationRequestToPem(csr); // convert a Forge certification request from PEM-format var csr = forge.pki.certificationRequestFromPem(pem); // get an attribute csr.getAttribute({name: 'challengePassword'}); // get extensions array csr.getAttribute({name: 'extensionRequest'}).extensions; ``` <a name="pkcs12" /> ### PKCS#12 Provides the cryptographic archive file format from [PKCS#12][]. **Note for Chrome/Firefox/iOS/similar users**: If you have trouble importing a PKCS#12 container, try using the TripleDES algorithm. It can be passed to `forge.pkcs12.toPkcs12Asn1` using the `{algorithm: '3des'}` option. __Examples__ ```js // decode p12 from base64 var p12Der = forge.util.decode64(p12b64); // get p12 as ASN.1 object var p12Asn1 = forge.asn1.fromDer(p12Der); // decrypt p12 using the password 'password' var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password'); // decrypt p12 using non-strict parsing mode (resolves some ASN.1 parse errors) var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, false, 'password'); // decrypt p12 using literally no password (eg: Mac OS X/apple push) var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1); // decrypt p12 using an "empty" password (eg: OpenSSL with no password input) var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, ''); // p12.safeContents is an array of safe contents, each of // which contains an array of safeBags // get bags by friendlyName var bags = p12.getBags({friendlyName: 'test'}); // bags are key'd by attribute type (here "friendlyName") // and the key values are an array of matching objects var cert = bags.friendlyName[0]; // get bags by localKeyId var bags = p12.getBags({localKeyId: buffer}); // bags are key'd by attribute type (here "localKeyId") // and the key values are an array of matching objects var cert = bags.localKeyId[0]; // get bags by localKeyId (input in hex) var bags = p12.getBags({localKeyIdHex: '7b59377ff142d0be4565e9ac3d396c01401cd879'}); // bags are key'd by attribute type (here "localKeyId", *not* "localKeyIdHex") // and the key values are an array of matching objects var cert = bags.localKeyId[0]; // get bags by type var bags = p12.getBags({bagType: forge.pki.oids.certBag}); // bags are key'd by bagType and each bagType key's value // is an array of matches (in this case, certificate objects) var cert = bags[forge.pki.oids.certBag][0]; // get bags by friendlyName and filter on bag type var bags = p12.getBags({ friendlyName: 'test', bagType: forge.pki.oids.certBag }); // get key bags var bags = p12.getBags({bagType: forge.pki.oids.keyBag}); // get key var bag = bags[forge.pki.oids.keyBag][0]; var key = bag.key; // if the key is in a format unrecognized by forge then // bag.key will be `null`, use bag.asn1 to get the ASN.1 // representation of the key if(bag.key === null) { var keyAsn1 = bag.asn1; // can now convert back to DER/PEM/etc for export } // generate a p12 using AES (default) var p12Asn1 = forge.pkcs12.toPkcs12Asn1( privateKey, certificateChain, 'password'); // generate a p12 that can be imported by Chrome/Firefox/iOS // (requires the use of Triple DES instead of AES) var p12Asn1 = forge.pkcs12.toPkcs12Asn1( privateKey, certificateChain, 'password', {algorithm: '3des'}); // base64-encode p12 var p12Der = forge.asn1.toDer(p12Asn1).getBytes(); var p12b64 = forge.util.encode64(p12Der); // create download link for p12 var a = document.createElement('a'); a.download = 'example.p12'; a.setAttribute('href', 'data:application/x-pkcs12;base64,' + p12b64); a.appendChild(document.createTextNode('Download')); ``` <a name="asn" /> ### ASN.1 Provides [ASN.1][] DER encoding and decoding. __Examples__ ```js var asn1 = forge.asn1; // create a SubjectPublicKeyInfo var subjectPublicKeyInfo = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids['rsaEncryption']).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // subjectPublicKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ // RSAPublicKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // modulus (n) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), // publicExponent (e) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)) ]) ]) ]); // serialize an ASN.1 object to DER format var derBuffer = asn1.toDer(subjectPublicKeyInfo); // deserialize to an ASN.1 object from a byte buffer filled with DER data var object = asn1.fromDer(derBuffer); // convert an OID dot-separated string to a byte buffer var derOidBuffer = asn1.oidToDer('1.2.840.113549.1.1.5'); // convert a byte buffer with a DER-encoded OID to a dot-separated string console.log(asn1.derToOid(derOidBuffer)); // output: 1.2.840.113549.1.1.5 // validates that an ASN.1 object matches a particular ASN.1 structure and // captures data of interest from that structure for easy access var publicKeyValidator = { name: 'SubjectPublicKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'subjectPublicKeyInfo', value: [{ name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'publicKeyOid' }] }, { // subjectPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, value: [{ // RSAPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, captureAsn1: 'rsaPublicKey' }] }] }; var capture = {}; var errors = []; if(!asn1.validate( publicKeyValidator, subjectPublicKeyInfo, validator, capture, errors)) { throw 'ASN.1 object is not a SubjectPublicKeyInfo.'; } // capture.subjectPublicKeyInfo contains the full ASN.1 object // capture.rsaPublicKey contains the full ASN.1 object for the RSA public key // capture.publicKeyOid only contains the value for the OID var oid = asn1.derToOid(capture.publicKeyOid); if(oid !== pki.oids['rsaEncryption']) { throw 'Unsupported OID.'; } // pretty print an ASN.1 object to a string for debugging purposes asn1.prettyPrint(object); ``` Message Digests ---------------- <a name="sha1" /> ### SHA1 Provides [SHA-1][] message digests. __Examples__ ```js var md = forge.md.sha1.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 ``` <a name="sha256" /> ### SHA256 Provides [SHA-256][] message digests. __Examples__ ```js var md = forge.md.sha256.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 ``` <a name="sha384" /> ### SHA384 Provides [SHA-384][] message digests. __Examples__ ```js var md = forge.md.sha384.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1 ``` <a name="sha512" /> ### SHA512 Provides [SHA-512][] message digests. __Examples__ ```js // SHA-512 var md = forge.md.sha512.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: 07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6 // SHA-512/224 var md = forge.md.sha512.sha224.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: 944cd2847fb54558d4775db0485a50003111c8e5daa63fe722c6aa37 // SHA-512/256 var md = forge.md.sha512.sha256.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d ``` <a name="md5" /> ### MD5 Provides [MD5][] message digests. __Examples__ ```js var md = forge.md.md5.create(); md.update('The quick brown fox jumps over the lazy dog'); console.log(md.digest().toHex()); // output: 9e107d9d372bb6826bd81d3542a419d6 ``` <a name="hmac" /> ### HMAC Provides [HMAC][] w/any supported message digest algorithm. __Examples__ ```js var hmac = forge.hmac.create(); hmac.start('sha1', 'Jefe'); hmac.update('what do ya want for nothing?'); console.log(hmac.digest().toHex()); // output: effcdf6ae5eb2fa2d27416d5f184df9c259a7c79 ``` Utilities --------- <a name="prime" /> ### Prime Provides an API for generating large, random, probable primes. __Examples__ ```js // generate a random prime on the main JS thread var bits = 1024; forge.prime.generateProbablePrime(bits, function(err, num) { console.log('random prime', num.toString(16)); }); // generate a random prime using Web Workers (if available, otherwise // falls back to the main thread) var bits = 1024; var options = { algorithm: { name: 'PRIMEINC', workers: -1 // auto-optimize # of workers } }; forge.prime.generateProbablePrime(bits, options, function(err, num) { console.log('random prime', num.toString(16)); }); ``` <a name="prng" /> ### PRNG Provides a [Fortuna][]-based cryptographically-secure pseudo-random number generator, to be used with a cryptographic function backend, e.g. [AES][]. An implementation using [AES][] as a backend is provided. An API for collecting entropy is given, though if window.crypto.getRandomValues is available, it will be used automatically. __Examples__ ```js // get some random bytes synchronously var bytes = forge.random.getBytesSync(32); console.log(forge.util.bytesToHex(bytes)); // get some random bytes asynchronously forge.random.getBytes(32, function(err, bytes) { console.log(forge.util.bytesToHex(bytes)); }); // collect some entropy if you'd like forge.random.collect(someRandomBytes); jQuery().mousemove(function(e) { forge.random.collectInt(e.clientX, 16); forge.random.collectInt(e.clientY, 16); }); // specify a seed file for use with the synchronous API if you'd like forge.random.seedFileSync = function(needed) { // get 'needed' number of random bytes from somewhere return fetchedRandomBytes; }; // specify a seed file for use with the asynchronous API if you'd like forge.random.seedFile = function(needed, callback) { // get the 'needed' number of random bytes from somewhere callback(null, fetchedRandomBytes); }); // register the main thread to send entropy or a Web Worker to receive // entropy on demand from the main thread forge.random.registerWorker(self); // generate a new instance of a PRNG with no collected entropy var myPrng = forge.random.createInstance(); ``` <a name="task" /> ### Tasks Provides queuing and synchronizing tasks in a web application. __Examples__ ```js // TODO ``` <a name="util" /> ### Utilities Provides utility functions, including byte buffer support, base64, bytes to/from hex, zlib inflate/deflate, etc. __Examples__ ```js // encode/decode base64 var encoded = forge.util.encode64(str); var str = forge.util.decode64(encoded); // encode/decode UTF-8 var encoded = forge.util.encodeUtf8(str); var str = forge.util.decodeUtf8(encoded); // bytes to/from hex var bytes = forge.util.hexToBytes(hex); var hex = forge.util.bytesToHex(bytes); // create an empty byte buffer var buffer = forge.util.createBuffer(); // create a byte buffer from raw binary bytes var buffer = forge.util.createBuffer(input, 'raw'); // create a byte buffer from utf8 bytes var buffer = forge.util.createBuffer(input, 'utf8'); // get the length of the buffer in bytes buffer.length(); // put bytes into the buffer buffer.putBytes(bytes); // put a 32-bit integer into the buffer buffer.putInt32(10); // buffer to hex buffer.toHex(); // get a copy of the bytes in the buffer bytes.bytes(/* count */); // empty this buffer and get its contents bytes.getBytes(/* count */); // convert a forge buffer into a Node.js Buffer // make sure you specify the encoding as 'binary' var forgeBuffer = forge.util.createBuffer(); var nodeBuffer = new Buffer(forgeBuffer.getBytes(), 'binary'); // convert a Node.js Buffer into a forge buffer // make sure you specify the encoding as 'binary' var nodeBuffer = new Buffer(); var forgeBuffer = forge.util.createBuffer(nodeBuffer.toString('binary')); // parse a URL var parsed = forge.util.parseUrl('http://example.com/foo?bar=baz'); // parsed.scheme, parsed.host, parsed.port, parsed.path, parsed.fullHost ``` <a name="log" /> ### Logging Provides logging to a javascript console using various categories and levels of verbosity. __Examples__ ```js // TODO ``` <a name="debug" /> ### Debugging Provides storage of debugging information normally inaccessible in closures for viewing/investigation. __Examples__ ```js // TODO ``` <a name="flash" /> ### Flash Networking Support The [flash README](./flash/README.md) provides details on rebuilding the optional Flash component used for networking. It also provides details on Policy Server support. Security Considerations ----------------------- When using this code please keep the following in mind: - Cryptography is hard. Please review and test this code before depending on it for critical functionality. - The nature of JavaScript is that execution of this code depends on trusting a very large set of JavaScript tools and systems. Consider runtime variations, runtime characteristics, runtime optimization, code optimization, code minimization, code obfuscation, bundling tools, possible bugs, the Forge code itself, and so on. - If using pre-built bundles from [Bower][] or similar be aware someone else ran the tools to create those files. - Use a secure transport channel such as [TLS][] to load scripts and consider using additional security mechanisms such as [Subresource Integrity][] script attributes. - Use "native" functionality where possible. This can be critical when dealing with performance and random number generation. Note that the JavaScript random number algorithms should perform well if given suitable entropy. - Understand possible attacks against cryptographic systems. For instance side channel and timing attacks may be possible due to the difficulty in implementing constant time algorithms in pure JavaScript. - Certain features in this library are less susceptible to attacks depending on usage. This primarily includes features that deal with data format manipulation or those that are not involved in communication. Library Background ------------------ * http://digitalbazaar.com/2010/07/20/javascript-tls-1/ * http://digitalbazaar.com/2010/07/20/javascript-tls-2/ Contact ------- * Code: https://github.com/digitalbazaar/forge * Bugs: https://github.com/digitalbazaar/forge/issues * Email: [email protected] * IRC: [#forgejs][] on [freenode][] Donations --------- Financial support is welcome and helps contribute to futher development: * For [PayPal][] please send to [email protected]. * Something else? Please contact [email protected]. [#forgejs]: https://webchat.freenode.net/?channels=#forgejs [0.6.x]: https://github.com/digitalbazaar/forge/tree/0.6.x [3DES]: http://en.wikipedia.org/wiki/Triple_DES [AES]: http://en.wikipedia.org/wiki/Advanced_Encryption_Standard [ASN.1]: http://en.wikipedia.org/wiki/ASN.1 [Bower]: https://bower.io/ [Browserify]: http://browserify.org/ [CBC]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation [CFB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation [CTR]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation [CommonJS]: https://en.wikipedia.org/wiki/CommonJS [DES]: http://en.wikipedia.org/wiki/Data_Encryption_Standard [ECB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation [Fortuna]: http://en.wikipedia.org/wiki/Fortuna_(PRNG) [GCM]: http://en.wikipedia.org/wiki/GCM_mode [HMAC]: http://en.wikipedia.org/wiki/HMAC [JavaScript]: http://en.wikipedia.org/wiki/JavaScript [Karma]: https://karma-runner.github.io/ [MD5]: http://en.wikipedia.org/wiki/MD5 [Node.js]: http://nodejs.org/ [OFB]: http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation [PKCS#10]: http://en.wikipedia.org/wiki/Certificate_signing_request [PKCS#12]: http://en.wikipedia.org/wiki/PKCS_%E2%99%AF12 [PKCS#5]: http://en.wikipedia.org/wiki/PKCS [PKCS#7]: http://en.wikipedia.org/wiki/Cryptographic_Message_Syntax [PayPal]: https://www.paypal.com/ [RC2]: http://en.wikipedia.org/wiki/RC2 [SHA-1]: http://en.wikipedia.org/wiki/SHA-1 [SHA-256]: http://en.wikipedia.org/wiki/SHA-256 [SHA-384]: http://en.wikipedia.org/wiki/SHA-384 [SHA-512]: http://en.wikipedia.org/wiki/SHA-512 [Subresource Integrity]: https://www.w3.org/TR/SRI/ [TLS]: http://en.wikipedia.org/wiki/Transport_Layer_Security [UMD]: https://github.com/umdjs/umd [X.509]: http://en.wikipedia.org/wiki/X.509 [freenode]: https://freenode.net/ [unpkg]: https://unpkg.com/ [webpack]: https://webpack.github.io/ [TweetNaCl]: https://github.com/dchest/tweetnacl-js # balanced-match Match balanced string pairs, like `{` and `}` or `<b>` and `</b>`. Supports regular expressions as well! [![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) [![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) [![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) ## Example Get the first matching pair of braces: ```js var balanced = require('balanced-match'); console.log(balanced('{', '}', 'pre{in{nested}}post')); console.log(balanced('{', '}', 'pre{first}between{second}post')); console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); ``` The matches are: ```bash $ node example.js { start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } { start: 3, end: 9, pre: 'pre', body: 'first', post: 'between{second}post' } { start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } ``` ## API ### var m = balanced(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an object with those keys: * **start** the index of the first match of `a` * **end** the index of the matching `b` * **pre** the preamble, `a` and `b` not included * **body** the match, `a` and `b` not included * **post** the postscript, `a` and `b` not included If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. ### var r = balanced.range(a, b, str) For the first non-nested matching pair of `a` and `b` in `str`, return an array with indexes: `[ <a index>, <b index> ]`. If there's no match, `undefined` will be returned. If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. ## Installation With [npm](https://npmjs.org) do: ```bash npm install balanced-match ``` ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <h1 align="center">connect-history-api-fallback</h1> <p align="center">Middleware to proxy requests through a specified index page, useful for Single Page Applications that utilise the HTML5 History API.</p> [![Build Status](https://travis-ci.org/bripkens/connect-history-api-fallback.svg?branch=master)](https://travis-ci.org/bripkens/connect-history-api-fallback) [![Dependency Status](https://david-dm.org/bripkens/connect-history-api-fallback/master.svg)](https://david-dm.org/bripkens/connect-history-api-fallback/master) [![NPM](https://nodei.co/npm/connect-history-api-fallback.png?downloads=true&downloadRank=true)](https://nodei.co/npm/connect-history-api-fallback/) <h2>Table of Contents</h2> <!-- TOC depthFrom:2 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 --> - [Introduction](#introduction) - [Usage](#usage) - [Options](#options) - [index](#index) - [rewrites](#rewrites) - [verbose](#verbose) - [htmlAcceptHeaders](#htmlacceptheaders) - [disableDotRule](#disabledotrule) <!-- /TOC --> ## Introduction Single Page Applications (SPA) typically only utilise one index file that is accessible by web browsers: usually `index.html`. Navigation in the application is then commonly handled using JavaScript with the help of the [HTML5 History API](http://www.w3.org/html/wg/drafts/html/master/single-page.html#the-history-interface). This results in issues when the user hits the refresh button or is directly accessing a page other than the landing page, e.g. `/help` or `/help/online` as the web server bypasses the index file to locate the file at this location. As your application is a SPA, the web server will fail trying to retrieve the file and return a *404 - Not Found* message to the user. This tiny middleware addresses some of the issues. Specifically, it will change the requested location to the index you specify (default being `/index.html`) whenever there is a request which fulfills the following criteria: 1. The request is a GET request 2. which accepts `text/html`, 3. is not a direct file request, i.e. the requested path does not contain a `.` (DOT) character and 4. does not match a pattern provided in options.rewrites (see options below) ## Usage The middleware is available through NPM and can easily be added. ``` npm install --save connect-history-api-fallback ``` Import the library ```javascript var history = require('connect-history-api-fallback'); ``` Now you only need to add the middleware to your application like so ```javascript var connect = require('connect'); var app = connect() .use(history()) .listen(3000); ``` Of course you can also use this piece of middleware with express: ```javascript var express = require('express'); var app = express(); app.use(history()); ``` ## Options You can optionally pass options to the library when obtaining the middleware ```javascript var middleware = history({}); ``` ### index Override the index (default `/index.html`) ```javascript history({ index: '/default.html' }); ``` ### rewrites Override the index when the request url matches a regex pattern. You can either rewrite to a static string or use a function to transform the incoming request. The following will rewrite a request that matches the `/\/soccer/` pattern to `/soccer.html`. ```javascript history({ rewrites: [ { from: /\/soccer/, to: '/soccer.html'} ] }); ``` Alternatively functions can be used to have more control over the rewrite process. For instance, the following listing shows how requests to `/libs/jquery/jquery.1.12.0.min.js` and the like can be routed to `./bower_components/libs/jquery/jquery.1.12.0.min.js`. You can also make use of this if you have an API version in the URL path. ```javascript history({ rewrites: [ { from: /^\/libs\/.*$/, to: function(context) { return '/bower_components' + context.parsedUrl.pathname; } } ] }); ``` The function will always be called with a context object that has the following properties: - **parsedUrl**: Information about the URL as provided by the [URL module's](https://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost) `url.parse`. - **match**: An Array of matched results as provided by `String.match(...)`. - **request**: The HTTP request object. ### verbose This middleware does not log any information by default. If you wish to activate logging, then you can do so via the `verbose` option or by specifying a logger function. ```javascript history({ verbose: true }); ``` Alternatively use your own logger ```javascript history({ logger: console.log.bind(console) }); ``` ### htmlAcceptHeaders Override the default `Accepts:` headers that are queried when matching HTML content requests (Default: `['text/html', '*/*']`). ```javascript history({ htmlAcceptHeaders: ['text/html', 'application/xhtml+xml'] }) ``` ### disableDotRule Disables the dot rule mentioned above: > […] is not a direct file request, i.e. the requested path does not contain a `.` (DOT) character […] ```javascript history({ disableDotRule: true }) ``` An ini format parser and serializer for node. Sections are treated as nested objects. Items before the first heading are saved on the object directly. ## Usage Consider an ini-file `config.ini` that looks like this: ; this comment is being ignored scope = global [database] user = dbuser password = dbpassword database = use_this_database [paths.default] datadir = /var/lib/data array[] = first value array[] = second value array[] = third value You can read, manipulate and write the ini-file like so: var fs = require('fs') , ini = require('ini') var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8')) config.scope = 'local' config.database.database = 'use_another_database' config.paths.default.tmpdir = '/tmp' delete config.paths.default.datadir config.paths.default.array.push('fourth value') fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' })) This will result in a file called `config_modified.ini` being written to the filesystem with the following content: [section] scope=local [section.database] user=dbuser password=dbpassword database=use_another_database [section.paths.default] tmpdir=/tmp array[]=first value array[]=second value array[]=third value array[]=fourth value ## API ### decode(inistring) Decode the ini-style formatted `inistring` into a nested object. ### parse(inistring) Alias for `decode(inistring)` ### encode(object, [options]) Encode the object `object` into an ini-style formatted string. If the optional parameter `section` is given, then all top-level properties of the object are put into this section and the `section`-string is prepended to all sub-sections, see the usage example above. The `options` object may contain the following: * `section` A string which will be the first `section` in the encoded ini data. Defaults to none. * `whitespace` Boolean to specify whether to put whitespace around the `=` character. By default, whitespace is omitted, to be friendly to some persnickety old parsers that don't tolerate it well. But some find that it's more human-readable and pretty with the whitespace. For backwards compatibility reasons, if a `string` options is passed in, then it is assumed to be the `section` value. ### stringify(object, [options]) Alias for `encode(object, [options])` ### safe(val) Escapes the string `val` such that it is safe to be used as a key or value in an ini-file. Basically escapes quotes. For example ini.safe('"unsafe string"') would result in "\"unsafe string\"" ### unsafe(val) Unescapes the string `val` # is-data-descriptor [![NPM version](https://img.shields.io/npm/v/is-data-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-data-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-data-descriptor.svg?style=flat)](https://npmjs.org/package/is-data-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-data-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-data-descriptor) > Returns true if a value has the characteristics of a valid JavaScript data descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-data-descriptor ``` ## Usage ```js var isDataDesc = require('is-data-descriptor'); ``` ## Examples `true` when the descriptor has valid properties with valid values. ```js // `value` can be anything isDataDesc({value: 'foo'}) isDataDesc({value: function() {}}) isDataDesc({value: true}) //=> true ``` `false` when not an object ```js isDataDesc('a') //=> false isDataDesc(null) //=> false isDataDesc([]) //=> false ``` `false` when the object has invalid properties ```js isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', bar: 'baz'}) //=> false isDataDesc({value: 'foo', get: function(){}}) //=> false isDataDesc({get: function(){}, value: 'foo'}) //=> false ``` `false` when a value is not the correct type ```js isDataDesc({value: 'foo', enumerable: 'foo'}) //=> false isDataDesc({value: 'foo', configurable: 'foo'}) //=> false isDataDesc({value: 'foo', writable: 'foo'}) //=> false ``` ## Valid properties The only valid data descriptor properties are the following: * `configurable` (required) * `enumerable` (required) * `value` (optional) * `writable` (optional) To be a valid data descriptor, either `value` or `writable` must be defined. **Invalid properties** A descriptor may have additional _invalid_ properties (an error will **not** be thrown). ```js var foo = {}; Object.defineProperty(foo, 'bar', { enumerable: true, whatever: 'blah', // invalid, but doesn't cause an error get: function() { return 'baz'; } }); console.log(foo.bar); //=> 'baz' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 21 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # snapdragon-node [![NPM version](https://img.shields.io/npm/v/snapdragon-node.svg?style=flat)](https://www.npmjs.com/package/snapdragon-node) [![NPM monthly downloads](https://img.shields.io/npm/dm/snapdragon-node.svg?style=flat)](https://npmjs.org/package/snapdragon-node) [![NPM total downloads](https://img.shields.io/npm/dt/snapdragon-node.svg?style=flat)](https://npmjs.org/package/snapdragon-node) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/snapdragon-node.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/snapdragon-node) > Snapdragon utility for creating a new AST node in custom code, such as plugins. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save snapdragon-node ``` ## Usage With [snapdragon](https://github.com/jonschlinkert/snapdragon) v0.9.0 and higher you can use `this.node()` to create a new `Node`, whenever it makes sense. ```js var Node = require('snapdragon-node'); var Snapdragon = require('snapdragon'); var snapdragon = new Snapdragon(); // example usage inside a parser visitor function snapdragon.parser.set('foo', function() { // get the current "start" position var pos = this.position(); // returns the match if regex matches the substring // at the current position on `parser.input` var match = this.match(/foo/); if (match) { // call "pos" on the node, to set the start and end // positions, and return the node to push it onto the AST // (snapdragon will push the node onto the correct // nodes array, based on the stack) return pos(new Node({type: 'bar', val: match[0]})); } }); ``` ## API ### [Node](index.js#L22) Create a new AST `Node` with the given `val` and `type`. **Params** * `val` **{String|Object}**: Pass a matched substring, or an object to merge onto the node. * `type` **{String}**: The node type to use when `val` is a string. * `returns` **{Object}**: node instance **Example** ```js var node = new Node('*', 'Star'); var node = new Node({type: 'star', val: '*'}); ``` ### [.isNode](index.js#L61) Returns true if the given value is a node. **Params** * `node` **{Object}** * `returns` **{Boolean}** **Example** ```js var Node = require('snapdragon-node'); var node = new Node({type: 'foo'}); console.log(Node.isNode(node)); //=> true console.log(Node.isNode({})); //=> false ``` ### [.define](index.js#L80) Define a non-enumberable property on the node instance. Useful for adding properties that shouldn't be extended or visible during debugging. **Params** * `name` **{String}** * `val` **{any}** * `returns` **{Object}**: returns the node instance **Example** ```js var node = new Node(); node.define('foo', 'something non-enumerable'); ``` ### [.isEmpty](index.js#L100) Returns true if `node.val` is an empty string, or `node.nodes` does not contain any non-empty text nodes. **Params** * `fn` **{Function}**: (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes. * `returns` **{Boolean}** **Example** ```js var node = new Node({type: 'text'}); node.isEmpty(); //=> true node.val = 'foo'; node.isEmpty(); //=> false ``` ### [.push](index.js#L118) Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and set `foo` as `bar.parent`. **Params** * `node` **{Object}** * `returns` **{Number}**: Returns the length of `node.nodes` **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); foo.push(bar); ``` ### [.unshift](index.js#L140) Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and set `foo` as `bar.parent`. **Params** * `node` **{Object}** * `returns` **{Number}**: Returns the length of `node.nodes` **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); foo.unshift(bar); ``` ### [.pop](index.js#L167) Pop a node from `node.nodes`. * `returns` **{Number}**: Returns the popped `node` **Example** ```js var node = new Node({type: 'foo'}); node.push(new Node({type: 'a'})); node.push(new Node({type: 'b'})); node.push(new Node({type: 'c'})); node.push(new Node({type: 'd'})); console.log(node.nodes.length); //=> 4 node.pop(); console.log(node.nodes.length); //=> 3 ``` ### [.shift](index.js#L190) Shift a node from `node.nodes`. * `returns` **{Object}**: Returns the shifted `node` **Example** ```js var node = new Node({type: 'foo'}); node.push(new Node({type: 'a'})); node.push(new Node({type: 'b'})); node.push(new Node({type: 'c'})); node.push(new Node({type: 'd'})); console.log(node.nodes.length); //=> 4 node.shift(); console.log(node.nodes.length); //=> 3 ``` ### [.remove](index.js#L205) Remove `node` from `node.nodes`. **Params** * `node` **{Object}** * `returns` **{Object}**: Returns the removed node. **Example** ```js node.remove(childNode); ``` ### [.find](index.js#L231) Get the first child node from `node.nodes` that matches the given `type`. If `type` is a number, the child node at that index is returned. **Params** * `type` **{String}** * `returns` **{Object}**: Returns a child node or undefined. **Example** ```js var child = node.find(1); //<= index of the node to get var child = node.find('foo'); //<= node.type of a child node var child = node.find(/^(foo|bar)$/); //<= regex to match node.type var child = node.find(['foo', 'bar']); //<= array of node.type(s) ``` ### [.isType](index.js#L249) Return true if the node is the given `type`. **Params** * `type` **{String}** * `returns` **{Boolean}** **Example** ```js var node = new Node({type: 'bar'}); cosole.log(node.isType('foo')); // false cosole.log(node.isType(/^(foo|bar)$/)); // true cosole.log(node.isType(['foo', 'bar'])); // true ``` ### [.hasType](index.js#L270) Return true if the `node.nodes` has the given `type`. **Params** * `type` **{String}** * `returns` **{Boolean}** **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); foo.push(bar); cosole.log(foo.hasType('qux')); // false cosole.log(foo.hasType(/^(qux|bar)$/)); // true cosole.log(foo.hasType(['qux', 'bar'])); // true ``` * `returns` **{Array}** **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); foo.push(bar); foo.push(baz); console.log(bar.siblings.length) // 2 console.log(baz.siblings.length) // 2 ``` * `returns` **{Number}** **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); var qux = new Node({type: 'qux'}); foo.push(bar); foo.push(baz); foo.unshift(qux); console.log(bar.index) // 1 console.log(baz.index) // 2 console.log(qux.index) // 0 ``` * `returns` **{Object}** **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); foo.push(bar); foo.push(baz); console.log(baz.prev.type) // 'bar' ``` * `returns` **{Object}** **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); foo.push(bar); foo.push(baz); console.log(bar.siblings.length) // 2 console.log(baz.siblings.length) // 2 ``` * `returns` **{Object}**: The first node, or undefiend **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); var qux = new Node({type: 'qux'}); foo.push(bar); foo.push(baz); foo.push(qux); console.log(foo.first.type) // 'bar' ``` * `returns` **{Object}**: The last node, or undefiend **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); var qux = new Node({type: 'qux'}); foo.push(bar); foo.push(baz); foo.push(qux); console.log(foo.last.type) // 'qux' ``` * `returns` **{Object}**: The last node, or undefiend **Example** ```js var foo = new Node({type: 'foo'}); var bar = new Node({type: 'bar'}); var baz = new Node({type: 'baz'}); var qux = new Node({type: 'qux'}); foo.push(bar); foo.push(baz); foo.push(qux); console.log(foo.last.type) // 'qux' ``` ## Release history Changelog entries are classified using the following labels from [keep-a-changelog](https://github.com/olivierlacan/keep-a-changelog): * `added`: for new features * `changed`: for changes in existing functionality * `deprecated`: for once-stable features removed in upcoming releases * `removed`: for deprecated features removed in this release * `fixed`: for any bug fixes Custom labels used in this changelog: * `dependencies`: bumps dependencies * `housekeeping`: code re-organization, minor edits, or other changes that don't fit in one of the other categories. ### [2.0.0] - 2017-05-01 **Changed** * `.unshiftNode` was renamed to [.unshift](#unshift) * `.pushNode` was renamed to [.push](#push) * `.getNode` was renamed to [.find](#find) **Added** * [.isNode](#isNode) * [.isEmpty](#isEmpty) * [.pop](#pop) * [.shift](#shift) * [.remove](#remove) ### [0.1.0] First release. ## About ### Related projects * [breakdance](https://www.npmjs.com/package/breakdance): Breakdance is a node.js library for converting HTML to markdown. Highly pluggable, flexible and easy… [more](http://breakdance.io) | [homepage](http://breakdance.io "Breakdance is a node.js library for converting HTML to markdown. Highly pluggable, flexible and easy to use. It's time for your markup to get down.") * [snapdragon-capture](https://www.npmjs.com/package/snapdragon-capture): Snapdragon plugin that adds a capture method to the parser instance. | [homepage](https://github.com/jonschlinkert/snapdragon-capture "Snapdragon plugin that adds a capture method to the parser instance.") * [snapdragon-cheerio](https://www.npmjs.com/package/snapdragon-cheerio): Snapdragon plugin for converting a cheerio AST to a snapdragon AST. | [homepage](https://github.com/jonschlinkert/snapdragon-cheerio "Snapdragon plugin for converting a cheerio AST to a snapdragon AST.") * [snapdragon-util](https://www.npmjs.com/package/snapdragon-util): Utilities for the snapdragon parser/compiler. | [homepage](https://github.com/jonschlinkert/snapdragon-util "Utilities for the snapdragon parser/compiler.") * [snapdragon](https://www.npmjs.com/package/snapdragon): Easy-to-use plugin system for creating powerful, fast and versatile parsers and compilers, with built-in source-map… [more](https://github.com/jonschlinkert/snapdragon) | [homepage](https://github.com/jonschlinkert/snapdragon "Easy-to-use plugin system for creating powerful, fast and versatile parsers and compilers, with built-in source-map support.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards. ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 25, 2017._ # regjsgen [![Build status](https://travis-ci.org/bnjmnt4n/regjsgen.svg?branch=master)](https://travis-ci.org/bnjmnt4n/regjsgen) [![Code coverage status](https://codecov.io/gh/bnjmnt4n/regjsgen/branch/master/graph/badge.svg)](https://codecov.io/gh/bnjmnt4n/regjsgen) Generate regular expressions from [regjsparser](https://github.com/jviereck/regjsparser)’s AST. ## Installation ```bash npm install --save regjsgen ``` ## API ### `regjsgen.generate(ast)` This function accepts an abstract syntax tree representing a regular expression, and returns the generated regular expression string. ```js var regjsparser = require('regjsparser'); var regjsgen = require('regjsgen'); // Generate an AST with `regjsparser`. var ast = regjsparser.parse(regex); // Modify AST // … // Generate `RegExp` string with `regjsgen`. regex = regjsgen.generate(ast); ``` ## Support Tested in Node.js 0.10, 0.12, 4, 6 and 8. # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` `disable()` Will disable all namespaces. The functions returns the namespaces currently enabled (and skipped). This can be useful if you want to disable debugging temporarily without knowing what was enabled to begin with. For example: ```js let debug = require('debug'); debug.enable('foo:*,-foo:bar'); let namespaces = debug.disable(); debug.enable(namespaces); ``` Note: There is no guarantee that the string will be identical to the initial enable string, but semantically they will be identical. ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # is-accessor-descriptor [![NPM version](https://img.shields.io/npm/v/is-accessor-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-accessor-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-accessor-descriptor.svg?style=flat)](https://npmjs.org/package/is-accessor-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-accessor-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-accessor-descriptor) > Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-accessor-descriptor ``` ## Usage ```js var isAccessor = require('is-accessor-descriptor'); isAccessor({get: function() {}}); //=> true ``` You may also pass an object and property name to check if the property is an accessor: ```js isAccessor(foo, 'bar'); ``` ## Examples `false` when not an object ```js isAccessor('a') isAccessor(null) isAccessor([]) //=> false ``` `true` when the object has valid properties and the properties all have the correct JavaScript types: ```js isAccessor({get: noop, set: noop}) isAccessor({get: noop}) isAccessor({set: noop}) //=> true ``` `false` when the object has invalid properties ```js isAccessor({get: noop, set: noop, bar: 'baz'}) isAccessor({get: noop, writable: true}) isAccessor({get: noop, value: true}) //=> false ``` `false` when an accessor is not a function ```js isAccessor({get: noop, set: 'baz'}) isAccessor({get: 'foo', set: noop}) isAccessor({get: 'foo', bar: 'baz'}) isAccessor({get: 'foo', set: 'baz'}) //=> false ``` `false` when a value is not the correct type ```js isAccessor({get: noop, set: noop, enumerable: 'foo'}) isAccessor({set: noop, configurable: 'foo'}) isAccessor({get: noop, configurable: 'foo'}) //=> false ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 22 | [jonschlinkert](https://github.com/jonschlinkert) | | 2 | [realityking](https://github.com/realityking) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 01, 2017._ # pump pump is a small node module that pipes streams together and destroys all of them if one of them closes. ``` npm install pump ``` [![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump) ## What problem does it solve? When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error. You are also not able to provide a callback to tell when then pipe has finished. pump does these two things for you ## Usage Simply pass the streams you want to pipe together to pump and add an optional callback ``` js var pump = require('pump') var fs = require('fs') var source = fs.createReadStream('/dev/random') var dest = fs.createWriteStream('/dev/null') pump(source, dest, function(err) { console.log('pipe finished', err) }) setTimeout(function() { dest.destroy() // when dest is closed pump will destroy source }, 1000) ``` You can use pump to pipe more than two streams together as well ``` js var transform = someTransformStream() pump(source, transform, anotherTransform, dest, function(err) { console.log('pipe finished', err) }) ``` If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed. ## License MIT ## Related `pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one. Browser-friendly inheritance fully compatible with standard node.js [inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). This package exports standard `inherits` from node.js `util` module in node environment, but also provides alternative browser-friendly implementation through [browser field](https://gist.github.com/shtylman/4339901). Alternative implementation is a literal copy of standard one located in standalone module to avoid requiring of `util`. It also has a shim for old browsers with no `Object.create` support. While keeping you sure you are using standard `inherits` implementation in node.js environment, it allows bundlers such as [browserify](https://github.com/substack/node-browserify) to not include full `util` package to your client code if all you need is just `inherits` function. It worth, because browser shim for `util` package is large and `inherits` is often the single function you need from it. It's recommended to use this package instead of `require('util').inherits` for any code that has chances to be used not only in node.js but in browser too. ## usage ```js var inherits = require('inherits'); // then use exactly as the standard one ``` ## note on version ~1.0 Version ~1.0 had completely different motivation and is not compatible neither with 2.0 nor with standard node.js `inherits`. If you are using version ~1.0 and planning to switch to ~2.0, be careful: * new version uses `super_` instead of `super` for referencing superclass * new version overwrites current prototype while old one preserves any existing fields on it # lru cache A cache object that deletes the least-recently-used items. [![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) ## Installation: ```javascript npm install lru-cache --save ``` ## Usage: ```javascript var LRU = require("lru-cache") , options = { max: 500 , length: function (n, key) { return n * 2 + key.length } , dispose: function (key, n) { n.close() } , maxAge: 1000 * 60 * 60 } , cache = LRU(options) , otherCache = LRU(50) // sets just the max size cache.set("key", "value") cache.get("key") // "value" // non-string keys ARE fully supported // but note that it must be THE SAME object, not // just a JSON-equivalent object. var someObject = { a: 1 } cache.set(someObject, 'a value') // Object keys are not toString()-ed cache.set('[object Object]', 'a different value') assert.equal(cache.get(someObject), 'a value') // A similar object with same keys/values won't work, // because it's a different object identity assert.equal(cache.get({ a: 1 }), undefined) cache.reset() // empty the cache ``` If you put more stuff in it, then items will fall out. If you try to put an oversized thing in it, then it'll fall out right away. ## Options * `max` The maximum size of the cache, checked by applying the length function to all values in the cache. Not setting this is kind of silly, since that's the whole purpose of this lib, but it defaults to `Infinity`. * `maxAge` 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. * `length` Function that is used to calculate the length of stored items. If you're storing strings or buffers, then you probably want to do something like `function(n, key){return n.length}`. The default is `function(){return 1}`, which is fine if you want to store `max` like-sized things. The item is passed as the first argument, and the key is passed as the second argumnet. * `dispose` Function that is called on items when they are dropped from the cache. This can be handy if you want to close file descriptors or do other cleanup tasks when items are no longer accessible. Called with `key, value`. It's called *before* actually removing the item from the internal cache, so if you want to immediately put it back in, you'll have to do that in a `nextTick` or `setTimeout` callback or it won't do anything. * `stale` By default, if you set a `maxAge`, it'll only actually pull stale items out of the cache when you `get(key)`. (That is, it's not pre-emptively doing a `setTimeout` or anything.) If you set `stale:true`, it'll return the stale value before deleting it. If you don't set this, then it'll return `undefined` when you try to get a stale entry, as if it had already been deleted. * `noDisposeOnSet` By default, if you set a `dispose()` method, then it'll be called whenever a `set()` operation overwrites an existing key. If you set this option, `dispose()` will only be called when a key falls out of the cache, not when it is overwritten. ## API * `set(key, value, maxAge)` * `get(key) => value` Both of these will update the "recently used"-ness of the key. They do what you think. `maxAge` is optional and overrides the cache `maxAge` option if provided. If the key is not found, `get()` will return `undefined`. The key and val can be any value. * `peek(key)` Returns the key value (or `undefined` if not found) without updating the "recently used"-ness of the key. (If you find yourself using this a lot, you *might* be using the wrong sort of data structure, but there are some use cases where it's handy.) * `del(key)` Deletes a key out of the cache. * `reset()` Clear the cache entirely, throwing away all values. * `has(key)` Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. * `forEach(function(value,key,cache), [thisp])` Just like `Array.prototype.forEach`. Iterates over all the keys in the cache, in order of recent-ness. (Ie, more recently used items are iterated over first.) * `rforEach(function(value,key,cache), [thisp])` The same as `cache.forEach(...)` but items are iterated over in reverse order. (ie, less recently used items are iterated over first.) * `keys()` Return an array of the keys in the cache. * `values()` Return an array of the values in the cache. * `length` Return total length of objects in cache taking into account `length` options function. * `itemCount` Return total quantity of objects currently in cache. Note, that `stale` (see options) items are returned as part of this item count. * `dump()` Return an array of the cache entries ready for serialization and usage with 'destinationCache.load(arr)`. * `load(cacheEntriesArray)` Loads another cache entries array, obtained with `sourceCache.dump()`, into the cache. The destination cache is reset before loading new entries * `prune()` Manually iterates over the entire cache proactively pruning old entries # split-string [![NPM version](https://img.shields.io/npm/v/split-string.svg?style=flat)](https://www.npmjs.com/package/split-string) [![NPM monthly downloads](https://img.shields.io/npm/dm/split-string.svg?style=flat)](https://npmjs.org/package/split-string) [![NPM total downloads](https://img.shields.io/npm/dt/split-string.svg?style=flat)](https://npmjs.org/package/split-string) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/split-string.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/split-string) > Split a string on a character except when the character is escaped. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save split-string ``` <!-- section: Why use this? --> <details> <summary><strong>Why use this?</strong></summary> <br> Although it's easy to split on a string: ```js console.log('a.b.c'.split('.')); //=> ['a', 'b', 'c'] ``` It's more challenging to split a string whilst respecting escaped or quoted characters. **Bad** ```js console.log('a\\.b.c'.split('.')); //=> ['a\\', 'b', 'c'] console.log('"a.b.c".d'.split('.')); //=> ['"a', 'b', 'c"', 'd'] ``` **Good** ```js var split = require('split-string'); console.log(split('a\\.b.c')); //=> ['a.b', 'c'] console.log(split('"a.b.c".d')); //=> ['a.b.c', 'd'] ``` See the [options](#options) to learn how to choose the separator or retain quotes or escaping. <br> </details> ## Usage ```js var split = require('split-string'); split('a.b.c'); //=> ['a', 'b', 'c'] // respects escaped characters split('a.b.c\\.d'); //=> ['a', 'b', 'c.d'] // respects double-quoted strings split('a."b.c.d".e'); //=> ['a', 'b.c.d', 'e'] ``` **Brackets** Also respects brackets [unless disabled](#optionsbrackets): ```js split('a (b c d) e', ' '); //=> ['a', '(b c d)', 'e'] ``` ## Options ### options.brackets **Type**: `object|boolean` **Default**: `undefined` **Description** If enabled, split-string will not split inside brackets. The following brackets types are supported when `options.brackets` is `true`, ```js { '<': '>', '(': ')', '[': ']', '{': '}' } ``` Or, if object of brackets must be passed, each property on the object must be a bracket type, where the property key is the opening delimiter and property value is the closing delimiter. **Examples** ```js // no bracket support by default split('a.{b.c}'); //=> [ 'a', '{b', 'c}' ] // support all basic bracket types: "<>{}[]()" split('a.{b.c}', {brackets: true}); //=> [ 'a', '{b.c}' ] // also supports nested brackets split('a.{b.{c.d}.e}.f', {brackets: true}); //=> [ 'a', '{b.{c.d}.e}', 'f' ] // support only the specified brackets split('[a.b].(c.d)', {brackets: {'[': ']'}}); //=> [ '[a.b]', '(c', 'd)' ] ``` ### options.sep **Type**: `string` **Default**: `.` The separator/character to split on. **Example** ```js split('a.b,c', {sep: ','}); //=> ['a.b', 'c'] // you can also pass the separator as string as the last argument split('a.b,c', ','); //=> ['a.b', 'c'] ``` ### options.keepEscaping **Type**: `boolean` **Default**: `undefined` Keep backslashes in the result. **Example** ```js split('a.b\\.c'); //=> ['a', 'b.c'] split('a.b.\\c', {keepEscaping: true}); //=> ['a', 'b\.c'] ``` ### options.keepQuotes **Type**: `boolean` **Default**: `undefined` Keep single- or double-quotes in the result. **Example** ```js split('a."b.c.d".e'); //=> ['a', 'b.c.d', 'e'] split('a."b.c.d".e', {keepQuotes: true}); //=> ['a', '"b.c.d"', 'e'] split('a.\'b.c.d\'.e', {keepQuotes: true}); //=> ['a', '\'b.c.d\'', 'e'] ``` ### options.keepDoubleQuotes **Type**: `boolean` **Default**: `undefined` Keep double-quotes in the result. **Example** ```js split('a."b.c.d".e'); //=> ['a', 'b.c.d', 'e'] split('a."b.c.d".e', {keepDoubleQuotes: true}); //=> ['a', '"b.c.d"', 'e'] ``` ### options.keepSingleQuotes **Type**: `boolean` **Default**: `undefined` Keep single-quotes in the result. **Example** ```js split('a.\'b.c.d\'.e'); //=> ['a', 'b.c.d', 'e'] split('a.\'b.c.d\'.e', {keepSingleQuotes: true}); //=> ['a', '\'b.c.d\'', 'e'] ``` ## Customizer **Type**: `function` **Default**: `undefined` Pass a function as the last argument to customize how tokens are added to the array. **Example** ```js var arr = split('a.b', function(tok) { if (tok.arr[tok.arr.length - 1] === 'a') { tok.split = false; } }); console.log(arr); //=> ['a.b'] ``` **Properties** The `tok` object has the following properties: * `tok.val` (string) The current value about to be pushed onto the result array * `tok.idx` (number) the current index in the string * `tok.str` (string) the entire string * `tok.arr` (array) the result array ## Release history ### v3.0.0 - 2017-06-17 **Added** * adds support for brackets ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [deromanize](https://www.npmjs.com/package/deromanize): Convert roman numerals to arabic numbers (useful for books, outlines, documentation, slide decks, etc) | [homepage](https://github.com/jonschlinkert/deromanize "Convert roman numerals to arabic numbers (useful for books, outlines, documentation, slide decks, etc)") * [randomatic](https://www.npmjs.com/package/randomatic): Generate randomized strings of a specified length using simple character sequences. The original generate-password. | [homepage](https://github.com/jonschlinkert/randomatic "Generate randomized strings of a specified length using simple character sequences. The original generate-password.") * [repeat-string](https://www.npmjs.com/package/repeat-string): Repeat the given string n times. Fastest implementation for repeating a string. | [homepage](https://github.com/jonschlinkert/repeat-string "Repeat the given string n times. Fastest implementation for repeating a string.") * [romanize](https://www.npmjs.com/package/romanize): Convert numbers to roman numerals (useful for books, outlines, documentation, slide decks, etc) | [homepage](https://github.com/jonschlinkert/romanize "Convert numbers to roman numerals (useful for books, outlines, documentation, slide decks, etc)") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 28 | [jonschlinkert](https://github.com/jonschlinkert) | | 9 | [doowb](https://github.com/doowb) | ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on November 19, 2017._ # dns-txt Encode or decode the RDATA field in multicast DNS TXT records. For use with DNS-Based Service Discovery. For details see [RFC 6763](https://tools.ietf.org/html/rfc6763). [![Build status](https://travis-ci.org/watson/dns-txt.svg?branch=master)](https://travis-ci.org/watson/dns-txt) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard) [![abstract-encoding](https://img.shields.io/badge/abstract--encoding-compliant-brightgreen.svg?style=flat)](https://github.com/mafintosh/abstract-encoding) ## Installation ``` npm install dns-txt ``` ## Usage ```js var txt = require('dns-txt')() var obj = { foo: 1, bar: 2 } var enc = txt.encode(obj) // <Buffer 05 66 6f 6f 3d 31 05 62 61 72 3d 32> txt.decode(enc) // { foo: '1', bar: '2' } ``` ## API The encoder and decoder conforms to [RFC 6763](https://tools.ietf.org/html/rfc6763). ### Initialize The module exposes a constructor function which can be called with an optional options object: ```js var txt = require('dns-txt')({ binary: true }) ``` The options are: - `binary` - If set to `true` all values will be returned as `Buffer` objects. The default behavior is to turn all values into strings. But according to the RFC the values can be any binary data. If you expect binary data, use this option. #### `txt.encode(obj, [buffer], [offset])` Takes a key/value object and returns a buffer with the encoded TXT record. If a buffer is passed as the second argument the object should be encoded into that buffer. Otherwise a new buffer should be allocated If an offset is passed as the third argument the object should be encoded at that byte offset. The byte offset defaults to `0`. This module does not actively validate the key/value pairs, but keep the following in rules in mind: - To be RFC compliant, each key should conform with the rules as specified in [section 6.4](https://tools.ietf.org/html/rfc6763#section-6.4). - To be RFC compliant, each value should conform with the rules as specified in [section 6.5](https://tools.ietf.org/html/rfc6763#section-6.5). After encoding `txt.encode.bytes` is set to the amount of bytes used to encode the object. #### `txt.decode(buffer, [offset], [length])` Takes a buffer and returns a decoded key/value object. If an offset is passed as the second argument the object should be decoded from that byte offset. The byte offset defaults to `0`. Note that all keys will be lowercased and all values will be Buffer objects. After decoding `txt.decode.bytes` is set to the amount of bytes used to decode the object. #### `txt.encodingLength(obj)` Takes a single key/value object and returns the number of bytes that the given object would require if encoded. ## License MIT # util.promisify Polyfill for util.promisify in node versions &lt; v8 node v8.0.0 added support for a built-in `util.promisify`: https://github.com/nodejs/node/pull/12442/ This package provides the built-in `util.promisify` in node v8.0.0 and later, and a replacement in other environments. Note: this package requires a native ES5 environment, and for `Promise` to be globally available. It will throw upon requiring it if these are not present. If you want to write an option parser, and have it be good, there are two ways to do it. The Right Way, and the Wrong Way. The Wrong Way is to sit down and write an option parser. We've all done that. The Right Way is to write some complex configurable program with so many options that you hit the limit of your frustration just trying to manage them all, and defer it with duct-tape solutions until you see exactly to the core of the problem, and finally snap and write an awesome option parser. If you want to write an option parser, don't write an option parser. Write a package manager, or a source control system, or a service restarter, or an operating system. You probably won't end up with a good one of those, but if you don't give up, and you are relentless and diligent enough in your procrastination, you may just end up with a very nice option parser. ## USAGE ```javascript // my-program.js var nopt = require("nopt") , Stream = require("stream").Stream , path = require("path") , knownOpts = { "foo" : [String, null] , "bar" : [Stream, Number] , "baz" : path , "bloo" : [ "big", "medium", "small" ] , "flag" : Boolean , "pick" : Boolean , "many1" : [String, Array] , "many2" : [path, Array] } , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] , "b7" : ["--bar", "7"] , "m" : ["--bloo", "medium"] , "p" : ["--pick"] , "f" : ["--flag"] } // everything is optional. // knownOpts and shorthands default to {} // arg list defaults to process.argv // slice defaults to 2 , parsed = nopt(knownOpts, shortHands, process.argv, 2) console.log(parsed) ``` This would give you support for any of the following: ```console $ node my-program.js --foo "blerp" --no-flag { "foo" : "blerp", "flag" : false } $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag { bar: 7, foo: "Mr. Hand", flag: true } $ node my-program.js --foo "blerp" -f -----p { foo: "blerp", flag: true, pick: true } $ node my-program.js -fp --foofoo { foo: "Mr. Foo", flag: true, pick: true } $ node my-program.js --foofoo -- -fp # -- stops the flag parsing. { foo: "Mr. Foo", argv: { remain: ["-fp"] } } $ node my-program.js --blatzk -fp # unknown opts are ok. { blatzk: true, flag: true, pick: true } $ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value { blatzk: 1000, flag: true, pick: true } $ node my-program.js --no-blatzk -fp # unless they start with "no-" { blatzk: false, flag: true, pick: true } $ node my-program.js --baz b/a/z # known paths are resolved. { baz: "/Users/isaacs/b/a/z" } # if Array is one of the types, then it can take many # values, and will always be an array. The other types provided # specify what types are allowed in the list. $ node my-program.js --many1 5 --many1 null --many1 foo { many1: ["5", "null", "foo"] } $ node my-program.js --many2 foo --many2 bar { many2: ["/path/to/foo", "path/to/bar"] } ``` Read the tests at the bottom of `lib/nopt.js` for more examples of what this puppy can do. ## Types The following types are supported, and defined on `nopt.typeDefs` * String: A normal string. No parsing is done. * path: A file system path. Gets resolved against cwd if not absolute. * url: A url. If it doesn't parse, it isn't accepted. * Number: Must be numeric. * Date: Must parse as a date. If it does, and `Date` is one of the options, then it will return a Date object, not a string. * Boolean: Must be either `true` or `false`. If an option is a boolean, then it does not need a value, and its presence will imply `true` as the value. To negate boolean flags, do `--no-whatever` or `--whatever false` * NaN: Means that the option is strictly not allowed. Any value will fail. * Stream: An object matching the "Stream" class in node. Valuable for use when validating programmatically. (npm uses this to let you supply any WriteStream on the `outfd` and `logfd` config options.) * Array: If `Array` is specified as one of the types, then the value will be parsed as a list of options. This means that multiple values can be specified, and that the value will always be an array. If a type is an array of values not on this list, then those are considered valid values. For instance, in the example above, the `--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, and any other value will be rejected. When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be interpreted as their JavaScript equivalents. You can also mix types and values, or multiple types, in a list. For instance `{ blah: [Number, null] }` would allow a value to be set to either a Number or null. When types are ordered, this implies a preference, and the first type that can be used to properly interpret the value will be used. To define a new type, add it to `nopt.typeDefs`. Each item in that hash is an object with a `type` member and a `validate` method. The `type` member is an object that matches what goes in the type list. The `validate` method is a function that gets called with `validate(data, key, val)`. Validate methods should assign `data[key]` to the valid value of `val` if it can be handled properly, or return boolean `false` if it cannot. You can also call `nopt.clean(data, types, typeDefs)` to clean up a config object and remove its invalid properties. ## Error Handling By default, nopt outputs a warning to standard error when invalid values for known options are found. You can change this behavior by assigning a method to `nopt.invalidHandler`. This method will be called with the offending `nopt.invalidHandler(key, val, types)`. If no `nopt.invalidHandler` is assigned, then it will console.error its whining. If it is assigned to boolean `false` then the warning is suppressed. ## Abbreviations Yes, they are supported. If you define options like this: ```javascript { "foolhardyelephants" : Boolean , "pileofmonkeys" : Boolean } ``` Then this will work: ```bash node program.js --foolhar --pil node program.js --no-f --pileofmon # etc. ``` ## Shorthands Shorthands are a hash of shorter option names to a snippet of args that they expand to. If multiple one-character shorthands are all combined, and the combination does not unambiguously match any other option or shorthand, then they will be broken up into their constituent parts. For example: ```json { "s" : ["--loglevel", "silent"] , "g" : "--global" , "f" : "--force" , "p" : "--parseable" , "l" : "--long" } ``` ```bash npm ls -sgflp # just like doing this: npm ls --loglevel silent --global --force --long --parseable ``` ## The Rest of the args The config object returned by nopt is given a special member called `argv`, which is an object with the following fields: * `remain`: The remaining args after all the parsing has occurred. * `original`: The args as they originally appeared. * `cooked`: The args after flags and shorthands are expanded. ## Slicing Node programs are called with more or less the exact argv as it appears in C land, after the v8 and node-specific options have been plucked off. As such, `argv[0]` is always `node` and `argv[1]` is always the JavaScript program being run. That's usually not very useful to you. So they're sliced off by default. If you want them, then you can pass in `0` as the last argument, or any other number that you'd like to slice off the start of the list. # big.js **A small, fast JavaScript library for arbitrary-precision decimal arithmetic.** The little sister to [bignumber.js](https://github.com/MikeMcl/bignumber.js/) and [decimal.js](https://github.com/MikeMcl/decimal.js/). See [here](https://github.com/MikeMcl/big.js/wiki) for some notes on the difference between them. ## Features - Faster, smaller and easier-to-use than JavaScript versions of Java's BigDecimal - Only 5.9 KB minified and 2.7 KB gzipped - Simple API - Replicates the `toExponential`, `toFixed` and `toPrecision` methods of JavaScript's Number type - Includes a `sqrt` method - Stores values in an accessible decimal floating point format - No dependencies - Comprehensive [documentation](http://mikemcl.github.io/big.js/) and test set ## Set up The library is the single JavaScript file *big.js* (or *big.min.js*, which is *big.js* minified). Browser: ```html <script src='path/to/big.js'></script> ``` [Node.js](http://nodejs.org): ```bash $ npm install big.js ``` ```javascript const Big = require('big.js'); ``` ES6 module: ```javascript import Big from 'big.mjs'; ``` ## Use *In all examples below, `var`, semicolons and `toString` calls are not shown. If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* The library exports a single function, `Big`, the constructor of Big number instances. It accepts a value of type number, string or Big number object. x = new Big(123.4567) y = Big('123456.7e-3') // 'new' is optional z = new Big(x) x.eq(y) && x.eq(z) && y.eq(z) // true A Big number is immutable in the sense that it is not changed by its methods. 0.3 - 0.1 // 0.19999999999999998 x = new Big(0.3) x.minus(0.1) // "0.2" x // "0.3" The methods that return a Big number can be chained. x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772') x.sqrt().div(y).pow(3).gt(y.mod(z)) // true Like JavaScript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods. x = new Big(255.5) x.toExponential(5) // "2.55500e+2" x.toFixed(5) // "255.50000" x.toPrecision(5) // "255.50" The arithmetic methods always return the exact result except `div`, `sqrt` and `pow` (with negative exponent), as these methods involve division. The maximum number of decimal places and the rounding mode used to round the results of these methods is determined by the value of the `DP` and `RM` properties of the `Big` number constructor. Big.DP = 10 Big.RM = 1 x = new Big(2); y = new Big(3); z = x.div(y) // "0.6666666667" z.sqrt() // "0.8164965809" z.pow(-3) // "3.3749999995" z.times(z) // "0.44444444448888888889" z.times(z).round(10) // "0.4444444445" Multiple Big number constructors can be created, each with an independent configuration. The value of a Big number is stored in a decimal floating point format in terms of a coefficient, exponent and sign. x = new Big(-123.456); x.c // [1,2,3,4,5,6] coefficient (i.e. significand) x.e // 2 exponent x.s // -1 sign For further information see the [API](http://mikemcl.github.io/big.js/) reference from the *doc* folder. ## Test The *test* directory contains the test scripts for each Big number method. The tests can be run with Node.js or a browser. To run all the tests $ npm test To test a single method $ node test/toFixed For the browser, see *single-test.html* and *every-test.html* in the *test/browser* directory. *big-vs-number.html* is a simple application that enables some of the methods of big.js to be compared with those of JavaScript's Number type. ## Performance The *perf* directory contains two legacy applications and a *lib* directory containing the BigDecimal libraries used by both. *big-vs-bigdecimal.html* tests the performance of big.js against the JavaScript translations of two versions of BigDecimal, its use should be more or less self-explanatory. * [GWT: java.math.BigDecimal](https://github.com/iriscouch/bigdecimal.js) * [ICU4J: com.ibm.icu.math.BigDecimal](https://github.com/dtrebbien/BigDecimal.js) The BigDecimal in the npm registry is the GWT version. It has some bugs, see the Node.js script *perf/lib/bigdecimal_GWT/bugs.js* for examples of flaws in its *remainder*, *divide* and *compareTo* methods. *bigtime.js* is a Node.js command-line application which tests the performance of big.js against the GWT version of BigDecimal from the npm registry. For example, to compare the time taken by the big.js `plus` method and the BigDecimal `add` method $ node bigtime plus 10000 40 This will time 10000 calls to each, using operands of up to 40 random digits and will check that the results match. For help $ node bigtime -h ## Build If [uglify-js](https://github.com/mishoo/UglifyJS2) is installed globally $ npm install uglify-js -g then $ npm run build will create *big.min.js*. ## TypeScript The [DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped) project has a Typescript type definitions file for big.js. $ npm install @types/big.js Any questions about the TypeScript type definitions file should be addressed to the DefinitelyTyped project. ## Feedback Bugs/comments/questions? Open an issue, or email <a href="mailto:[email protected]">Michael</a> ## Licence [MIT](LICENCE) ## Contributors This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. <a href="graphs/contributors"><img src="https://opencollective.com/bigjs/contributors.svg?width=890&button=false" /></a> ## Backers Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/bigjs#backer)] <a href="https://opencollective.com/bigjs#backers" target="_blank"><img src="https://opencollective.com/bigjs/backers.svg?width=890"></a> ## Sponsors Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/bigjs#sponsor)] <a href="https://opencollective.com/bigjs/sponsor/0/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/1/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/2/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/3/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/4/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/5/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/6/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/7/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/8/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/bigjs/sponsor/9/website" target="_blank"><img src="https://opencollective.com/bigjs/sponsor/9/avatar.svg"></a> # compression [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Node.js compression middleware. The following compression codings are supported: - deflate - gzip ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install compression ``` ## API <!-- eslint-disable no-unused-vars --> ```js var compression = require('compression') ``` ### compression([options]) Returns the compression middleware using the given `options`. The middleware will attempt to compress response bodies for all request that traverse through the middleware, based on the given `options`. This middleware will never compress responses that include a `Cache-Control` header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4), as compressing will transform the body. #### Options `compression()` accepts these properties in the options object. In addition to those listed below, [zlib](http://nodejs.org/api/zlib.html) options may be passed in to the options object. ##### chunkSize The default value is `zlib.Z_DEFAULT_CHUNK`, or `16384`. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### filter A function to decide if the response should be considered for compression. This function is called as `filter(req, res)` and is expected to return `true` to consider the response for compression, or `false` to not compress the response. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible) module to determine if `res.getHeader('Content-Type')` is compressible. ##### level The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster. This is an integer in the range of `0` (no compression) to `9` (maximum compression). The special value `-1` can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6). - `-1` Default compression level (also `zlib.Z_DEFAULT_COMPRESSION`). - `0` No compression (also `zlib.Z_NO_COMPRESSION`). - `1` Fastest compression (also `zlib.Z_BEST_SPEED`). - `2` - `3` - `4` - `5` - `6` (currently what `zlib.Z_DEFAULT_COMPRESSION` points to). - `7` - `8` - `9` Best compression (also `zlib.Z_BEST_COMPRESSION`). The default value is `zlib.Z_DEFAULT_COMPRESSION`, or `-1`. **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### memLevel This specifies how much memory should be allocated for the internal compression state and is an integer in the range of `1` (minimum level) and `9` (maximum level). The default value is `zlib.Z_DEFAULT_MEMLEVEL`, or `8`. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### strategy This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately. - `zlib.Z_DEFAULT_STRATEGY` Use for normal data. - `zlib.Z_FILTERED` Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between `zlib.Z_DEFAULT_STRATEGY` and `zlib.Z_HUFFMAN_ONLY`. - `zlib.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - `zlib.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match). - `zlib.Z_RLE` Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as `zlib.Z_HUFFMAN_ONLY`, but give better compression for PNG image data. **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### threshold The byte threshold for the response body size before compression is considered for the response, defaults to `1kb`. This is a number of bytes or any string accepted by the [bytes](https://www.npmjs.com/package/bytes) module. **Note** this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is _over_ the threshold. To guarantee the response size can be determined, be sure set a `Content-Length` response header. ##### windowBits The default value is `zlib.Z_DEFAULT_WINDOWBITS`, or `15`. See [Node.js documentation](http://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. #### .filter The default `filter` function. This is used to construct a custom filter function that is an extension of the default function. ```js var compression = require('compression') var express = require('express') var app = express() app.use(compression({ filter: shouldCompress })) function shouldCompress (req, res) { if (req.headers['x-no-compression']) { // don't compress responses with this request header return false } // fallback to standard filter function return compression.filter(req, res) } ``` ### res.flush This module adds a `res.flush()` method to force the partially-compressed response to be flushed to the client. ## Examples ### express/connect When using this module with express or connect, simply `app.use` the module as high as you like. Requests that pass through the middleware will be compressed. ```js var compression = require('compression') var express = require('express') var app = express() // compress all responses app.use(compression()) // add all routes ``` ### Server-Sent Events Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client. You can achieve this by calling `res.flush()` when you need the data written to actually make it to the client. ```js var compression = require('compression') var express = require('express') var app = express() // compress responses app.use(compression()) // server-sent event stream app.get('/events', function (req, res) { res.setHeader('Content-Type', 'text/event-stream') res.setHeader('Cache-Control', 'no-cache') // send a ping approx every 2 seconds var timer = setInterval(function () { res.write('data: ping\n\n') // !!! this is the important part res.flush() }, 2000) res.on('close', function () { clearInterval(timer) }) }) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/compression.svg [npm-url]: https://npmjs.org/package/compression [travis-image]: https://img.shields.io/travis/expressjs/compression/master.svg [travis-url]: https://travis-ci.org/expressjs/compression [coveralls-image]: https://img.shields.io/coveralls/expressjs/compression/master.svg [coveralls-url]: https://coveralls.io/r/expressjs/compression?branch=master [downloads-image]: https://img.shields.io/npm/dm/compression.svg [downloads-url]: https://npmjs.org/package/compression # HAR Schema [![version][npm-version]][npm-url] [![License][npm-license]][license-url] > JSON Schema for HTTP Archive ([HAR][spec]). [![Build Status][travis-image]][travis-url] [![Downloads][npm-downloads]][npm-url] [![Code Climate][codeclimate-quality]][codeclimate-url] [![Coverage Status][codeclimate-coverage]][codeclimate-url] [![Dependency Status][dependencyci-image]][dependencyci-url] [![Dependencies][david-image]][david-url] ## Install ```bash npm install --only=production --save har-schema ``` ## Usage Compatible with any [JSON Schema validation tool][validator]. ---- > :copyright: [ahmadnassri.com](https://www.ahmadnassri.com/) &nbsp;&middot;&nbsp; > License: [ISC][license-url] &nbsp;&middot;&nbsp; > Github: [@ahmadnassri](https://github.com/ahmadnassri) &nbsp;&middot;&nbsp; > Twitter: [@ahmadnassri](https://twitter.com/ahmadnassri) [license-url]: http://choosealicense.com/licenses/isc/ [travis-url]: https://travis-ci.org/ahmadnassri/har-schema [travis-image]: https://img.shields.io/travis/ahmadnassri/har-schema.svg?style=flat-square [npm-url]: https://www.npmjs.com/package/har-schema [npm-license]: https://img.shields.io/npm/l/har-schema.svg?style=flat-square [npm-version]: https://img.shields.io/npm/v/har-schema.svg?style=flat-square [npm-downloads]: https://img.shields.io/npm/dm/har-schema.svg?style=flat-square [codeclimate-url]: https://codeclimate.com/github/ahmadnassri/har-schema [codeclimate-quality]: https://img.shields.io/codeclimate/github/ahmadnassri/har-schema.svg?style=flat-square [codeclimate-coverage]: https://img.shields.io/codeclimate/coverage/github/ahmadnassri/har-schema.svg?style=flat-square [david-url]: https://david-dm.org/ahmadnassri/har-schema [david-image]: https://img.shields.io/david/ahmadnassri/har-schema.svg?style=flat-square [dependencyci-url]: https://dependencyci.com/github/ahmadnassri/har-schema [dependencyci-image]: https://dependencyci.com/github/ahmadnassri/har-schema/badge?style=flat-square [spec]: https://github.com/ahmadnassri/har-spec/blob/master/versions/1.2.md [validator]: https://github.com/ahmadnassri/har-validator # ieee754 [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/ieee754/master.svg [travis-url]: https://travis-ci.org/feross/ieee754 [npm-image]: https://img.shields.io/npm/v/ieee754.svg [npm-url]: https://npmjs.org/package/ieee754 [downloads-image]: https://img.shields.io/npm/dm/ieee754.svg [downloads-url]: https://npmjs.org/package/ieee754 [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com [![saucelabs][saucelabs-image]][saucelabs-url] [saucelabs-image]: https://saucelabs.com/browser-matrix/ieee754.svg [saucelabs-url]: https://saucelabs.com/u/ieee754 ### Read/write IEEE754 floating point numbers from/to a Buffer or array-like object. ## install ``` npm install ieee754 ``` [Get supported ieee754 with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-ieee754?utm_source=npm-ieee754&utm_medium=referral&utm_campaign=readme) ## methods `var ieee754 = require('ieee754')` The `ieee754` object has the following functions: ``` ieee754.read = function (buffer, offset, isLE, mLen, nBytes) ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) ``` The arguments mean the following: - buffer = the buffer - offset = offset into the buffer - value = value to set (only for `write`) - isLe = is little endian? - mLen = mantissa length - nBytes = number of bytes ## what is ieee754? The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point computation. [Read more](http://en.wikipedia.org/wiki/IEEE_floating_point). ## license BSD 3 Clause. Copyright (c) 2008, Fair Oaks Labs, Inc. # brace-expansion [Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), as known from sh/bash, in JavaScript. [![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) [![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) [![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) [![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) ## Example ```js var expand = require('brace-expansion'); expand('file-{a,b,c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('-v{,,}') // => ['-v', '-v', '-v'] expand('file{0..2}.jpg') // => ['file0.jpg', 'file1.jpg', 'file2.jpg'] expand('file-{a..c}.jpg') // => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] expand('file{2..0}.jpg') // => ['file2.jpg', 'file1.jpg', 'file0.jpg'] expand('file{0..4..2}.jpg') // => ['file0.jpg', 'file2.jpg', 'file4.jpg'] expand('file-{a..e..2}.jpg') // => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] expand('file{00..10..5}.jpg') // => ['file00.jpg', 'file05.jpg', 'file10.jpg'] expand('{{A..C},{a..c}}') // => ['A', 'B', 'C', 'a', 'b', 'c'] expand('ppp{,config,oe{,conf}}') // => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] ``` ## API ```js var expand = require('brace-expansion'); ``` ### var expanded = expand(str) Return an array of all possible and valid expansions of `str`. If none are found, `[str]` is returned. Valid expansions are: ```js /^(.*,)+(.+)?$/ // {a,b,...} ``` A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` A numeric sequence from `x` to `y` inclusive, with optional increment. If `x` or `y` start with a leading `0`, all the numbers will be padded to have equal length. Negative numbers and backwards iteration work too. ```js /^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ // {x..y[..incr]} ``` An alphabetic sequence from `x` to `y` inclusive, with optional increment. `x` and `y` must be exactly one character, and if given, `incr` must be a number. For compatibility reasons, the string `${` is not eligible for brace expansion. ## Installation With [npm](https://npmjs.org) do: ```bash npm install brace-expansion ``` ## Contributors - [Julian Gruber](https://github.com/juliangruber) - [Isaac Z. Schlueter](https://github.com/isaacs) ## Sponsors This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! ## License (MIT) Copyright (c) 2013 Julian Gruber &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # stdout-stream Non-blocking stdout stream npm install stdout-stream [![build status](http://img.shields.io/travis/mafintosh/level-filesystem.svg?style=flat)](http://travis-ci.org/mafintosh/stdout-stream) ![dat](http://img.shields.io/badge/Development%20sponsored%20by-dat-green.svg?style=flat) ## Rant Try saving this example as `example.js` ``` js console.error('start'); process.stdout.write(new Buffer(1024*1024)); console.error('end'); ``` And run the following program ``` node example.js | sleep 1000 ``` The program will never print `end` since stdout in node currently is blocking - even when its being piped (!). stdout-stream tries to fix this by being a stream that writes to stdout but never blocks ## Usage ``` js var stdout = require('stdout-stream'); stdout.write('hello\n'); // write should NEVER block stdout.write('non-blocking\n') stdout.write('world\n'); ``` `stdout-stream` should behave in the same way as `process.stdout` (i.e. do not end on pipe etc) ## License MIT wide-align ---------- A wide-character aware text alignment function for use in terminals / on the console. ### Usage ``` var align = require('wide-align') // Note that if you view this on a unicode console, all of the slashes are // aligned. This is because on a console, all narrow characters are // an en wide and all wide characters are an em. In browsers, this isn't // held to and wide characters like "古" can be less than two narrow // characters even with a fixed width font. console.log(align.center('abc', 10)) // ' abc ' console.log(align.center('古古古', 10)) // ' 古古古 ' console.log(align.left('abc', 10)) // 'abc ' console.log(align.left('古古古', 10)) // '古古古 ' console.log(align.right('abc', 10)) // ' abc' console.log(align.right('古古古', 10)) // ' 古古古' ``` ### Functions #### `align.center(str, length)` → `str` Returns *str* with spaces added to both sides such that that it is *length* chars long and centered in the spaces. #### `align.left(str, length)` → `str` Returns *str* with spaces to the right such that it is *length* chars long. ### `align.right(str, length)` → `str` Returns *str* with spaces to the left such that it is *length* chars long. ### Origins These functions were originally taken from [cliui](https://npmjs.com/package/cliui). Changes include switching to the MUCH faster pad generation function from [lodash](https://npmjs.com/package/lodash), making center alignment pad both sides and adding left alignment. # jsesc [![Build status](https://travis-ci.org/mathiasbynens/jsesc.svg?branch=master)](https://travis-ci.org/mathiasbynens/jsesc) [![Code coverage status](https://coveralls.io/repos/mathiasbynens/jsesc/badge.svg)](https://coveralls.io/r/mathiasbynens/jsesc) [![Dependency status](https://gemnasium.com/mathiasbynens/jsesc.svg)](https://gemnasium.com/mathiasbynens/jsesc) Given some data, _jsesc_ returns a stringified representation of that data. jsesc is similar to `JSON.stringify()` except: 1. it outputs JavaScript instead of JSON [by default](#json), enabling support for data structures like ES6 maps and sets; 2. it offers [many options](#api) to customize the output; 3. its output is ASCII-safe [by default](#minimal), thanks to its use of [escape sequences](https://mathiasbynens.be/notes/javascript-escapes) where needed. For any input, jsesc generates the shortest possible valid printable-ASCII-only output. [Here’s an online demo.](https://mothereff.in/js-escapes) jsesc’s output can be used instead of `JSON.stringify`’s to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake) and other encoding issues, or even to [avoid errors](https://twitter.com/annevk/status/380000829643571200) when passing JSON-formatted data (which may contain U+2028 LINE SEPARATOR, U+2029 PARAGRAPH SEPARATOR, or [lone surrogates](https://esdiscuss.org/topic/code-points-vs-unicode-scalar-values#content-14)) to a JavaScript parser or an UTF-8 encoder. ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install jsesc ``` In [Node.js](https://nodejs.org/): ```js const jsesc = require('jsesc'); ``` ## API ### `jsesc(value, options)` This function takes a value and returns an escaped version of the value where any characters that are not printable ASCII symbols are escaped using the shortest possible (but valid) [escape sequences for use in JavaScript strings](https://mathiasbynens.be/notes/javascript-escapes). The first supported value type is strings: ```js jsesc('Ich ♥ Bücher'); // → 'Ich \\u2665 B\\xFCcher' jsesc('foo 𝌆 bar'); // → 'foo \\uD834\\uDF06 bar' ``` Instead of a string, the `value` can also be an array, an object, a map, a set, or a buffer. In such cases, `jsesc` returns a stringified version of the value where any characters that are not printable ASCII symbols are escaped in the same way. ```js // Escaping an array jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ]); // → '[\'Ich \\u2665 B\\xFCcher\',\'foo \\uD834\\uDF06 bar\']' // Escaping an object jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }); // → '{\'Ich \\u2665 B\\xFCcher\':\'foo \\uD834\\uDF06 bar\'}' ``` The optional `options` argument accepts an object with the following options: #### `quotes` The default value for the `quotes` option is `'single'`. This means that any occurrences of `'` in the input string are escaped as `\'`, so that the output can be used in a string literal wrapped in single quotes. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.'); // → 'Lorem ipsum "dolor" sit \\\'amet\\\' etc.' jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single' }); // → '`Lorem` ipsum "dolor" sit \\\'amet\\\' etc.' // → "`Lorem` ipsum \"dolor\" sit \\'amet\\' etc." ``` If you want to use the output as part of a string literal wrapped in double quotes, set the `quotes` option to `'double'`. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double' }); // → '`Lorem` ipsum \\"dolor\\" sit \'amet\' etc.' // → "`Lorem` ipsum \\\"dolor\\\" sit 'amet' etc." ``` If you want to use the output as part of a template literal (i.e. wrapped in backticks), set the `quotes` option to `'backtick'`. ```js jsesc('`Lorem` ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'backtick' }); // → '\\`Lorem\\` ipsum "dolor" sit \'amet\' etc.' // → "\\`Lorem\\` ipsum \"dolor\" sit 'amet' etc." // → `\\\`Lorem\\\` ipsum "dolor" sit 'amet' etc.` ``` This setting also affects the output for arrays and objects: ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'quotes': 'double' }); // → '{"Ich \\u2665 B\\xFCcher":"foo \\uD834\\uDF06 bar"}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'quotes': 'double' }); // → '["Ich \\u2665 B\\xFCcher","foo \\uD834\\uDF06 bar"]' ``` #### `numbers` The default value for the `numbers` option is `'decimal'`. This means that any numeric values are represented using decimal integer literals. Other valid options are `binary`, `octal`, and `hexadecimal`, which result in binary integer literals, octal integer literals, and hexadecimal integer literals, respectively. ```js jsesc(42, { 'numbers': 'binary' }); // → '0b101010' jsesc(42, { 'numbers': 'octal' }); // → '0o52' jsesc(42, { 'numbers': 'decimal' }); // → '42' jsesc(42, { 'numbers': 'hexadecimal' }); // → '0x2A' ``` #### `wrap` The `wrap` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is a valid JavaScript string literal wrapped in quotes. The type of quotes can be specified through the `quotes` setting. ```js jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'single', 'wrap': true }); // → '\'Lorem ipsum "dolor" sit \\\'amet\\\' etc.\'' // → "\'Lorem ipsum \"dolor\" sit \\\'amet\\\' etc.\'" jsesc('Lorem ipsum "dolor" sit \'amet\' etc.', { 'quotes': 'double', 'wrap': true }); // → '"Lorem ipsum \\"dolor\\" sit \'amet\' etc."' // → "\"Lorem ipsum \\\"dolor\\\" sit \'amet\' etc.\"" ``` #### `es6` The `es6` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any astral Unicode symbols in the input are escaped using [ECMAScript 6 Unicode code point escape sequences](https://mathiasbynens.be/notes/javascript-escapes#unicode-code-point) instead of using separate escape sequences for each surrogate half. If backwards compatibility with ES5 environments is a concern, don’t enable this setting. If the `json` setting is enabled, the value for the `es6` setting is ignored (as if it was `false`). ```js // By default, the `es6` option is disabled: jsesc('foo 𝌆 bar 💩 baz'); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To explicitly disable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': false }); // → 'foo \\uD834\\uDF06 bar \\uD83D\\uDCA9 baz' // To enable it: jsesc('foo 𝌆 bar 💩 baz', { 'es6': true }); // → 'foo \\u{1D306} bar \\u{1F4A9} baz' ``` #### `escapeEverything` The `escapeEverything` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, all the symbols in the output are escaped — even printable ASCII symbols. ```js jsesc('lolwat"foo\'bar', { 'escapeEverything': true }); // → '\\x6C\\x6F\\x6C\\x77\\x61\\x74\\"\\x66\\x6F\\x6F\\\'\\x62\\x61\\x72' // → "\\x6C\\x6F\\x6C\\x77\\x61\\x74\\\"\\x66\\x6F\\x6F\\'\\x62\\x61\\x72" ``` This setting also affects the output for string literals within arrays and objects. #### `minimal` The `minimal` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, only a limited set of symbols in the output are escaped: * U+0000 `\0` * U+0008 `\b` * U+0009 `\t` * U+000A `\n` * U+000C `\f` * U+000D `\r` * U+005C `\\` * U+2028 `\u2028` * U+2029 `\u2029` * whatever symbol is being used for wrapping string literals (based on [the `quotes` option](#quotes)) Note: with this option enabled, jsesc output is no longer guaranteed to be ASCII-safe. ```js jsesc('foo\u2029bar\nbaz©qux𝌆flops', { 'minimal': false }); // → 'foo\\u2029bar\\nbaz©qux𝌆flops' ``` #### `isScriptContext` The `isScriptContext` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, occurrences of [`</script` and `</style`](https://mathiasbynens.be/notes/etago) in the output are escaped as `<\/script` and `<\/style`, and [`<!--`](https://mathiasbynens.be/notes/etago#comment-8) is escaped as `\x3C!--` (or `\u003C!--` when the `json` option is enabled). This setting is useful when jsesc’s output ends up as part of a `<script>` or `<style>` element in an HTML document. ```js jsesc('foo</script>bar', { 'isScriptContext': true }); // → 'foo<\\/script>bar' ``` #### `compact` The `compact` option takes a boolean value (`true` or `false`), and defaults to `true` (enabled). When enabled, the output for arrays and objects is as compact as possible; it’s not formatted nicely. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': true // this is the default }); // → '{\'Ich \u2665 B\xFCcher\':\'foo \uD834\uDF06 bar\'}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false }); // → '[\n\t\'Ich \u2665 B\xFCcher\',\n\t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `indent` The `indent` option takes a string value, and defaults to `'\t'`. When the `compact` setting is enabled (`true`), the value of the `indent` option is used to format the output for arrays and objects. ```js jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': '\t' // this is the default }); // → '{\n\t\'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc({ 'Ich ♥ Bücher': 'foo 𝌆 bar' }, { 'compact': false, 'indent': ' ' }); // → '{\n \'Ich \u2665 B\xFCcher\': \'foo \uD834\uDF06 bar\'\n}' jsesc([ 'Ich ♥ Bücher', 'foo 𝌆 bar' ], { 'compact': false, 'indent': ' ' }); // → '[\n \'Ich \u2665 B\xFCcher\',\n\ t\'foo \uD834\uDF06 bar\'\n]' ``` This setting has no effect on the output for strings. #### `indentLevel` The `indentLevel` option takes a numeric value, and defaults to `0`. It represents the current indentation level, i.e. the number of times the value of [the `indent` option](#indent) is repeated. ```js jsesc(['a', 'b', 'c'], { 'compact': false, 'indentLevel': 1 }); // → '[\n\t\t\'a\',\n\t\t\'b\',\n\t\t\'c\'\n\t]' jsesc(['a', 'b', 'c'], { 'compact': false, 'indentLevel': 2 }); // → '[\n\t\t\t\'a\',\n\t\t\t\'b\',\n\t\t\t\'c\'\n\t\t]' ``` #### `json` The `json` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, the output is valid JSON. [Hexadecimal character escape sequences](https://mathiasbynens.be/notes/javascript-escapes#hexadecimal) and [the `\v` or `\0` escape sequences](https://mathiasbynens.be/notes/javascript-escapes#single) are not used. Setting `json: true` implies `quotes: 'double', wrap: true, es6: false`, although these values can still be overridden if needed — but in such cases, the output won’t be valid JSON anymore. ```js jsesc('foo\x00bar\xFF\uFFFDbaz', { 'json': true }); // → '"foo\\u0000bar\\u00FF\\uFFFDbaz"' jsesc({ 'foo\x00bar\xFF\uFFFDbaz': 'foo\x00bar\xFF\uFFFDbaz' }, { 'json': true }); // → '{"foo\\u0000bar\\u00FF\\uFFFDbaz":"foo\\u0000bar\\u00FF\\uFFFDbaz"}' jsesc([ 'foo\x00bar\xFF\uFFFDbaz', 'foo\x00bar\xFF\uFFFDbaz' ], { 'json': true }); // → '["foo\\u0000bar\\u00FF\\uFFFDbaz","foo\\u0000bar\\u00FF\\uFFFDbaz"]' // Values that are acceptable in JSON but aren’t strings, arrays, or object // literals can’t be escaped, so they’ll just be preserved: jsesc([ 'foo\x00bar', [1, '©', { 'foo': true, 'qux': null }], 42 ], { 'json': true }); // → '["foo\\u0000bar",[1,"\\u00A9",{"foo":true,"qux":null}],42]' // Values that aren’t allowed in JSON are run through `JSON.stringify()`: jsesc([ undefined, -Infinity ], { 'json': true }); // → '[null,null]' ``` **Note:** Using this option on objects or arrays that contain non-string values relies on `JSON.stringify()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](http://bestiejs.github.io/json3/). #### `lowercaseHex` The `lowercaseHex` option takes a boolean value (`true` or `false`), and defaults to `false` (disabled). When enabled, any alphabetical hexadecimal digits in escape sequences as well as any hexadecimal integer literals (see [the `numbers` option](#numbers)) in the output are in lowercase. ```js jsesc('Ich ♥ Bücher', { 'lowercaseHex': true }); // → 'Ich \\u2665 B\\xfccher' // ^^ jsesc(42, { 'numbers': 'hexadecimal', 'lowercaseHex': true }); // → '0x2a' // ^^ ``` ### `jsesc.version` A string representing the semantic version number. ### Using the `jsesc` binary To use the `jsesc` binary in your shell, simply install jsesc globally using npm: ```bash npm install -g jsesc ``` After that you’re able to escape strings from the command line: ```bash $ jsesc 'föo ♥ bår 𝌆 baz' f\xF6o \u2665 b\xE5r \uD834\uDF06 baz ``` To escape arrays or objects containing string values, use the `-o`/`--object` option: ```bash $ jsesc --object '{ "föo": "♥", "bår": "𝌆 baz" }' {'f\xF6o':'\u2665','b\xE5r':'\uD834\uDF06 baz'} ``` To prettify the output in such cases, use the `-p`/`--pretty` option: ```bash $ jsesc --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { 'f\xF6o': '\u2665', 'b\xE5r': '\uD834\uDF06 baz' } ``` For valid JSON output, use the `-j`/`--json` option: ```bash $ jsesc --json --pretty '{ "föo": "♥", "bår": "𝌆 baz" }' { "f\u00F6o": "\u2665", "b\u00E5r": "\uD834\uDF06 baz" } ``` Read a local JSON file, escape any non-ASCII symbols, and save the result to a new file: ```bash $ jsesc --json --object < data-raw.json > data-escaped.json ``` Or do the same with an online JSON file: ```bash $ curl -sL "http://git.io/aorKgQ" | jsesc --json --object > data-escaped.json ``` See `jsesc --help` for the full list of options. ## Support As of v2.0.0, jsesc supports Node.js v4+ only. Older versions (up to jsesc v1.3.0) support Chrome 27, Firefox 3, Safari 4, Opera 10, IE 6, Node.js v6.0.0, Narwhal 0.3.2, RingoJS 0.8-0.11, PhantomJS 1.9.0, and Rhino 1.7RC4. **Note:** Using the `json` option on objects or arrays that contain non-string values relies on `JSON.parse()`. For legacy environments like IE ≤ 7, use [a `JSON` polyfill](https://bestiejs.github.io/json3/). ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License This library is available under the [MIT](https://mths.be/mit) license. # define-property [![NPM version](https://img.shields.io/npm/v/define-property.svg?style=flat)](https://www.npmjs.com/package/define-property) [![NPM monthly downloads](https://img.shields.io/npm/dm/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![NPM total downloads](https://img.shields.io/npm/dt/define-property.svg?style=flat)](https://npmjs.org/package/define-property) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/define-property.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/define-property) > Define a non-enumerable property on an object. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save define-property ``` Install with [yarn](https://yarnpkg.com): ```sh $ yarn add define-property ``` ## Usage **Params** * `obj`: The object on which to define the property. * `prop`: The name of the property to be defined or modified. * `descriptor`: The descriptor for the property being defined or modified. ```js var define = require('define-property'); var obj = {}; define(obj, 'foo', function(val) { return val.toUpperCase(); }); console.log(obj); //=> {} console.log(obj.foo('bar')); //=> 'BAR' ``` **get/set** ```js define(obj, 'foo', { get: function() {}, set: function() {} }); ``` ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") * [mixin-deep](https://www.npmjs.com/package/mixin-deep): Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. | [homepage](https://github.com/jonschlinkert/mixin-deep "Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.5.0, on April 20, 2017._ # is-descriptor [![NPM version](https://img.shields.io/npm/v/is-descriptor.svg?style=flat)](https://www.npmjs.com/package/is-descriptor) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![NPM total downloads](https://img.shields.io/npm/dt/is-descriptor.svg?style=flat)](https://npmjs.org/package/is-descriptor) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-descriptor.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-descriptor) > Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-descriptor ``` ## Usage ```js var isDescriptor = require('is-descriptor'); isDescriptor({value: 'foo'}) //=> true isDescriptor({get: function(){}, set: function(){}}) //=> true isDescriptor({get: 'foo', set: function(){}}) //=> false ``` You may also check for a descriptor by passing an object as the first argument and property name (`string`) as the second argument. ```js var obj = {}; obj.foo = 'abc'; Object.defineProperty(obj, 'bar', { value: 'xyz' }); isDescriptor(obj, 'foo'); //=> true isDescriptor(obj, 'bar'); //=> true ``` ## Examples ### value type `false` when not an object ```js isDescriptor('a'); //=> false isDescriptor(null); //=> false isDescriptor([]); //=> false ``` ### data descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({value: 'foo'}); //=> true isDescriptor({value: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', bar: 'baz'}); //=> false isDescriptor({value: 'foo', get: noop}); //=> false isDescriptor({get: noop, value: noop}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({value: 'foo', enumerable: 'foo'}); //=> false isDescriptor({value: 'foo', configurable: 'foo'}); //=> false isDescriptor({value: 'foo', writable: 'foo'}); //=> false ``` ### accessor descriptor `true` when the object has valid properties with valid values. ```js isDescriptor({get: noop, set: noop}); //=> true isDescriptor({get: noop}); //=> true isDescriptor({set: noop}); //=> true ``` `false` when the object has invalid properties ```js isDescriptor({get: noop, set: noop, bar: 'baz'}); //=> false isDescriptor({get: noop, writable: true}); //=> false isDescriptor({get: noop, value: true}); //=> false ``` `false` when an accessor is not a function ```js isDescriptor({get: noop, set: 'baz'}); //=> false isDescriptor({get: 'foo', set: noop}); //=> false isDescriptor({get: 'foo', bar: 'baz'}); //=> false isDescriptor({get: 'foo', set: 'baz'}); //=> false ``` `false` when a value is not the correct type ```js isDescriptor({get: noop, set: noop, enumerable: 'foo'}); //=> false isDescriptor({set: noop, configurable: 'foo'}); //=> false isDescriptor({get: noop, configurable: 'foo'}); //=> false ``` ## About ### Related projects * [is-accessor-descriptor](https://www.npmjs.com/package/is-accessor-descriptor): Returns true if a value has the characteristics of a valid JavaScript accessor descriptor. | [homepage](https://github.com/jonschlinkert/is-accessor-descriptor "Returns true if a value has the characteristics of a valid JavaScript accessor descriptor.") * [is-data-descriptor](https://www.npmjs.com/package/is-data-descriptor): Returns true if a value has the characteristics of a valid JavaScript data descriptor. | [homepage](https://github.com/jonschlinkert/is-data-descriptor "Returns true if a value has the characteristics of a valid JavaScript data descriptor.") * [is-descriptor](https://www.npmjs.com/package/is-descriptor): Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for… [more](https://github.com/jonschlinkert/is-descriptor) | [homepage](https://github.com/jonschlinkert/is-descriptor "Returns true if a value has the characteristics of a valid JavaScript descriptor. Works for data descriptors and accessor descriptors.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Contributors | **Commits** | **Contributor** | | --- | --- | | 24 | [jonschlinkert](https://github.com/jonschlinkert) | | 1 | [doowb](https://github.com/doowb) | | 1 | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) | ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 22, 2017._ # ripemd160 [![NPM Package](https://img.shields.io/npm/v/ripemd160.svg?style=flat-square)](https://www.npmjs.org/package/ripemd160) [![Build Status](https://img.shields.io/travis/crypto-browserify/ripemd160.svg?branch=master&style=flat-square)](https://travis-ci.org/crypto-browserify/ripemd160) [![Dependency status](https://img.shields.io/david/crypto-browserify/ripemd160.svg?style=flat-square)](https://david-dm.org/crypto-browserify/ripemd160#info=dependencies) [![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) Node style `ripemd160` on pure JavaScript. ## Example ```js var RIPEMD160 = require('ripemd160') console.log(new RIPEMD160().update('42').digest('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 var ripemd160stream = new RIPEMD160() ripemd160stream.end('42') console.log(ripemd160stream.read().toString('hex')) // => 0df020ba32aa9b8b904471ff582ce6b579bf8bc8 ``` ## LICENSE MIT # has-value [![NPM version](https://img.shields.io/npm/v/has-value.svg?style=flat)](https://www.npmjs.com/package/has-value) [![NPM downloads](https://img.shields.io/npm/dm/has-value.svg?style=flat)](https://npmjs.org/package/has-value) [![Build Status](https://img.shields.io/travis/jonschlinkert/has-value.svg?style=flat)](https://travis-ci.org/jonschlinkert/has-value) > Returns true if a value exists, false if empty. Works with deeply nested values using object paths. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install has-value --save ``` **Works for:** * booleans * functions * numbers (pass `true` as the last arg to treat zero as a value instead of falsey) * strings * nulls * object * arrays ## Usage Works with nested object paths or a single value: ```js var hasValue = require('has-value'); hasValue({a: {b: {c: 'foo'}}} 'a.b.c'); //=> true hasValue('a'); //=> true hasValue(''); //=> false hasValue(1); //=> true hasValue(0); //=> false hasValue(0, true); // pass `true` as the last arg to treat zero as a value //=> true hasValue({a: 'a'}}); //=> true hasValue({}}); //=> false hasValue(['a']); //=> true hasValue([]); //=> false hasValue(function(foo) {}); // function length/arity //=> true hasValue(function() {}); //=> false hasValue(true); hasValue(false); //=> true ``` ## isEmpty To do the opposite and test for empty values, do: ```js function isEmpty(o, isZero) { return !hasValue.apply(hasValue, arguments); } ``` ## Related projects You might also be interested in these projects: * [get-object](https://www.npmjs.com/package/get-object): Get a property from an object using dot (object path) notation. | [homepage](https://github.com/jonschlinkert/get-object) * [get-property](https://www.npmjs.com/package/get-property): Get a nested property or its value from an object using simple `a.b.c` paths. | [homepage](https://github.com/jonschlinkert/get-property) * [get-value](https://www.npmjs.com/package/get-value): Use property paths (`a.b.c`) to get a nested value from an object. | [homepage](https://github.com/jonschlinkert/get-value) * [set-value](https://www.npmjs.com/package/set-value): Create nested values and any intermediaries using dot notation (`'a.b.c'`) paths. | [homepage](https://github.com/jonschlinkert/set-value) ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/has-value/issues/new). ## Building docs Generate readme and API documentation with [verb](https://github.com/verbose/verb): ```sh $ npm install verb && npm run docs ``` Or, if [verb](https://github.com/verbose/verb) is installed globally: ```sh $ verb ``` ## Running tests Install dev dependencies: ```sh $ npm install -d && npm test ``` ## Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT license](https://github.com/jonschlinkert/has-value/blob/master/LICENSE). *** _This file was generated by [verb](https://github.com/verbose/verb), v, on March 27, 2016._ # mixin-deep [![NPM version](https://img.shields.io/npm/v/mixin-deep.svg?style=flat)](https://www.npmjs.com/package/mixin-deep) [![NPM monthly downloads](https://img.shields.io/npm/dm/mixin-deep.svg?style=flat)](https://npmjs.org/package/mixin-deep) [![NPM total downloads](https://img.shields.io/npm/dt/mixin-deep.svg?style=flat)](https://npmjs.org/package/mixin-deep) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/mixin-deep.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/mixin-deep) > Deeply mix the properties of objects into the first object. Like merge-deep, but doesn't clone. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save mixin-deep ``` ## Usage ```js var mixinDeep = require('mixin-deep'); mixinDeep({a: {aa: 'aa'}}, {a: {bb: 'bb'}}, {a: {cc: 'cc'}}); //=> { a: { aa: 'aa', bb: 'bb', cc: 'cc' } } ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [defaults-deep](https://www.npmjs.com/package/defaults-deep): Like `extend` but recursively copies only the missing properties/values to the target object. | [homepage](https://github.com/jonschlinkert/defaults-deep "Like `extend` but recursively copies only the missing properties/values to the target object.") * [extend-shallow](https://www.npmjs.com/package/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. | [homepage](https://github.com/jonschlinkert/extend-shallow "Extend an object with the properties of additional objects. node.js/javascript util.") * [merge-deep](https://www.npmjs.com/package/merge-deep): Recursively merge values in a javascript object. | [homepage](https://github.com/jonschlinkert/merge-deep "Recursively merge values in a javascript object.") * [mixin-object](https://www.npmjs.com/package/mixin-object): Mixin the own and inherited properties of other objects onto the first object. Pass an… [more](https://github.com/jonschlinkert/mixin-object) | [homepage](https://github.com/jonschlinkert/mixin-object "Mixin the own and inherited properties of other objects onto the first object. Pass an empty object as the first arg to shallow clone.") ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on December 09, 2017._ # kind-of [![NPM version](https://img.shields.io/npm/v/kind-of.svg?style=flat)](https://www.npmjs.com/package/kind-of) [![NPM monthly downloads](https://img.shields.io/npm/dm/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![NPM total downloads](https://img.shields.io/npm/dt/kind-of.svg?style=flat)](https://npmjs.org/package/kind-of) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/kind-of.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/kind-of) > Get the native type of a value. Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save kind-of ``` Install with [bower](https://bower.io/) ```sh $ bower install kind-of --save ``` ## Why use this? 1. [it's fast](#benchmarks) | [optimizations](#optimizations) 2. [better type checking](#better-type-checking) ## Usage > es5, es6, and browser ready ```js var kindOf = require('kind-of'); kindOf(undefined); //=> 'undefined' kindOf(null); //=> 'null' kindOf(true); //=> 'boolean' kindOf(false); //=> 'boolean' kindOf(new Buffer('')); //=> 'buffer' kindOf(42); //=> 'number' kindOf('str'); //=> 'string' kindOf(arguments); //=> 'arguments' kindOf({}); //=> 'object' kindOf(Object.create(null)); //=> 'object' kindOf(new Test()); //=> 'object' kindOf(new Date()); //=> 'date' kindOf([1, 2, 3]); //=> 'array' kindOf(/foo/); //=> 'regexp' kindOf(new RegExp('foo')); //=> 'regexp' kindOf(new Error('error')); //=> 'error' kindOf(function () {}); //=> 'function' kindOf(function * () {}); //=> 'generatorfunction' kindOf(Symbol('str')); //=> 'symbol' kindOf(new Map()); //=> 'map' kindOf(new WeakMap()); //=> 'weakmap' kindOf(new Set()); //=> 'set' kindOf(new WeakSet()); //=> 'weakset' kindOf(new Int8Array()); //=> 'int8array' kindOf(new Uint8Array()); //=> 'uint8array' kindOf(new Uint8ClampedArray()); //=> 'uint8clampedarray' kindOf(new Int16Array()); //=> 'int16array' kindOf(new Uint16Array()); //=> 'uint16array' kindOf(new Int32Array()); //=> 'int32array' kindOf(new Uint32Array()); //=> 'uint32array' kindOf(new Float32Array()); //=> 'float32array' kindOf(new Float64Array()); //=> 'float64array' ``` ## Benchmarks Benchmarked against [typeof](http://github.com/CodingFu/typeof) and [type-of](https://github.com/ForbesLindesay/type-of). ```bash # arguments (32 bytes) kind-of x 17,024,098 ops/sec ±1.90% (86 runs sampled) lib-type-of x 11,926,235 ops/sec ±1.34% (83 runs sampled) lib-typeof x 9,245,257 ops/sec ±1.22% (87 runs sampled) fastest is kind-of (by 161% avg) # array (22 bytes) kind-of x 17,196,492 ops/sec ±1.07% (88 runs sampled) lib-type-of x 8,838,283 ops/sec ±1.02% (87 runs sampled) lib-typeof x 8,677,848 ops/sec ±0.87% (87 runs sampled) fastest is kind-of (by 196% avg) # boolean (24 bytes) kind-of x 16,841,600 ops/sec ±1.10% (86 runs sampled) lib-type-of x 8,096,787 ops/sec ±0.95% (87 runs sampled) lib-typeof x 8,423,345 ops/sec ±1.15% (86 runs sampled) fastest is kind-of (by 204% avg) # buffer (38 bytes) kind-of x 14,848,060 ops/sec ±1.05% (86 runs sampled) lib-type-of x 3,671,577 ops/sec ±1.49% (87 runs sampled) lib-typeof x 8,360,236 ops/sec ±1.24% (86 runs sampled) fastest is kind-of (by 247% avg) # date (30 bytes) kind-of x 16,067,761 ops/sec ±1.58% (86 runs sampled) lib-type-of x 8,954,436 ops/sec ±1.40% (87 runs sampled) lib-typeof x 8,488,307 ops/sec ±1.51% (84 runs sampled) fastest is kind-of (by 184% avg) # error (36 bytes) kind-of x 9,634,090 ops/sec ±1.12% (89 runs sampled) lib-type-of x 7,735,624 ops/sec ±1.32% (86 runs sampled) lib-typeof x 7,442,160 ops/sec ±1.11% (90 runs sampled) fastest is kind-of (by 127% avg) # function (34 bytes) kind-of x 10,031,494 ops/sec ±1.27% (86 runs sampled) lib-type-of x 9,502,757 ops/sec ±1.17% (89 runs sampled) lib-typeof x 8,278,985 ops/sec ±1.08% (88 runs sampled) fastest is kind-of (by 113% avg) # null (24 bytes) kind-of x 18,159,808 ops/sec ±1.92% (86 runs sampled) lib-type-of x 12,927,635 ops/sec ±1.01% (88 runs sampled) lib-typeof x 7,958,234 ops/sec ±1.21% (89 runs sampled) fastest is kind-of (by 174% avg) # number (22 bytes) kind-of x 17,846,779 ops/sec ±0.91% (85 runs sampled) lib-type-of x 3,316,636 ops/sec ±1.19% (86 runs sampled) lib-typeof x 2,329,477 ops/sec ±2.21% (85 runs sampled) fastest is kind-of (by 632% avg) # object-plain (47 bytes) kind-of x 7,085,155 ops/sec ±1.05% (88 runs sampled) lib-type-of x 8,870,930 ops/sec ±1.06% (83 runs sampled) lib-typeof x 8,716,024 ops/sec ±1.05% (87 runs sampled) fastest is lib-type-of (by 112% avg) # regex (25 bytes) kind-of x 14,196,052 ops/sec ±1.65% (84 runs sampled) lib-type-of x 9,554,164 ops/sec ±1.25% (88 runs sampled) lib-typeof x 8,359,691 ops/sec ±1.07% (87 runs sampled) fastest is kind-of (by 158% avg) # string (33 bytes) kind-of x 16,131,428 ops/sec ±1.41% (85 runs sampled) lib-type-of x 7,273,172 ops/sec ±1.05% (87 runs sampled) lib-typeof x 7,382,635 ops/sec ±1.17% (85 runs sampled) fastest is kind-of (by 220% avg) # symbol (34 bytes) kind-of x 17,011,537 ops/sec ±1.24% (86 runs sampled) lib-type-of x 3,492,454 ops/sec ±1.23% (89 runs sampled) lib-typeof x 7,471,235 ops/sec ±2.48% (87 runs sampled) fastest is kind-of (by 310% avg) # template-strings (36 bytes) kind-of x 15,434,250 ops/sec ±1.46% (83 runs sampled) lib-type-of x 7,157,907 ops/sec ±0.97% (87 runs sampled) lib-typeof x 7,517,986 ops/sec ±0.92% (86 runs sampled) fastest is kind-of (by 210% avg) # undefined (29 bytes) kind-of x 19,167,115 ops/sec ±1.71% (87 runs sampled) lib-type-of x 15,477,740 ops/sec ±1.63% (85 runs sampled) lib-typeof x 19,075,495 ops/sec ±1.17% (83 runs sampled) fastest is lib-typeof,kind-of ``` ## Optimizations In 7 out of 8 cases, this library is 2x-10x faster than other top libraries included in the benchmarks. There are a few things that lead to this performance advantage, none of them hard and fast rules, but all of them simple and repeatable in almost any code library: 1. Optimize around the fastest and most common use cases first. Of course, this will change from project-to-project, but I took some time to understand how and why `typeof` checks were being used in my own libraries and other libraries I use a lot. 2. Optimize around bottlenecks - In other words, the order in which conditionals are implemented is significant, because each check is only as fast as the failing checks that came before it. Here, the biggest bottleneck by far is checking for plain objects (an object that was created by the `Object` constructor). I opted to make this check happen by process of elimination rather than brute force up front (e.g. by using something like `val.constructor.name`), so that every other type check would not be penalized it. 3. Don't do uneccessary processing - why do `.slice(8, -1).toLowerCase();` just to get the word `regex`? It's much faster to do `if (type === '[object RegExp]') return 'regex'` 4. There is no reason to make the code in a microlib as terse as possible, just to win points for making it shorter. It's always better to favor performant code over terse code. You will always only be using a single `require()` statement to use the library anyway, regardless of how the code is written. ## Better type checking kind-of seems to be more consistently "correct" than other type checking libs I've looked at. For example, here are some differing results from other popular libs: ### [typeof](https://github.com/CodingFu/typeof) lib Incorrectly identifies instances of custom constructors (pretty common): ```js var typeOf = require('typeof'); function Test() {} console.log(typeOf(new Test())); //=> 'test' ``` Returns `object` instead of `arguments`: ```js function foo() { console.log(typeOf(arguments)) //=> 'object' } foo(); ``` ### [type-of](https://github.com/ForbesLindesay/type-of) lib Incorrectly returns `object` for generator functions, buffers, `Map`, `Set`, `WeakMap` and `WeakSet`: ```js function * foo() {} console.log(typeOf(foo)); //=> 'object' console.log(typeOf(new Buffer(''))); //=> 'object' console.log(typeOf(new Map())); //=> 'object' console.log(typeOf(new Set())); //=> 'object' console.log(typeOf(new WeakMap())); //=> 'object' console.log(typeOf(new WeakSet())); //=> 'object' ``` ## About <details> <summary><strong>Contributing</strong></summary> Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). </details> <details> <summary><strong>Running Tests</strong></summary> Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` </details> <details> <summary><strong>Building docs</strong></summary> _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` </details> ### Related projects You might also be interested in these projects: * [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") * [is-number](https://www.npmjs.com/package/is-number): Returns true if the value is a number. comprehensive tests. | [homepage](https://github.com/jonschlinkert/is-number "Returns true if the value is a number. comprehensive tests.") * [is-primitive](https://www.npmjs.com/package/is-primitive): Returns `true` if the value is a primitive. | [homepage](https://github.com/jonschlinkert/is-primitive "Returns `true` if the value is a primitive. ") ### Contributors | **Commits** | **Contributor** | | --- | --- | | 98 | [jonschlinkert](https://github.com/jonschlinkert) | | 3 | [aretecode](https://github.com/aretecode) | | 2 | [miguelmota](https://github.com/miguelmota) | | 1 | [dtothefp](https://github.com/dtothefp) | | 1 | [ianstormtaylor](https://github.com/ianstormtaylor) | | 1 | [ksheedlo](https://github.com/ksheedlo) | | 1 | [pdehaan](https://github.com/pdehaan) | | 1 | [laggingreflex](https://github.com/laggingreflex) | | 1 | [charlike-old](https://github.com/charlike-old) | ### Author **Jon Schlinkert** * [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert) * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on December 01, 2017._ # amdefine A module that can be used to implement AMD's define() in Node. This allows you to code to the AMD API and have the module work in node programs without requiring those other programs to use AMD. ## Usage **1)** Update your package.json to indicate amdefine as a dependency: ```javascript "dependencies": { "amdefine": ">=0.1.0" } ``` Then run `npm install` to get amdefine into your project. **2)** At the top of each module that uses define(), place this code: ```javascript if (typeof define !== 'function') { var define = require('amdefine')(module) } ``` **Only use these snippets** when loading amdefine. If you preserve the basic structure, with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer). You can add spaces, line breaks and even require amdefine with a local path, but keep the rest of the structure to get the stripping behavior. As you may know, because `if` statements in JavaScript don't have their own scope, the var declaration in the above snippet is made whether the `if` expression is truthy or not. If RequireJS is loaded then the declaration is superfluous because `define` is already already declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var` declarations of the same variable in the same scope gracefully. If you want to deliver amdefine.js with your code rather than specifying it as a dependency with npm, then just download the latest release and refer to it using a relative path: [Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js) ### amdefine/intercept Consider this very experimental. Instead of pasting the piece of text for the amdefine setup of a `define` variable in each module you create or consume, you can use `amdefine/intercept` instead. It will automatically insert the above snippet in each .js file loaded by Node. **Warning**: you should only use this if you are creating an application that is consuming AMD style defined()'d modules that are distributed via npm and want to run that code in Node. For library code where you are not sure if it will be used by others in Node or in the browser, then explicitly depending on amdefine and placing the code snippet above is suggested path, instead of using `amdefine/intercept`. The intercept module affects all .js files loaded in the Node app, and it is inconsiderate to modify global state like that unless you are also controlling the top level app. #### Why distribute AMD-style modules via npm? npm has a lot of weaknesses for front-end use (installed layout is not great, should have better support for the `baseUrl + moduleID + '.js' style of loading, single file JS installs), but some people want a JS package manager and are willing to live with those constraints. If that is you, but still want to author in AMD style modules to get dynamic require([]), better direct source usage and powerful loader plugin support in the browser, then this tool can help. #### amdefine/intercept usage Just require it in your top level app module (for example index.js, server.js): ```javascript require('amdefine/intercept'); ``` The module does not return a value, so no need to assign the result to a local variable. Then just require() code as you normally would with Node's require(). Any .js loaded after the intercept require will have the amdefine check injected in the .js source as it is loaded. It does not modify the source on disk, just prepends some content to the text of the module as it is loaded by Node. #### How amdefine/intercept works It overrides the `Module._extensions['.js']` in Node to automatically prepend the amdefine snippet above. So, it will affect any .js file loaded by your app. ## define() usage It is best if you use the anonymous forms of define() in your module: ```javascript define(function (require) { var dependency = require('dependency'); }); ``` or ```javascript define(['dependency'], function (dependency) { }); ``` ## RequireJS optimizer integration. <a name="optimizer"></name> Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html) will have support for stripping the `if (typeof define !== 'function')` check mentioned above, so you can include this snippet for code that runs in the browser, but avoid taking the cost of the if() statement once the code is optimized for deployment. ## Node 0.4 Support If you want to support Node 0.4, then add `require` as the second parameter to amdefine: ```javascript //Only if you want Node 0.4. If using 0.5 or later, use the above snippet. if (typeof define !== 'function') { var define = require('amdefine')(module, require) } ``` ## Limitations ### Synchronous vs Asynchronous amdefine creates a define() function that is callable by your code. It will execute and trace dependencies and call the factory function *synchronously*, to keep the behavior in line with Node's synchronous dependency tracing. The exception: calling AMD's callback-style require() from inside a factory function. The require callback is called on process.nextTick(): ```javascript define(function (require) { require(['a'], function(a) { //'a' is loaded synchronously, but //this callback is called on process.nextTick(). }); }); ``` ### Loader Plugins Loader plugins are supported as long as they call their load() callbacks synchronously. So ones that do network requests will not work. However plugins like [text](http://requirejs.org/docs/api.html#text) can load text files locally. The plugin API's `load.fromText()` is **not supported** in amdefine, so this means transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs) will not work. This may be fixable, but it is a bit complex, and I do not have enough node-fu to figure it out yet. See the source for amdefine.js if you want to get an idea of the issues involved. ## Tests To run the tests, cd to **tests** and run: ``` node all.js node all-intercept.js ``` ## License New BSD and MIT. Check the LICENSE file for all the details. # node-error-ex [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-error-ex.svg?style=flat-square)](https://travis-ci.org/Qix-/node-error-ex) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-error-ex.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-error-ex) > Easily subclass and customize new Error types ## Examples To include in your project: ```javascript var errorEx = require('error-ex'); ``` To create an error message type with a specific name (note, that `ErrorFn.name` will not reflect this): ```javascript var JSONError = errorEx('JSONError'); var err = new JSONError('error'); err.name; //-> JSONError throw err; //-> JSONError: error ``` To add a stack line: ```javascript var JSONError = errorEx('JSONError', {fileName: errorEx.line('in %s')}); var err = new JSONError('error') err.fileName = '/a/b/c/foo.json'; throw err; //-> (line 2)-> in /a/b/c/foo.json ``` To append to the error message: ```javascript var JSONError = errorEx('JSONError', {fileName: errorEx.append('in %s')}); var err = new JSONError('error'); err.fileName = '/a/b/c/foo.json'; throw err; //-> JSONError: error in /a/b/c/foo.json ``` ## API #### `errorEx([name], [properties])` Creates a new ErrorEx error type - `name`: the name of the new type (appears in the error message upon throw; defaults to `Error.name`) - `properties`: if supplied, used as a key/value dictionary of properties to use when building up the stack message. Keys are property names that are looked up on the error message, and then passed to function values. - `line`: if specified and is a function, return value is added as a stack entry (error-ex will indent for you). Passed the property value given the key. - `stack`: if specified and is a function, passed the value of the property using the key, and the raw stack lines as a second argument. Takes no return value (but the stack can be modified directly). - `message`: if specified and is a function, return value is used as new `.message` value upon get. Passed the property value of the property named by key, and the existing message is passed as the second argument as an array of lines (suitable for multi-line messages). Returns a constructor (Function) that can be used just like the regular Error constructor. ```javascript var errorEx = require('error-ex'); var BasicError = errorEx(); var NamedError = errorEx('NamedError'); // -- var AdvancedError = errorEx('AdvancedError', { foo: { line: function (value, stack) { if (value) { return 'bar ' + value; } return null; } } } var err = new AdvancedError('hello, world'); err.foo = 'baz'; throw err; /* AdvancedError: hello, world bar baz at tryReadme() (readme.js:20:1) */ ``` #### `errorEx.line(str)` Creates a stack line using a delimiter > This is a helper function. It is to be used in lieu of writing a value object > for `properties` values. - `str`: The string to create - Use the delimiter `%s` to specify where in the string the value should go ```javascript var errorEx = require('error-ex'); var FileError = errorEx('FileError', {fileName: errorEx.line('in %s')}); var err = new FileError('problem reading file'); err.fileName = '/a/b/c/d/foo.js'; throw err; /* FileError: problem reading file in /a/b/c/d/foo.js at tryReadme() (readme.js:7:1) */ ``` #### `errorEx.append(str)` Appends to the `error.message` string > This is a helper function. It is to be used in lieu of writing a value object > for `properties` values. - `str`: The string to append - Use the delimiter `%s` to specify where in the string the value should go ```javascript var errorEx = require('error-ex'); var SyntaxError = errorEx('SyntaxError', {fileName: errorEx.append('in %s')}); var err = new SyntaxError('improper indentation'); err.fileName = '/a/b/c/d/foo.js'; throw err; /* SyntaxError: improper indentation in /a/b/c/d/foo.js at tryReadme() (readme.js:7:1) */ ``` ## License Licensed under the [MIT License](http://opensource.org/licenses/MIT). You can find a copy of it in [LICENSE](LICENSE). # scss-tokenizer A tokenzier for Sass' SCSS syntax ![https://travis-ci.org/sasstools/scss-tokenizer.svg?branch=master](https://img.shields.io/travis/sasstools/scss-tokenizer.svg) ![https://www.npmjs.com/package/scss-tokenizer](https://img.shields.io/npm/v/scss-tokenizer.svg) ![https://github.com/sasstools/scss-tokenizer/issues](https://img.shields.io/github/issues/sasstools/scss-tokenizer.svg) ![](https://img.shields.io/github/license/sasstools/scss-tokenizer.svg) # Install ``` npm install scss-tokenizer ``` # Usage ```js var scss = require('scss-tokenizer'); scss.tokenize(css); ``` # API ### `tokenize` Tokenizes source `css` and returns an ordered array of tokens with positional data. ```js var tokenizer = require('scss-tokenizer'); var tokens = tokenize.tokenize(css); ``` Arguments: * `css (string|#toString)`: String with input CSS or any object with `toString()` method, like file stream. * `opts (object) optional`: options: * `from`: the path to the source CSS file. You should always set `from`, because it is used in map generation and in syntax error messages. # Test ``` npm test ``` ## Attribution This project started as a fork of the [PostCSS](https://github.com/postcss/postcss) tokenizer. # isStream [![Build Status](https://secure.travis-ci.org/rvagg/isstream.png)](http://travis-ci.org/rvagg/isstream) **Test if an object is a `Stream`** [![NPM](https://nodei.co/npm/isstream.svg)](https://nodei.co/npm/isstream/) The missing `Stream.isStream(obj)`: determine if an object is standard Node.js `Stream`. Works for Node-core `Stream` objects (for 0.8, 0.10, 0.11, and in theory, older and newer versions) and all versions of **[readable-stream](https://github.com/isaacs/readable-stream)**. ## Usage: ```js var isStream = require('isstream') var Stream = require('stream') isStream(new Stream()) // true isStream({}) // false isStream(new Stream.Readable()) // true isStream(new Stream.Writable()) // true isStream(new Stream.Duplex()) // true isStream(new Stream.Transform()) // true isStream(new Stream.PassThrough()) // true ``` ## But wait! There's more! You can also test for `isReadable(obj)`, `isWritable(obj)` and `isDuplex(obj)` to test for implementations of Streams2 (and Streams3) base classes. ```js var isReadable = require('isstream').isReadable var isWritable = require('isstream').isWritable var isDuplex = require('isstream').isDuplex var Stream = require('stream') isReadable(new Stream()) // false isWritable(new Stream()) // false isDuplex(new Stream()) // false isReadable(new Stream.Readable()) // true isReadable(new Stream.Writable()) // false isReadable(new Stream.Duplex()) // true isReadable(new Stream.Transform()) // true isReadable(new Stream.PassThrough()) // true isWritable(new Stream.Readable()) // false isWritable(new Stream.Writable()) // true isWritable(new Stream.Duplex()) // true isWritable(new Stream.Transform()) // true isWritable(new Stream.PassThrough()) // true isDuplex(new Stream.Readable()) // false isDuplex(new Stream.Writable()) // false isDuplex(new Stream.Duplex()) // true isDuplex(new Stream.Transform()) // true isDuplex(new Stream.PassThrough()) // true ``` *Reminder: when implementing your own streams, please [use **readable-stream** rather than core streams](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).* ## License **isStream** is Copyright (c) 2015 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. # fs.realpath A backwards-compatible fs.realpath for Node v6 and above In Node v6, the JavaScript implementation of fs.realpath was replaced with a faster (but less resilient) native implementation. That raises new and platform-specific errors and cannot handle long or excessively symlink-looping paths. This module handles those cases by detecting the new errors and falling back to the JavaScript implementation. On versions of Node prior to v6, it has no effect. ## USAGE ```js var rp = require('fs.realpath') // async version rp.realpath(someLongAndLoopingPath, function (er, real) { // the ELOOP was handled, but it was a bit slower }) // sync version var real = rp.realpathSync(someLongAndLoopingPath) // monkeypatch at your own risk! // This replaces the fs.realpath/fs.realpathSync builtins rp.monkeypatch() // un-do the monkeypatching rp.unmonkeypatch() ``` # type-is [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] Infer the content-type of a request. ### Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install type-is ``` ## API ```js var http = require('http') var typeis = require('type-is') http.createServer(function (req, res) { var istext = typeis(req, ['text/*']) res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') }) ``` ### type = typeis(request, types) `request` is the node HTTP request. `types` is an array of types. <!-- eslint-disable no-undef --> ```js // req.headers.content-type = 'application/json' typeis(req, ['json']) // 'json' typeis(req, ['html', 'json']) // 'json' typeis(req, ['application/*']) // 'application/json' typeis(req, ['application/json']) // 'application/json' typeis(req, ['html']) // false ``` ### typeis.hasBody(request) Returns a Boolean if the given `request` has a body, regardless of the `Content-Type` header. Having a body has no relation to how large the body is (it may be 0 bytes). This is similar to how file existence works. If a body does exist, then this indicates that there is data to read from the Node.js request stream. <!-- eslint-disable no-undef --> ```js if (typeis.hasBody(req)) { // read the body, since there is one req.on('data', function (chunk) { // ... }) } ``` ### type = typeis.is(mediaType, types) `mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. <!-- eslint-disable no-undef --> ```js var mediaType = 'application/json' typeis.is(mediaType, ['json']) // 'json' typeis.is(mediaType, ['html', 'json']) // 'json' typeis.is(mediaType, ['application/*']) // 'application/json' typeis.is(mediaType, ['application/json']) // 'application/json' typeis.is(mediaType, ['html']) // false ``` ### Each type can be: - An extension name such as `json`. This name will be returned if matched. - A mime type such as `application/json`. - A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. The full mime type will be returned if matched. - A suffix such as `+json`. This can be combined with a wildcard such as `*/vnd+json` or `application/*+json`. The full mime type will be returned if matched. `false` will be returned if no type matches or the content type is invalid. `null` will be returned if the request does not have a body. ## Examples ### Example body parser ```js var express = require('express') var typeis = require('type-is') var app = express() app.use(function bodyParser (req, res, next) { if (!typeis.hasBody(req)) { return next() } switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { case 'urlencoded': // parse urlencoded body throw new Error('implement urlencoded body parsing') case 'json': // parse json body throw new Error('implement json body parsing') case 'multipart': // parse multipart body throw new Error('implement multipart body parsing') default: // 415 error code res.statusCode = 415 res.end() break } }) ``` ## License [MIT](LICENSE) [npm-image]: https://img.shields.io/npm/v/type-is.svg [npm-url]: https://npmjs.org/package/type-is [node-version-image]: https://img.shields.io/node/v/type-is.svg [node-version-url]: https://nodejs.org/en/download/ [travis-image]: https://img.shields.io/travis/jshttp/type-is/master.svg [travis-url]: https://travis-ci.org/jshttp/type-is [coveralls-image]: https://img.shields.io/coveralls/jshttp/type-is/master.svg [coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master [downloads-image]: https://img.shields.io/npm/dm/type-is.svg [downloads-url]: https://npmjs.org/package/type-is #utf8 detector Detect if a Buffer is utf8 encoded. It need The minimum amount of bytes is 4. ```javascript var fs = require('fs'); var isUtf8 = require('is-utf8'); var ansi = fs.readFileSync('ansi.txt'); var utf8 = fs.readFileSync('utf8.txt'); console.log('ansi.txt is utf8: '+isUtf8(ansi)); //false console.log('utf8.txt is utf8: '+isUtf8(utf8)); //true ``` # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ # node-errno > Better [libuv](https://github.com/libuv/libuv)/[Node.js](https://nodejs.org)/[io.js](https://iojs.org) error handling & reporting. Available in npm as *errno*. [![npm](https://img.shields.io/npm/v/errno.svg)](https://www.npmjs.com/package/errno) [![Build Status](https://secure.travis-ci.org/rvagg/node-errno.png)](http://travis-ci.org/rvagg/node-errno) [![npm](https://img.shields.io/npm/dm/errno.svg)](https://www.npmjs.com/package/errno) * [errno exposed](#errnoexposed) * [Custom errors](#customerrors) <a name="errnoexposed"></a> ## errno exposed Ever find yourself needing more details about Node.js errors? Me too, so *node-errno* contains the errno mappings direct from libuv so you can use them in your code. **By errno:** ```js require('errno').errno[3] // → { // "errno": 3, // "code": "EACCES", // "description": "permission denied" // } ``` **By code:** ```js require('errno').code.ENOTEMPTY // → { // "errno": 53, // "code": "ENOTEMPTY", // "description": "directory not empty" // } ``` **Make your errors more descriptive:** ```js var errno = require('errno') function errmsg(err) { var str = 'Error: ' // if it's a libuv error then get the description from errno if (errno.errno[err.errno]) str += errno.errno[err.errno].description else str += err.message // if it's a `fs` error then it'll have a 'path' property if (err.path) str += ' [' + err.path + ']' return str } var fs = require('fs') fs.readFile('thisisnotarealfile.txt', function (err, data) { if (err) console.log(errmsg(err)) }) ``` **Use as a command line tool:** ``` ~ $ errno 53 { "errno": 53, "code": "ENOTEMPTY", "description": "directory not empty" } ~ $ errno EROFS { "errno": 56, "code": "EROFS", "description": "read-only file system" } ~ $ errno foo No such errno/code: "foo" ``` Supply no arguments for the full list. Error codes are processed case-insensitive. You will need to install with `npm install errno -g` if you want the `errno` command to be available without supplying a full path to the node_modules installation. <a name="customerrors"></a> ## Custom errors Use `errno.custom.createError()` to create custom `Error` objects to throw around in your Node.js library. Create error hierarchies so `instanceof` becomes a useful tool in tracking errors. Call-stack is correctly captured at the time you create an instance of the error object, plus a `cause` property will make available the original error object if you pass one in to the constructor. ```js var create = require('errno').custom.createError var MyError = create('MyError') // inherits from Error var SpecificError = create('SpecificError', MyError) // inherits from MyError var OtherError = create('OtherError', MyError) // use them! if (condition) throw new SpecificError('Eeek! Something bad happened') if (err) return callback(new OtherError(err)) ``` Also available is a `errno.custom.FilesystemError` with in-built access to errno properties: ```js fs.readFile('foo', function (err, data) { if (err) return callback(new errno.custom.FilesystemError(err)) // do something else }) ``` The resulting error object passed through the callback will have the following properties: `code`, `errno`, `path` and `message` will contain a descriptive human-readable message. ## Contributors * [bahamas10](https://github.com/bahamas10) (Dave Eddy) - Added CLI * [ralphtheninja](https://github.com/ralphtheninja) (Lars-Magnus Skog) ## Copyright & Licence *Copyright (c) 2012-2015 [Rod Vagg](https://github.com/rvagg) ([@rvagg](https://twitter.com/rvagg))* Made available under the MIT licence: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # util [![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util) node.js [util](http://nodejs.org/api/util.html) module as a module ## install via [npm](npmjs.org) ```shell npm install util ``` ## browser support This module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features. # is-extendable [![NPM version](https://badge.fury.io/js/is-extendable.svg)](http://badge.fury.io/js/is-extendable) > Returns true if a value is any of the object types: array, regexp, plain object, function or date. This is useful for determining if a value can be extended, e.g. "can the value have keys?" ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i is-extendable --save ``` ## Usage ```js var isExtendable = require('is-extendable'); ``` Returns true if the value is any of the following: * `array` * `regexp` * `plain object` * `function` * `date` * `error` ## Notes All objects in JavaScript can have keys, but it's a pain to check for this, since we ether need to verify that the value is not `null` or `undefined` and: * the value is not a primitive, or * that the object is an `object`, `function` Also note that an `extendable` object is not the same as an [extensible object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), which is one that (in es6) is not sealed, frozen, or marked as non-extensible using `preventExtensions`. ## Related projects * [assign-deep](https://github.com/jonschlinkert/assign-deep): Deeply assign the enumerable properties of source objects to a destination object. * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [is-equal-shallow](https://github.com/jonschlinkert/is-equal-shallow): Does a shallow comparison of two objects, returning false if the keys or values differ. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](https://github.com/jonschlinkert/is-extendable/issues/new) ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on July 04, 2015._ # Cyclist Cyclist is an efficient [cyclic list](http://en.wikipedia.org/wiki/Circular_buffer) implemention for Javascript. It is available through npm npm install cyclist ## What? Cyclist allows you to create a list of fixed size that is cyclic. In a cyclist list the element following the last one is the first one. This property can be really useful when for example trying to order data packets that can arrive out of order over a network stream. ## Usage ``` js var cyclist = require('cyclist'); var list = cyclist(4); // if size (4) is not a power of 2 it will be the follwing power of 2 // this buffer can now hold 4 elements in total list.put(42, 'hello 42'); // store something and index 42 list.put(43, 'hello 43'); // store something and index 43 console.log(list.get(42)); // prints hello 42 console.log(list.get(46)); // prints hello 42 again since 46 - 42 == list.size ``` ## API * `cyclist(size)` creates a new buffer * `cyclist#get(index)` get an object stored in the buffer * `cyclist#put(index,value)` insert an object into the buffer * `cyclist#del(index)` delete an object from an index * `cyclist#size` property containing current size of buffer ## License MIT <div align="center"> <a href="https://github.com/webpack/webpack"> <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg"> </a> </div> [![npm][npm]][npm-url] [![node][node]][node-url] [![deps][deps]][deps-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![chat][chat]][chat-url] # webpack-log A common logging module for the Webpack ecosystem. `webpack-log` leverages [`loglevelnext`][loglevelnext]. ## Getting Started First thing's first, install the module: ```console npm install webpack-log --save ``` _Note: We do not recommend installing this module globally._ ## Requirements `webpack-log` requires Node v6 or higher. ## Usage ```js const weblog = require('webpack-log'); const log = weblog({ name: 'wds' }) // webpack-dev-server log.info('Server Starting'); ``` The code above will produce: ![output](output.png) ## Options The default export (`function`) will return a logger, given an `options` Object. The following is a property reference for the Object. _Note: the logger returned is unique by default, due to the nature of the `webpack` ecosystem. Please reference the [`unique`](#unique) option below for disabling this feature and to force caching._ ### level Type: `String` Default: `'info'` Specifies the level the logger should use. A logger will not produce output for any log level _beneath_ the specified level. Available levels and order are: ```js [ 'trace', 'debug', 'info', 'warn', 'error', 'silent' ] ``` _Note: The level names shown above correspond to the available logging methods, with the notable exception of the `silent` level._ ### name _Required_ Type: `String` Default: `'<unknown>'` Specifies the name of the log to create. This property is required, and used to differentiate between loggers when `webpack-log` is used in multiple projects executing in the same process space. ### timestamp Type: `Boolean` Default: `false` If `true`, instructs the logger to display a timestamp for log output, preceding all other data. ### unique Type: `Boolean` Default: `true` If `false`, instructs the logger to used cached versions of a log with the same name. Due to the nature of the `webpack` ecosystem and multiple plugin/loader use in the same process space, loggers are created as unique instances by default. By passing `false` for this property, the module is instructed to cache the requested logger. ## Contributing We welcome your contributions! Please have a read of [CONTRIBUTING.md](CONTRIBUTING.md) for more information on how to get involved. ## License #### [MIT](./LICENSE) [npm]: https://img.shields.io/npm/v/webpack-log.svg [npm-url]: https://npmjs.com/package/webpack-log [node]: https://img.shields.io/node/v/webpack-log.svg [node-url]: https://nodejs.org [deps]: https://david-dm.org/webpack-contrib/webpack-log.svg [deps-url]: https://david-dm.org/webpack-contrib/webpack-log [tests]: http://img.shields.io/travis/webpack-contrib/webpack-log.svg [tests-url]: https://travis-ci.org/webpack-contrib/webpack-log [cover]: https://codecov.io/gh/webpack-contrib/webpack-log/branch/master/graph/badge.svg [cover-url]: https://codecov.io/gh/webpack-contrib/webpack-log [chat]: https://badges.gitter.im/webpack/webpack.svg [chat-url]: https://gitter.im/webpack/webpack [loglevelnext]: https://github.com/shellscape/loglevelnext # extend-shallow [![NPM version](https://badge.fury.io/js/extend-shallow.svg)](http://badge.fury.io/js/extend-shallow) [![Build Status](https://travis-ci.org/jonschlinkert/extend-shallow.svg)](https://travis-ci.org/jonschlinkert/extend-shallow) > Extend an object with the properties of additional objects. node.js/javascript util. ## Install Install with [npm](https://www.npmjs.com/) ```sh $ npm i extend-shallow --save ``` ## Usage ```js var extend = require('extend-shallow'); extend({a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` Pass an empty object to shallow clone: ```js var obj = {}; extend(obj, {a: 'b'}, {c: 'd'}) //=> {a: 'b', c: 'd'} ``` ## Related * [extend-shallow](https://github.com/jonschlinkert/extend-shallow): Extend an object with the properties of additional objects. node.js/javascript util. * [for-own](https://github.com/jonschlinkert/for-own): Iterate over the own enumerable properties of an object, and return an object with properties… [more](https://github.com/jonschlinkert/for-own) * [for-in](https://github.com/jonschlinkert/for-in): Iterate over the own and inherited enumerable properties of an objecte, and return an object… [more](https://github.com/jonschlinkert/for-in) * [is-plain-object](https://github.com/jonschlinkert/is-plain-object): Returns true if an object was created by the `Object` constructor. * [isobject](https://github.com/jonschlinkert/isobject): Returns true if the value is an object and not an array or null. * [kind-of](https://github.com/jonschlinkert/kind-of): Get the native type of a value. ## Running tests Install dev dependencies: ```sh $ npm i -d && npm test ``` ## Author **Jon Schlinkert** + [github/jonschlinkert](https://github.com/jonschlinkert) + [twitter/jonschlinkert](http://twitter.com/jonschlinkert) ## License Copyright © 2015 Jon Schlinkert Released under the MIT license. *** _This file was generated by [verb-cli](https://github.com/assemble/verb-cli) on June 29, 2015._ [![Build Status](https://travis-ci.org/css-modules/icss-utils.svg)](https://travis-ci.org/css-modules/icss-utils) # ICSS Utils ## replaceSymbols Governs the way tokens are searched & replaced during the linking stage of ICSS loading. This is broken into its own module in case the behaviour needs to be replicated in other PostCSS plugins (i.e. [CSS Modules Values](https://github.com/css-modules/postcss-modules-values)) ```js import { replaceSymbols, replaceValueSymbols } from "icss-utils"; replaceSymbols(css, replacements); replaceValueSymbols(string, replacements); ``` Where: - `css` is the PostCSS tree you're working with - `replacements` is an JS object of `symbol: "replacement"` pairs, where all occurrences of `symbol` are replaced with `replacement`. A symbol is a string of alphanumeric, `-` or `_` characters. A replacement can be any string. They are replaced in the following places: - In the value of a declaration, i.e. `color: my_symbol;` or `box-shadow: 0 0 blur spread shadow-color` - In a media expression i.e. `@media small {}` or `@media screen and not-large {}` ## extractICSS(css, removeRules = true) Extracts and remove (if removeRules is equal true) from PostCSS tree `:import` and `:export` statements. ```js import postcss from "postcss"; import { extractICSS } from "icss-utils"; const css = postcss.parse(` :import(colors) { a: b; } :export { c: d; } `); extractICSS(css); /* { icssImports: { colors: { a: 'b' } }, icssExports: { c: 'd' } } */ ``` ## createICSSRules(icssImports, icssExports) Converts icss imports and exports definitions to postcss ast ```js createICSSRules( { colors: { a: "b" } }, { c: "d" } ); ``` ## License ISC --- Glen Maddern, Bogdan Chadkin and Evilebottnawi 2015-present. # is-extendable [![NPM version](https://img.shields.io/npm/v/is-extendable.svg?style=flat)](https://www.npmjs.com/package/is-extendable) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-extendable.svg?style=flat)](https://npmjs.org/package/is-extendable) [![NPM total downloads](https://img.shields.io/npm/dt/is-extendable.svg?style=flat)](https://npmjs.org/package/is-extendable) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-extendable.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-extendable) > Returns true if a value is a plain object, array or function. ## Install Install with [npm](https://www.npmjs.com/): ```sh $ npm install --save is-extendable ``` ## Usage ```js var isExtendable = require('is-extendable'); ``` Returns true if the value is any of the following: * array * plain object * function ## Notes All objects in JavaScript can have keys, but it's a pain to check for this, since we ether need to verify that the value is not `null` or `undefined` and: * the value is not a primitive, or * that the object is a plain object, function or array Also note that an `extendable` object is not the same as an [extensible object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible), which is one that (in es6) is not sealed, frozen, or marked as non-extensible using `preventExtensions`. ## Release history ### v1.0.0 - 2017/07/20 **Breaking changes** * No longer considers date, regex or error objects to be extendable ## About ### Related projects * [assign-deep](https://www.npmjs.com/package/assign-deep): Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target… [more](https://github.com/jonschlinkert/assign-deep) | [homepage](https://github.com/jonschlinkert/assign-deep "Deeply assign the enumerable properties and/or es6 Symbol properies of source objects to the target (first) object.") * [is-equal-shallow](https://www.npmjs.com/package/is-equal-shallow): Does a shallow comparison of two objects, returning false if the keys or values differ. | [homepage](https://github.com/jonschlinkert/is-equal-shallow "Does a shallow comparison of two objects, returning false if the keys or values differ.") * [is-plain-object](https://www.npmjs.com/package/is-plain-object): Returns true if an object was created by the `Object` constructor. | [homepage](https://github.com/jonschlinkert/is-plain-object "Returns true if an object was created by the `Object` constructor.") * [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.") * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") ### Contributing Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). ### Building docs _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ To generate the readme, run the following command: ```sh $ npm install -g verbose/verb#dev verb-generate-readme && verb ``` ### Running tests Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: ```sh $ npm install && npm test ``` ### Author **Jon Schlinkert** * [github/jonschlinkert](https://github.com/jonschlinkert) * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) ### License Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). Released under the [MIT License](LICENSE). *** _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on July 20, 2017._ # fs-write-stream-atomic Like `fs.createWriteStream(...)`, but atomic. Writes to a tmp file and does an atomic `fs.rename` to move it into place when it's done. First rule of debugging: **It's always a race condition.** ## USAGE ```javascript var fsWriteStreamAtomic = require('fs-write-stream-atomic') // options are optional. var write = fsWriteStreamAtomic('output.txt', options) var read = fs.createReadStream('input.txt') read.pipe(write) // When the write stream emits a 'finish' or 'close' event, // you can be sure that it is moved into place, and contains // all the bytes that were written to it, even if something else // was writing to `output.txt` at the same time. ``` ### `fsWriteStreamAtomic(filename, [options])` * `filename` {String} The file we want to write to * `options` {Object} * `chown` {Object} User and group to set ownership after write * `uid` {Number} * `gid` {Number} * `encoding` {String} default = 'utf8' * `mode` {Number} default = `0666` * `flags` {String} default = `'w'` # Request - Simplified HTTP client [![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/) [![Build status](https://img.shields.io/travis/request/request/master.svg?style=flat-square)](https://travis-ci.org/request/request) [![Coverage](https://img.shields.io/codecov/c/github/request/request.svg?style=flat-square)](https://codecov.io/github/request/request?branch=master) [![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request) [![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request) [![Known Vulnerabilities](https://snyk.io/test/npm/request/badge.svg?style=flat-square)](https://snyk.io/test/npm/request) [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge) ## Super simple to use Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. ```js var request = require('request'); request('http://www.google.com', function (error, response, body) { console.log('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); ``` ## Table of contents - [Streaming](#streaming) - [Promises & Async/Await](#promises--asyncawait) - [Forms](#forms) - [HTTP Authentication](#http-authentication) - [Custom HTTP Headers](#custom-http-headers) - [OAuth Signing](#oauth-signing) - [Proxies](#proxies) - [Unix Domain Sockets](#unix-domain-sockets) - [TLS/SSL Protocol](#tlsssl-protocol) - [Support for HAR 1.2](#support-for-har-12) - [**All Available Options**](#requestoptions-callback) Request also offers [convenience methods](#convenience-methods) like `request.defaults` and `request.post`, and there are lots of [usage examples](#examples) and several [debugging techniques](#debugging). --- ## Streaming You can stream any response to a file stream. ```js request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) ``` You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one). ```js fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) ``` Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers. ```js request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) ``` Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage). ```js request .get('http://google.com/img.png') .on('response', function(response) { console.log(response.statusCode) // 200 console.log(response.headers['content-type']) // 'image/png' }) .pipe(request.put('http://mysite.com/img.png')) ``` To easily handle errors when streaming requests, listen to the `error` event before piping: ```js request .get('http://mysite.com/doodle.png') .on('error', function(err) { console.log(err) }) .pipe(fs.createWriteStream('doodle.png')) ``` Now let’s get fancy. ```js http.createServer(function (req, resp) { if (req.url === '/doodle.png') { if (req.method === 'PUT') { req.pipe(request.put('http://mysite.com/doodle.png')) } else if (req.method === 'GET' || req.method === 'HEAD') { request.get('http://mysite.com/doodle.png').pipe(resp) } } }) ``` You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do: ```js http.createServer(function (req, resp) { if (req.url === '/doodle.png') { var x = request('http://mysite.com/doodle.png') req.pipe(x) x.pipe(resp) } }) ``` And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :) ```js req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) ``` Also, none of this new functionality conflicts with requests previous features, it just expands them. ```js var r = request.defaults({'proxy':'http://localproxy.com'}) http.createServer(function (req, resp) { if (req.url === '/doodle.png') { r.get('http://google.com/doodle.png').pipe(resp) } }) ``` You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. [back to top](#table-of-contents) --- ## Promises & Async/Await `request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017. Several alternative interfaces are provided by the request team, including: - [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises) - [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises) - [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises) [back to top](#table-of-contents) --- ## Forms `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API. #### application/x-www-form-urlencoded (URL-Encoded Forms) URL-encoded forms are simple. ```js request.post('http://service.com/upload', {form:{key:'value'}}) // or request.post('http://service.com/upload').form({key:'value'}) // or request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) ``` #### multipart/form-data (Multipart Form Uploads) For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option. ```js var formData = { // Pass a simple key-value pair my_field: 'my_value', // Pass data via Buffers my_buffer: Buffer.from([1, 2, 3]), // Pass data via Streams my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), // Pass multiple values /w an Array attachments: [ fs.createReadStream(__dirname + '/attachment1.jpg'), fs.createReadStream(__dirname + '/attachment2.jpg') ], // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS} // Use case: for some types of streams, you'll need to provide "file"-related information manually. // See the `form-data` README for more information about options: https://github.com/form-data/form-data custom_file: { value: fs.createReadStream('/dev/urandom'), options: { filename: 'topsecret.jpg', contentType: 'image/jpeg' } } }; request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); ``` For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.) ```js // NOTE: Advanced use-case, for normal use see 'formData' usage above var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...}) var form = r.form(); form.append('my_field', 'my_value'); form.append('my_buffer', Buffer.from([1, 2, 3])); form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); ``` See the [form-data README](https://github.com/form-data/form-data) for more information & examples. #### multipart/related Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options. ```js request({ method: 'PUT', preambleCRLF: true, postambleCRLF: true, uri: 'http://service.com/upload', multipart: [ { 'content-type': 'application/json', body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) }, { body: 'I am an attachment' }, { body: fs.createReadStream('image.png') } ], // alternatively pass an object containing additional options multipart: { chunked: false, data: [ { 'content-type': 'application/json', body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) }, { body: 'I am an attachment' } ] } }, function (error, response, body) { if (error) { return console.error('upload failed:', error); } console.log('Upload successful! Server responded with:', body); }) ``` [back to top](#table-of-contents) --- ## HTTP Authentication ```js request.get('http://some.server.com/').auth('username', 'password', false); // or request.get('http://some.server.com/', { 'auth': { 'user': 'username', 'pass': 'password', 'sendImmediately': false } }); // or request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); // or request.get('http://some.server.com/', { 'auth': { 'bearer': 'bearerToken' } }); ``` If passed as an option, `auth` should be a hash containing values: - `user` || `username` - `pass` || `password` - `sendImmediately` (optional) - `bearer` (optional) The method form takes parameters `auth(username, password, sendImmediately, bearer)`. `sendImmediately` defaults to `true`, which causes a basic or bearer authentication header to be sent. If `sendImmediately` is `false`, then `request` will retry with a proper authentication header after receiving a `401` response from the server (which must contain a `WWW-Authenticate` header indicating the required authentication method). Note that you can also specify basic authentication using the URL itself, as detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the `user:password` before the host with an `@` sign: ```js var username = 'username', password = 'password', url = 'http://' + username + ':' + password + '@some.server.com'; request({url: url}, function (error, response, body) { // Do more stuff with 'body' here }); ``` Digest authentication is supported, but it only works with `sendImmediately` set to `false`; otherwise `request` will send basic authentication on the initial request, which will probably cause the request to fail. Bearer authentication is supported, and is activated when the `bearer` value is available. The value may be either a `String` or a `Function` returning a `String`. Using a function to supply the bearer token is particularly useful if used in conjunction with `defaults` to allow a single function to supply the last known token at the time of sending a request, or to compute one on the fly. [back to top](#table-of-contents) --- ## Custom HTTP Headers HTTP Headers, such as `User-Agent`, can be set in the `options` object. In the example below, we call the github API to find out the number of stars and forks for the request repository. This requires a custom `User-Agent` header as well as https. ```js var request = require('request'); var options = { url: 'https://api.github.com/repos/request/request', headers: { 'User-Agent': 'request' } }; function callback(error, response, body) { if (!error && response.statusCode == 200) { var info = JSON.parse(body); console.log(info.stargazers_count + " Stars"); console.log(info.forks_count + " Forks"); } } request(options, callback); ``` [back to top](#table-of-contents) --- ## OAuth Signing [OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The default signing algorithm is [HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2): ```js // OAuth1.0 - 3-legged server side flow (Twitter example) // step 1 var qs = require('querystring') , oauth = { callback: 'http://mysite.com/callback/' , consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET } , url = 'https://api.twitter.com/oauth/request_token' ; request.post({url:url, oauth:oauth}, function (e, r, body) { // Ideally, you would take the body in the response // and construct a URL that a user clicks on (like a sign in button). // The verifier is only available in the response after a user has // verified with twitter that they are authorizing your app. // step 2 var req_data = qs.parse(body) var uri = 'https://api.twitter.com/oauth/authenticate' + '?' + qs.stringify({oauth_token: req_data.oauth_token}) // redirect the user to the authorize uri // step 3 // after the user is redirected back to your server var auth_data = qs.parse(body) , oauth = { consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET , token: auth_data.oauth_token , token_secret: req_data.oauth_token_secret , verifier: auth_data.oauth_verifier } , url = 'https://api.twitter.com/oauth/access_token' ; request.post({url:url, oauth:oauth}, function (e, r, body) { // ready to make signed requests on behalf of the user var perm_data = qs.parse(body) , oauth = { consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET , token: perm_data.oauth_token , token_secret: perm_data.oauth_token_secret } , url = 'https://api.twitter.com/1.1/users/show.json' , qs = { screen_name: perm_data.screen_name , user_id: perm_data.user_id } ; request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) { console.log(user) }) }) }) ``` For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make the following changes to the OAuth options object: * Pass `signature_method : 'RSA-SHA1'` * Instead of `consumer_secret`, specify a `private_key` string in [PEM format](http://how2ssl.com/articles/working_with_pem_files/) For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make the following changes to the OAuth options object: * Pass `signature_method : 'PLAINTEXT'` To send OAuth parameters via query params or in a post body as described in The [Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param) section of the oauth1 spec: * Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth options object. * `transport_method` defaults to `'header'` To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either * Manually generate the body hash and pass it as a string `body_hash: '...'` * Automatically generate the body hash by passing `body_hash: true` [back to top](#table-of-contents) --- ## Proxies If you specify a `proxy` option, then the request (and any subsequent redirects) will be sent via a connection to the proxy server. If your endpoint is an `https` url, and you are using a proxy, then request will send a `CONNECT` request to the proxy server *first*, and then use the supplied connection to connect to the endpoint. That is, first it will make a request like: ``` HTTP/1.1 CONNECT endpoint-server.com:80 Host: proxy-server.com User-Agent: whatever user agent you specify ``` and then the proxy server make a TCP connection to `endpoint-server` on port `80`, and return a response that looks like: ``` HTTP/1.1 200 OK ``` At this point, the connection is left open, and the client is communicating directly with the `endpoint-server.com` machine. See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel) for more information. By default, when proxying `http` traffic, request will simply make a standard proxied `http` request. This is done by making the `url` section of the initial line of the request a fully qualified url to the endpoint. For example, it will make a single request that looks like: ``` HTTP/1.1 GET http://endpoint-server.com/some-url Host: proxy-server.com Other-Headers: all go here request body or whatever ``` Because a pure "http over http" tunnel offers no additional security or other features, it is generally simpler to go with a straightforward HTTP proxy in this case. However, if you would like to force a tunneling proxy, you may set the `tunnel` option to `true`. You can also make a standard proxied `http` request by explicitly setting `tunnel : false`, but **note that this will allow the proxy to see the traffic to/from the destination server**. If you are using a tunneling proxy, you may set the `proxyHeaderWhiteList` to share certain headers with the proxy. You can also set the `proxyHeaderExclusiveList` to share certain headers only with the proxy and not with destination host. By default, this set is: ``` accept accept-charset accept-encoding accept-language accept-ranges cache-control content-encoding content-language content-length content-location content-md5 content-range content-type connection date expect max-forwards pragma proxy-authorization referer te transfer-encoding user-agent via ``` Note that, when using a tunneling proxy, the `proxy-authorization` header and any headers from custom `proxyHeaderExclusiveList` are *never* sent to the endpoint server, but only to the proxy server. ### Controlling proxy behaviour using environment variables The following environment variables are respected by `request`: * `HTTP_PROXY` / `http_proxy` * `HTTPS_PROXY` / `https_proxy` * `NO_PROXY` / `no_proxy` When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request. `request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables. Here's some examples of valid `no_proxy` values: * `google.com` - don't proxy HTTP/HTTPS requests to Google. * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google. * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo! * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether. [back to top](#table-of-contents) --- ## UNIX Domain Sockets `request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme: ```js /* Pattern */ 'http://unix:SOCKET:PATH' /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path') ``` Note: The `SOCKET` path is assumed to be absolute to the root of the host file system. [back to top](#table-of-contents) --- ## TLS/SSL Protocol TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommended way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent). ```js var fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem') , request = require('request'); var options = { url: 'https://api.some-server.com/', cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile), passphrase: 'password', ca: fs.readFileSync(caFile) }; request.get(options); ``` ### Using `options.agentOptions` In the example below, we call an API that requires client side SSL certificate (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol: ```js var fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , request = require('request'); var options = { url: 'https://api.some-server.com/', agentOptions: { cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile), // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: // pfx: fs.readFileSync(pfxFilePath), passphrase: 'password', securityOptions: 'SSL_OP_NO_SSLv3' } }; request.get(options); ``` It is able to force using SSLv3 only by specifying `secureProtocol`: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { secureProtocol: 'SSLv3_method' } }); ``` It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs). This can be useful, for example, when using self-signed certificates. To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`. The certificate the domain presents must be signed by the root certificate specified: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { ca: fs.readFileSync('ca.cert.pem') } }); ``` [back to top](#table-of-contents) --- ## Support for HAR 1.2 The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`. A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching. ```js var request = require('request') request({ // will be ignored method: 'GET', uri: 'http://www.google.com', // HTTP Archive Request Object har: { url: 'http://www.mockbin.com/har', method: 'POST', headers: [ { name: 'content-type', value: 'application/x-www-form-urlencoded' } ], postData: { mimeType: 'application/x-www-form-urlencoded', params: [ { name: 'foo', value: 'bar' }, { name: 'hello', value: 'world' } ] } } }) // a POST request will be sent to http://www.mockbin.com // with body an application/x-www-form-urlencoded body: // foo=bar&hello=world ``` [back to top](#table-of-contents) --- ## request(options, callback) The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional. - `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()` - `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string. - `method` - http method (default: `"GET"`) - `headers` - http headers (default: `{}`) --- - `qs` - object containing querystring values to be appended to the `uri` - `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}` - `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat` - `useQuerystring` - if true, use `querystring` to stringify and parse querystrings, otherwise use `qs` (default: `false`). Set this option to `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the default `foo[0]=bar&foo[1]=baz`. --- - `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object. - `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above. - `formData` - data to pass for a `multipart/form-data` request. See [Forms](#forms) section above. - `multipart` - array of objects which contain their own headers and `body` attributes. Sends a `multipart/related` request. See [Forms](#forms) section above. - Alternatively you can pass in an object `{chunked: false, data: []}` where `chunked` is used to specify whether the request is sent in [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) In non-chunked requests, data items with body streams are not allowed. - `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request. - `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request. - `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON. - `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body. - `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body. --- - `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above. - `oauth` - options for OAuth HMAC-SHA1 signing. See documentation above. - `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example). - `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. If you are using SigV4, you can also include a `service` property that specifies the service name. **Note:** you need to `npm install aws4` first. - `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options. --- - `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise. - `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`) - `followOriginalHttpMethod` - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: `false`) - `maxRedirects` - the maximum number of redirects to follow (default: `10`) - `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). **Note:** if true, referer header set in the initial request is preserved during redirect chain. --- - `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.) - `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below. - `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section) --- - `agent` - `http(s).Agent` instance to use - `agentClass` - alternatively specify your agent's class name - `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions). - `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+ - `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified. - A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`). - Note that if you are sending multiple requests in a loop and creating multiple new `pool` objects, `maxSockets` will not work as intended. To work around this, either use [`request.defaults`](#requestdefaultsoptions) with your pool options or create the pool object with the `maxSockets` property outside of the loop. - `timeout` - integer containing the number of milliseconds to wait for a server to send response headers (and start the response body) before aborting the request. Note that if the underlying TCP connection cannot be established, the OS-wide TCP connection timeout will overrule the `timeout` option ([the default in Linux can be anywhere from 20-120 seconds][linux-timeout]). [linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout --- - `localAddress` - local interface to bind for network connections. - `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`) - `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option. - `tunnel` - controls the behavior of [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling) as follows: - `undefined` (default) - `true` if the destination is `https`, `false` otherwise - `true` - always tunnel to the destination by making a `CONNECT` request to the proxy - `false` - request the destination as a `GET` request. - `proxyHeaderWhiteList` - a whitelist of headers to send to a tunneling proxy. - `proxyHeaderExclusiveList` - a whitelist of headers to send exclusively to a tunneling proxy and not to destination. --- - `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object: - `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*). - `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*). - `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds). - `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain: - `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request. - `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved. - `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection. - `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server. - `end`: Relative timestamp when the last bytes of the response are received. - `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain: - `wait`: Duration of socket initialization (`timings.socket`) - `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`) - `tcp`: Duration of TCP connection (`timings.connect` - `timings.socket`) - `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`) - `download`: Duration of HTTP download (`timings.end` - `timings.response`) - `total`: Duration entire HTTP round-trip (`timings.end`) - `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-1.2) for details)* - `callback` - alternatively pass the request's callback in the options object The callback argument gets 3 arguments: 1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object) 2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object) 3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied) [back to top](#table-of-contents) --- ## Convenience methods There are also shorthand methods for different HTTP METHODs and some other conveniences. ### request.defaults(options) This method **returns a wrapper** around the normal request API that defaults to whatever options you pass to it. **Note:** `request.defaults()` **does not** modify the global request API; instead, it **returns a wrapper** that has your default settings applied to it. **Note:** You can call `.defaults()` on the wrapper that is returned from `request.defaults` to add/override defaults that were previously defaulted. For example: ```js //requests using baseRequest() will set the 'x-token' header var baseRequest = request.defaults({ headers: {'x-token': 'my-token'} }) //requests using specialRequest() will include the 'x-token' header set in //baseRequest and will also include the 'special' header var specialRequest = baseRequest.defaults({ headers: {special: 'special value'} }) ``` ### request.METHOD() These HTTP method convenience functions act just like `request()` but with a default method already set for you: - *request.get()*: Defaults to `method: "GET"`. - *request.post()*: Defaults to `method: "POST"`. - *request.put()*: Defaults to `method: "PUT"`. - *request.patch()*: Defaults to `method: "PATCH"`. - *request.del() / request.delete()*: Defaults to `method: "DELETE"`. - *request.head()*: Defaults to `method: "HEAD"`. - *request.options()*: Defaults to `method: "OPTIONS"`. ### request.cookie() Function that creates a new cookie. ```js request.cookie('key1=value1') ``` ### request.jar() Function that creates a new cookie jar. ```js request.jar() ``` [back to top](#table-of-contents) --- ## Debugging There are at least three ways to debug the operation of `request`: 1. Launch the node process like `NODE_DEBUG=request node script.js` (`lib,request,otherlib` works too). 2. Set `require('request').debug = true` at any time (this does the same thing as #1). 3. Use the [request-debug module](https://github.com/request/request-debug) to view request and response headers and bodies. [back to top](#table-of-contents) --- ## Timeouts Most requests to external servers should have a timeout attached, in case the server is not responding in a timely manner. Without a timeout, your code may have a socket open/consume resources for minutes or more. There are two main types of timeouts: **connection timeouts** and **read timeouts**. A connect timeout occurs if the timeout is hit while your client is attempting to establish a connection to a remote machine (corresponding to the [connect() call][connect] on the socket). A read timeout occurs any time the server is too slow to send back a part of the response. These two situations have widely different implications for what went wrong with the request, so it's useful to be able to distinguish them. You can detect timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you can detect whether the timeout was a connection timeout by checking if the `err.connect` property is set to `true`. ```js request.get('http://10.255.255.1', {timeout: 1500}, function(err) { console.log(err.code === 'ETIMEDOUT'); // Set to `true` if the timeout was a connection timeout, `false` or // `undefined` otherwise. console.log(err.connect === true); process.exit(0); }); ``` [connect]: http://linux.die.net/man/2/connect ## Examples: ```js var request = require('request') , rand = Math.floor(Math.random()*100000000).toString() ; request( { method: 'PUT' , uri: 'http://mikeal.iriscouch.com/testjs/' + rand , multipart: [ { 'content-type': 'application/json' , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) } , { body: 'I am an attachment' } ] } , function (error, response, body) { if(response.statusCode == 201){ console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) } else { console.log('error: '+ response.statusCode) console.log(body) } } ) ``` For backwards-compatibility, response compression is not supported by default. To accept gzip-compressed responses, set the `gzip` option to `true`. Note that the body data passed through `request` is automatically decompressed while the response object is unmodified and will contain compressed data if the server sent a compressed response. ```js var request = require('request') request( { method: 'GET' , uri: 'http://www.google.com' , gzip: true } , function (error, response, body) { // body is the decompressed response body console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) console.log('the decoded data is: ' + body) } ) .on('data', function(data) { // decompressed data as it is received console.log('decoded chunk: ' + data) }) .on('response', function(response) { // unmodified http.IncomingMessage object response.on('data', function(data) { // compressed data as it is received console.log('received ' + data.length + ' bytes of compressed data') }) }) ``` Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`). ```js var request = request.defaults({jar: true}) request('http://www.google.com', function () { request('http://images.google.com') }) ``` To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`) ```js var j = request.jar() var request = request.defaults({jar:j}) request('http://www.google.com', function () { request('http://images.google.com') }) ``` OR ```js var j = request.jar(); var cookie = request.cookie('key1=value1'); var url = 'http://www.google.com'; j.setCookie(cookie, url); request({url: url, jar: j}, function () { request('http://images.google.com') }) ``` To use a custom cookie store (such as a [`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore) which supports saving to and restoring from JSON files), pass it as a parameter to `request.jar()`: ```js var FileCookieStore = require('tough-cookie-filestore'); // NOTE - currently the 'cookies.json' file must already exist! var j = request.jar(new FileCookieStore('cookies.json')); request = request.defaults({ jar : j }) request('http://www.google.com', function() { request('http://images.google.com') }) ``` The cookie store must be a [`tough-cookie`](https://github.com/SalesforceEng/tough-cookie) store and it must support synchronous operations; see the [`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#cookiestore-api) for details. To inspect your cookie jar after a request: ```js var j = request.jar() request({url: 'http://www.google.com', jar: j}, function () { var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." var cookies = j.getCookies(url); // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] }) ``` [back to top](#table-of-contents) # debug [![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> A tiny JavaScript debugging utility modelled after Node.js core's debugging technique. Works in Node.js and web browsers. ## Installation ```bash $ npm install debug ``` ## Usage `debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. Example [_app.js_](./examples/node/app.js): ```js var debug = require('debug')('http') , http = require('http') , name = 'My App'; // fake app debug('booting %o', name); http.createServer(function(req, res){ debug(req.method + ' ' + req.url); res.end('hello\n'); }).listen(3000, function(){ debug('listening'); }); // fake worker of some kind require('./worker'); ``` Example [_worker.js_](./examples/node/worker.js): ```js var a = require('debug')('worker:a') , b = require('debug')('worker:b'); function work() { a('doing lots of uninteresting work'); setTimeout(work, Math.random() * 1000); } work(); function workb() { b('doing some work'); setTimeout(workb, Math.random() * 2000); } workb(); ``` The `DEBUG` environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: <img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png"> <img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png"> #### Windows command prompt notes ##### CMD On Windows the environment variable is set using the `set` command. ```cmd set DEBUG=*,-not_this ``` Example: ```cmd set DEBUG=* & node app.js ``` ##### PowerShell (VS Code default) PowerShell uses different syntax to set environment variables. ```cmd $env:DEBUG = "*,-not_this" ``` Example: ```cmd $env:DEBUG='app';node app.js ``` Then, run the program to be debugged as usual. npm script example: ```js "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", ``` ## Namespace Colors Every debug instance has a color generated for it based on its namespace name. This helps when visually parsing the debug output to identify which debug instance a debug line belongs to. #### Node.js In Node.js, colors are enabled when stderr is a TTY. You also _should_ install the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, otherwise debug will only use a small handful of basic colors. <img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png"> #### Web Browser Colors are also enabled on "Web Inspectors" that understand the `%c` formatting option. These are WebKit web inspectors, Firefox ([since version 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) and the Firebug plugin for Firefox (any version). <img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png"> ## Millisecond diff When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. <img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png"> When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: <img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png"> ## Conventions If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. ## Wildcards The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". ## Environment Variables When running through Node.js, you can set a few environment variables that will change the behavior of the debug logging: | Name | Purpose | |-----------|-------------------------------------------------| | `DEBUG` | Enables/disables specific debugging namespaces. | | `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | | `DEBUG_COLORS`| Whether or not to use colors in the debug output. | | `DEBUG_DEPTH` | Object inspection depth. | | `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | __Note:__ The environment variables beginning with `DEBUG_` end up being converted into an Options object that gets used with `%o`/`%O` formatters. See the Node.js documentation for [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) for the complete list. ## Formatters Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: | Formatter | Representation | |-----------|----------------| | `%O` | Pretty-print an Object on multiple lines. | | `%o` | Pretty-print an Object all on a single line. | | `%s` | String. | | `%d` | Number (both integer and float). | | `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | | `%%` | Single percent sign ('%'). This does not consume an argument. | ### Custom formatters You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: ```js const createDebug = require('debug') createDebug.formatters.h = (v) => { return v.toString('hex') } // …elsewhere const debug = createDebug('foo') debug('this is hex: %h', new Buffer('hello world')) // foo this is hex: 68656c6c6f20776f726c6421 +0ms ``` ## Browser Support You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), if you don't want to build it yourself. Debug's enable state is currently persisted by `localStorage`. Consider the situation shown below where you have `worker:a` and `worker:b`, and wish to debug both. You can enable this using `localStorage.debug`: ```js localStorage.debug = 'worker:*' ``` And then refresh the page. ```js a = debug('worker:a'); b = debug('worker:b'); setInterval(function(){ a('doing some work'); }, 1000); setInterval(function(){ b('doing some work'); }, 1200); ``` ## Output streams By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: Example [_stdout.js_](./examples/node/stdout.js): ```js var debug = require('debug'); var error = debug('app:error'); // by default stderr is used error('goes to stderr!'); var log = debug('app:log'); // set this namespace to log via console.log log.log = console.log.bind(console); // don't forget to bind to console! log('goes to stdout'); error('still goes to stderr!'); // set all output to go via console.info // overrides all per-namespace log settings debug.log = console.info.bind(console); error('now goes to stdout via console.info'); log('still goes to stdout, but via console.info now'); ``` ## Extend You can simply extend debugger ```js const log = require('debug')('auth'); //creates new debug instance with extended namespace const logSign = log.extend('sign'); const logLogin = log.extend('login'); log('hello'); // auth hello logSign('hello'); //auth:sign hello logLogin('hello'); //auth:login hello ``` ## Set dynamically You can also enable debug dynamically by calling the `enable()` method : ```js let debug = require('debug'); console.log(1, debug.enabled('test')); debug.enable('test'); console.log(2, debug.enabled('test')); debug.disable(); console.log(3, debug.enabled('test')); ``` print : ``` 1 false 2 true 3 false ``` Usage : `enable(namespaces)` `namespaces` can include modes separated by a colon and wildcards. Note that calling `enable()` completely overrides previously set DEBUG variable : ``` $ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' => false ``` ## Checking whether a debug target is enabled After you've created a debug instance, you can determine whether or not it is enabled by checking the `enabled` property: ```javascript const debug = require('debug')('http'); if (debug.enabled) { // do stuff... } ``` You can also manually toggle this property to force the debug instance to be enabled or disabled. ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne ## Backers Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] <a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> <a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> ## Sponsors Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] <a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> <a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> ## License (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk &lt;[email protected]&gt; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
esaminu_donation-boilerplate-template-js-qw98er
.github scripts runfe.sh workflows deploy-to-console.yml readme.yml tests.yml .gitpod.yml README.md contract README.md build.sh deploy.sh package-lock.json package.json src contract.ts model.ts utils.ts tsconfig.json integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
# Donation 💸 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/donation-js) [![](https://img.shields.io/badge/Contract-js-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![Build Status](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fnear-examples%2Fdonation-js%2Fbadge&style=flat&label=Tests)](https://actions-badge.atrox.dev/near-examples/donation-js/goto) Our Donation example enables to forward money to an account while keeping track of it. It is one of the simplest examples on making a contract receive and send money. ![](https://docs.near.org/assets/images/donation-7cf65e5e131274fd1ae9aa34bc465bb8.png) # What This Example Shows 1. How to receive and transfer $NEAR on a contract. 2. How to divide a project into multiple modules. 3. How to handle the storage costs. 4. How to handle transaction results. 5. How to use a `Map`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-js). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # Donation Contract The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. ```ts @call donate() { // Get who is calling the method and how much $NEAR they attached let donor = near.predecessorAccountId(); let donationAmount: bigint = near.attachedDeposit() as bigint; let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) let toTransfer = donationAmount; // This is the user's first donation, lets register it, which increases storage if(donatedSoFar == BigInt(0)) { assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); // Subtract the storage cost to the amount to transfer toTransfer -= STORAGE_COST } // Persist in storage the amount donated so far donatedSoFar += donationAmount this.donations.set(donor, donatedSoFar.toString()) // Send the money to the beneficiary const promise = near.promiseBatchCreate(this.beneficiary) near.promiseBatchActionTransfer(promise, toTransfer) // Return the total amount donated so far return donatedSoFar.toString() } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` The contract will be automatically initialized with a default `beneficiary`. To initialize the contract yourself do: ```bash # Use near-cli to initialize contract (optional) near call <dev-account> init '{"beneficiary":"<account>"}' --accountId <dev-account> ``` <br /> ## 2. Get Beneficiary `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> beneficiary ``` <br /> ## 3. Get Number of Donations `donate` forwards any attached money to the `beneficiary` while keeping track of it. `donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> donate --amount 1 --accountId <account> ``` **Tip:** If you would like to `donate` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
PrimeLabCore_web3-diagram
Cargo.toml README.md | cargo-diagram Cargo.toml src main.rs svg.rs do-build.sh do-docs.sh do-run.sh example Cargo.toml example.sh src events.rs lib.rs main.rs some_fancy_impl.rs some_fancy_impl helpers.rs trait_impl.rs mermaid-markdown-api Cargo.toml src lib.rs md_api.rs objects connection.rs mod.rs node.rs scanner_pipeline.rs syntax flow_chart.rs mod.rs scanner-syn Cargo.toml src contract_descriptor.rs core_impl code_generator attr_sig_info.rs impl_item_method_info.rs item_impl_info.rs item_struct_info.rs item_trait_info.rs mod.rs trait_item_method_info.rs info_extractor arg_info.rs attr_sig_info.rs impl_item_method_info.rs init_attr.rs item_fn_info.rs item_impl_info.rs item_trait_info.rs mod.rs serializer_attr.rs statements_parser.rs trait_item_method_info.rs metadata metadata_generator.rs metadata_visitor.rs mod.rs mod.rs lib.rs
# Web3 Diagram ## **This is a cargo utility that allows developers to generate visualizations depicting data flows within their NEAR Rust smart contracts.** <br> ### Which problem does it solve? **Provides the ability to generate representations of methods to allow for anyone to quickly understand how the contract works.** <br> ### Who can use this? **Smart contract developers use it to generate the images, but the images can help anyone trying to understand what’s going on.** <br> ## Key Features | Feature | Description | | ----------- | ----------- | | View Functions | Near smart contract view only functions | | Mutation | Near smart contract mutable functions | | Process | Helper or utility functions, also functions out of smart contract scope | | Events | Functions that falls into near event [standard]([https://link](https://github.com/near/near-sdk-rs/blob/master/near-contract-standards/src/event.rs)) | | View Trait Impl | View only functions but trait implamentation | | Mutation Trait Impl | Mutable functions but trait implamentation | | Payable | Functions that except Near | | Initializers | Smart contract initializer functions | <br> # Installation ## Install Rust ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` <br> ## Install cli with [brew](https://brew.sh/) ```bash brew install mermaid-cli ``` <br> ## Install web3d diagram utility ```bash cargo install web3d ``` <br> ## Install [node](https://gist.github.com/tomysmile/da3cb8194ec8f0e4df86#install-node) ```bash brew install node ``` <br> ## Web3 Utility Usage ### 1) Clone raffle smart contract from near examples ```bash git clone [email protected]:near-examples/rust-ft-raffle.git ``` <br> ### 2) Go to the root directory ```bash cd rust-ft-raffle ``` ### 3) Run utility againt cloned smart contract and open in web browser ```bash web3d -O --input raffle.md ``` <br> ## Options | Key/Command | Description | | ----------- | ----------- | | -b, --backgroundColor | Background color. Example: transparent, red, '#F0F0F0'. Optional. Default: white | | -h, --help | Print help information | | -H, --height | Height of the page. Optional. Default: 600 | | -i, --input | Markdown file name | | -o, --output | Output file name. It should be either md, svg, png or pdf. Optional. Default:'./res/input_file_name.svg' | | -O, --openb | Should open output file in browser | | -q, --quiet | Suppress log output | | -w, --width | Width of the page. Optional. Default: 800 |
LNThanhNhan_homework_near_app_day1
.gitpod.yml README.md contract Cargo.toml README.md neardev dev-account.env src lib.rs target .rustc_info.json frontend App.js dist index.521b6793.js index.5bcde184.js index.cc397963.js index.d6a4dc8d.js index.html index.html index.js near-api.js near-config.js package-lock.json package.json ui-components.js integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
Hello NEAR! ================================= A [smart contract] written in [Rust] for an app initialized with [create-near-app] Quick Start =========== Before you compile this code, you will need to install Rust with [correct target] Exploring The Code ================== 1. The main smart contract code lives in `src/lib.rs`. 2. There are two functions to the smart contract: `get_greeting` and `set_greeting`. 3. Tests: You can run smart contract tests with the `cargo test`. [smart contract]: https://docs.near.org/develop/welcome [Rust]: https://www.rust-lang.org/ [create-near-app]: https://github.com/near/create-near-app [correct target]: https://docs.near.org/develop/prerequisites#rust-and-wasm [cargo]: https://doc.rust-lang.org/book/ch01-03-hello-cargo.html near-blank-project ================== This app was initialized with [create-near-app] Quick Start =========== If you haven't installed dependencies during setup: npm run deps-install Build and deploy your contract to TestNet with a temporary dev account: npm run deploy Test your contract: npm test If you have a frontend, run `npm start`. This will run a dev server. Exploring The Code ================== 1. The smart-contract code lives in the `/contract` folder. See the README there for more info. In blockchain apps the smart contract is the "backend" of your app. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/index.js`, this is your entrypoint to learn how the frontend connects to the NEAR blockchain. 3. Test your contract: `npm test`, this will run the tests in `integration-tests` directory. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `npm run deploy`, your smart contract gets deployed to the live NEAR TestNet with a temporary dev account. When you're ready to make it permanent, here's how: Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `npm install`, but for best ergonomics you may want to install it globally: npm install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: deploy the contract --------------------------- Use the CLI to deploy the contract to TestNet with your account ID. Replace `PATH_TO_WASM_FILE` with the `wasm` that was generated in `contract` build directory. near deploy --accountId near-blank-project.YOUR-NAME.testnet --wasmFile PATH_TO_WASM_FILE Step 3: set contract name in your frontend code ----------------------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
hkuspace-pu_COMP-3000-Ngan-Tsz-Chung-FYP
.gitpod.yml README.md blockchain_mobile_application_demo Blockchain .idea compiler.xml gradle.xml misc.xml vcs.xml app release output-metadata.json src main AndroidManifest.xml res drawable-v24 ic_launcher_foreground.xml drawable ic_launcher_background.xml layout activity_edit.xml activity_main.xml list_item_block.xml mipmap-anydpi-v26 ic_launcher.xml ic_launcher_round.xml values-night themes.xml values colors.xml strings.xml themes.xml xml backup_rules.xml data_extraction_rules.xml gradlew.bat contract README.md babel.config.json build.sh build builder.c code.h hello_near.js methods.h deploy.sh neardev dev-account.env package-lock.json package.json src contract.ts model.ts tsconfig.json frontend App.js Components AddCandidate.js AddVoting.js Home.js Login.js VotingPage.js assets global.css logo-black.svg logo-white.svg dist frontend.3464ddca.js index.ab0485ab.css index.bc0daea6.css index.html logo-black.4514ed42.svg logo-white.a7716062.svg index.html index.js near-interface.js near-wallet.js package-lock.json package.json start.sh integration-tests package-lock.json package.json src main.ava.ts package-lock.json package.json
Blockchain in e-voting ====================== This app was initialized with [create-near-app] The aim of this project is for education only. It is developed for knowing more about how the blockchain enhance the security in e-voting. Quick Start =========== Build and deploy your contract to TestNet with a temporary dev account: yarn deploy Run the application: yarn start If you have a frontend, run `npm start`. This will run a dev server. Contact ======= E-mail:[email protected] Modify Block in Android Demo ============================ use /blockchain_mobile_application_demo/blockchain_mobile_application_demo.apk Reference ========= [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/concepts/basics/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```ts @NearBindgen({}) class HelloNear { greeting: string = "Hello"; @view // This method is read-only and can be called for free get_greeting(): string { return this.greeting; } @call // This method changes the state, for which it cost gas set_greeting({ greeting }: { greeting: string }): void { // Record a log permanently to the blockchain! near.log(`Saving greeting ${greeting}`); this.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `call` method. `Call` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"greeting":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
jerryno6_starter--AssemblyScript
README.md as-pect.config.js asconfig.json package-lock.json package.json scripts 1.init.sh 2.run.sh README.md src as-pect.d.ts as_types.d.ts sample README.md __tests__ README.md index.unit.spec.ts asconfig.json assembly index.ts tsconfig.json utils.ts
![Near, Inc. logo](https://near.org/wp-content/themes/near-19/assets/img/logo.svg?t=1553011311) ## Design ### Interface ```ts export function showYouKnow(): void; ``` - "View" function (ie. a function that does NOT alter contract state) - Takes no parameters - Returns nothing ```ts export function showYouKnow2(): bool; ``` - "View" function (ie. a function that does NOT alter contract state) - Takes no parameters - Returns true ```ts export function sayHello(): string; ``` - "View" function - Takes no parameters - Returns a string ```ts export function sayMyName(): string; ``` - "Change" function (although it does NOT alter state, it DOES read from `context`, [see docs for details](https://docs.near.org/docs/develop/contracts/as/intro)) - Takes no parameters - Returns a string ```ts export function saveMyName(): void; ``` - "Change" function (ie. a function that alters contract state) - Takes no parameters - Saves the sender account name to contract state - Returns nothing ```ts export function saveMyMessage(message: string): bool; ``` - "Change" function - Takes a single parameter message of type string - Saves the sender account name and message to contract state - Returns nothing ```ts export function getAllMessages(): Array<string>; ``` - "Change" function - Takes no parameters - Reads all recorded messages from contract state (this can become expensive!) - Returns an array of messages if any are found, otherwise empty array ## Unit tests Unit tests can be run from the top level folder using the following command: ``` yarn test:unit ``` ### Tests for Contract in `index.unit.spec.ts` ``` [Describe]: Greeting [Success]: ✔ should respond to showYouKnow() [Success]: ✔ should respond to showYouKnow2() [Success]: ✔ should respond to sayHello() [Success]: ✔ should respond to sayMyName() [Success]: ✔ should respond to saveMyName() [Success]: ✔ should respond to saveMyMessage() [Success]: ✔ should respond to getAllMessages() [File]: src/sample/__tests__/index.unit.spec.ts [Groups]: 2 pass, 2 total [Result]: ✔ PASS [Snapshot]: 0 total, 0 added, 0 removed, 0 different [Summary]: 7 pass, 0 fail, 7 total [Time]: 19.164ms ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Result]: ✔ PASS [Files]: 1 total [Groups]: 2 count, 2 pass [Tests]: 7 pass, 0 fail, 7 total [Time]: 8217.768ms ✨ Done in 8.86s. ``` # Sample This repository includes a complete project structure for AssemblyScript contracts targeting the NEAR platform. Watch this video where Willem Wyndham walks us through refactoring a simple example of a NEAR smart contract written in AssemblyScript https://youtu.be/QP7aveSqRPo ``` There are 2 "styles" of implementing AssemblyScript NEAR contracts: - the contract interface can either be a collection of exported functions - or the contract interface can be the methods of a an exported class We call the second style "Singleton" because there is only one instance of the class which is serialized to the blockchain storage. Rust contracts written for NEAR do this by default with the contract struct. 0:00 noise (to cut) 0:10 Welcome 0:59 Create project starting with "npm init" 2:20 Customize the project for AssemblyScript development 9:25 Import the Counter example and get unit tests passing 18:30 Adapt the Counter example to a Singleton style contract 21:49 Refactoring unit tests to access the new methods 24:45 Review and summary ``` The example here is very basic. It's a simple contract demonstrating the following concepts: - a single contract - the difference between `view` vs. `change` methods - basic contract storage The goal of this repository is to make it as easy as possible to get started writing unit and simulation tests for AssemblyScript contracts built to work with NEAR Protocol. ## Usage ### Getting started 1. clone this repo to a local folder 2. run `yarn` 3. run `yarn test` ### Top-level `yarn` commands - run `yarn test` to run all tests - (!) be sure to run `yarn build:release` at least once before: - run `yarn test:unit` to run only unit tests - run `yarn test:simulate` to run only simulation tests - run `yarn build` to quickly verify build status - run `yarn clean` to clean up build folder ### Other documentation - Sample contract and test documentation - see `/src/sample/README` for contract interface - see `/src/sample/__tests__/README` for Sample unit testing details - Sample contract simulation tests - see `/simulation/README` for simulation testing ## The file system Please note that boilerplate project configuration files have been ommitted from the following lists for simplicity. ### Contracts and Unit Tests ```txt src ├── sample <-- sample contract │   ├── README.md │   ├── __tests__ │   │   ├── README.md │   │   └── index.unit.spec.ts │   └── assembly │   └── index.ts └── utils.ts <-- shared contract code ``` ### Helper Scripts ```txt scripts ├── 1.init.sh ├── 2.run.sh └── README.md <-- instructions ``` ## Setting up your terminal The scripts in this folder support a simple demonstration of the contract. It uses the following setup: ```txt ┌───────────────────────────────────────┬───────────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ A │ B │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └───────────────────────────────────────┴───────────────────────────────────────┘ ``` ### Terminal **A** *This window is used to compile, deploy and control the contract* - Environment ```sh export CONTRACT= # depends on deployment export OWNER= # any account you control # for example # export CONTRACT=dev-1615190770786-2702449 # export OWNER=sherif.testnet ``` - Commands ```sh 1.init.sh # cleanup, compile and deploy contract 2.run.sh # call methods on the deployed contract ``` ### Terminal **B** *This window is used to render the contract account storage* - Environment ```sh export CONTRACT= # depends on deployment # for example # export CONTRACT=dev-1615190770786-2702449 ``` - Commands ```sh # monitor contract storage using near-account-utils # https://github.com/near-examples/near-account-utils watch -d -n 1 yarn storage $CONTRACT ``` --- ## OS Support ### Linux - The `watch` command is supported natively on Linux - To learn more about any of these shell commands take a look at [explainshell.com](https://explainshell.com) ### MacOS - Consider `brew info visionmedia-watch` (or `brew install watch`) ### Windows - Consider this article: [What is the Windows analog of the Linux watch command?](https://superuser.com/questions/191063/what-is-the-windows-analog-of-the-linux-watch-command#191068)
pmespresso_direct-revelation-dao
.gitpod.yml README.md contract Cargo.toml README.md build.sh deploy.sh src lib.rs policy.rs proposals.rs types.rs upgrade.rs views.rs target .rustc_info.json debug .fingerprint Inflector-778f054d6abc56ef lib-inflector.json ahash-97381fed487b9101 build-script-build-script-build.json ahash-c57412b343faddf3 lib-ahash.json ahash-cea78debba070bb8 run-build-script-build-script-build.json arrayref-c2749b0c05da3169 lib-arrayref.json arrayvec-ad64c20a53d6a7dd lib-arrayvec.json arrayvec-f2353b6724dd673e lib-arrayvec.json autocfg-603935bfeec52c52 lib-autocfg.json base64-72448b6d20c8b2db lib-base64.json base64-9acf3f843c276def lib-base64.json bitvec-52ce3e9e525b9fa7 lib-bitvec.json blake2-7f550b20af518811 lib-blake2.json block-buffer-143483d01c03f16a lib-block-buffer.json block-buffer-959598a7dbffc5c3 lib-block-buffer.json borsh-6d25269dafa3e304 lib-borsh.json borsh-derive-48024229487364c2 lib-borsh-derive.json borsh-derive-internal-a6090d53bed91ad2 lib-borsh-derive-internal.json borsh-schema-derive-internal-5a35dd033514d089 lib-borsh-schema-derive-internal.json bs58-25946aaa6185f382 lib-bs58.json byte-slice-cast-f986daf71dcc9c7e lib-byte-slice-cast.json byteorder-58e0741495b2f4e0 lib-byteorder.json bytesize-bd7e310cfd6bef2f lib-bytesize.json c2-chacha-47647f9d9a808552 lib-c2-chacha.json cc-c7439941d1214f63 lib-cc.json cfg-if-1e19dc40092c02c1 lib-cfg-if.json cfg-if-98bf6fd543f244a9 lib-cfg-if.json cfg-if-ce7b2a5af0d1979b lib-cfg-if.json chrono-0a4626ba2e05c9c4 lib-chrono.json cipher-7a52e7b78743420d lib-cipher.json convert_case-09d7f86de1c6b100 lib-convert_case.json core-foundation-sys-81d3d340ee22c797 run-build-script-build-script-build.json core-foundation-sys-86af3e8c12498eed build-script-build-script-build.json core-foundation-sys-fbe11bac17984266 lib-core-foundation-sys.json cpufeatures-f87f7f7e08b42bfc lib-cpufeatures.json crunchy-58688618432c3b24 build-script-build-script-build.json crunchy-c7da2c4fc23126b6 lib-crunchy.json crunchy-d84bc32a58590570 run-build-script-build-script-build.json crypto-common-998288ed477560dc lib-crypto-common.json crypto-mac-e8fd6125995bb93d lib-crypto-mac.json curve25519-dalek-30cff2202df8376c lib-curve25519-dalek.json derive_more-308fe686a593152e lib-derive_more.json digest-2f48c0baaeee5f9d lib-digest.json digest-dccbde44b655e007 lib-digest.json dyn-clone-b85f96a2f15d0e45 lib-dyn-clone.json easy-ext-60c0543fd7822531 lib-easy-ext.json ed25519-4bfb0d5a3c9b45b5 lib-ed25519.json ed25519-dalek-82592fa1e6e83648 lib-ed25519-dalek.json fixed-hash-934e1e2eafa88906 lib-fixed-hash.json funty-7a3fc6272b6b74e2 lib-funty.json generic-array-4b27dc6799ec4827 lib-generic_array.json generic-array-c554355b916315f2 build-script-build-script-build.json generic-array-cae325c7a42e1dc3 run-build-script-build-script-build.json getrandom-073bdd985a7a5468 lib-getrandom.json getrandom-25e209bd50587ce7 build-script-build-script-build.json getrandom-637b64fce0191e7e run-build-script-build-script-build.json getrandom-c32e8a6e1239550e lib-getrandom.json hashbrown-e76e9f9415a8a7be lib-hashbrown.json heck-4deb7a55f53763c1 lib-heck.json hello_near-14621de2fbfad35e lib-hello_near.json hello_near-2282861635613184 test-lib-hello_near.json hex-8878516771e3e191 lib-hex.json iana-time-zone-8a70ea7544d6bb91 lib-iana-time-zone.json impl-codec-afe663f1b8817a3a lib-impl-codec.json impl-trait-for-tuples-18a5762c4f3063a9 lib-impl-trait-for-tuples.json itoa-16eebe184da30835 lib-itoa.json keccak-b934e2bc93618a53 lib-keccak.json lazy_static-bf9799b5891adefc lib-lazy_static.json libc-1d0ec69be4cbcbe9 lib-libc.json libc-d4f8121ca238aabf build-script-build-script-build.json libc-dc34507ac2071d40 run-build-script-build-script-build.json memory_units-b122093dc6ed16e8 lib-memory_units.json near-abi-1b3897b3da83e6ff lib-near-abi.json near-account-id-0d258b105ed0515a lib-near-account-id.json near-crypto-c9148acc87d45100 lib-near-crypto.json near-primitives-3514454db22f8786 lib-near-primitives.json near-primitives-core-338625fd8cddf115 lib-near-primitives-core.json near-rpc-error-core-eb8c5c5be52d84d9 lib-near-rpc-error-core.json near-rpc-error-macro-edf2fd37f4baf94f lib-near-rpc-error-macro.json near-sdk-c4c69f0d4e76fe54 lib-near-sdk.json near-sdk-macros-2101e0567ccdd352 lib-near-sdk-macros.json near-sys-6fd02d67ed55bc9d lib-near-sys.json near-vm-errors-9bf35425988ffd82 lib-near-vm-errors.json near-vm-logic-658ba1c053a028b3 lib-near-vm-logic.json num-bigint-09a6a7fdbd6eb467 build-script-build-script-build.json num-bigint-1de3111c8367b596 run-build-script-build-script-build.json num-bigint-b8f6faa77e7799e1 lib-num-bigint.json num-integer-19108b734329cafd lib-num-integer.json num-integer-5f89f2cc598f1467 run-build-script-build-script-build.json num-integer-66d910e6ef60b165 build-script-build-script-build.json num-rational-07aceab1f25c4e07 lib-num-rational.json num-rational-3d4b485a6ae20660 run-build-script-build-script-build.json num-rational-3e3841f4894285ac build-script-build-script-build.json num-traits-8c7a289c167a9dce lib-num-traits.json num-traits-8edef72557ccac4e build-script-build-script-build.json num-traits-d5fb21b2d5452921 run-build-script-build-script-build.json once_cell-d6f31adfe1e701fe lib-once_cell.json once_cell-fa8bfab0025e477a lib-once_cell.json opaque-debug-7ebb550517ff91ea lib-opaque-debug.json parity-scale-codec-derive-976d54a104e6994c lib-parity-scale-codec-derive.json parity-scale-codec-e32783529bc20597 lib-parity-scale-codec.json parity-secp256k1-59d7d96b506f0859 lib-secp256k1.json parity-secp256k1-9b956ad274b2976e build-script-build-script-build.json parity-secp256k1-c030059626340fe0 run-build-script-build-script-build.json ppv-lite86-b71edf07bc734810 lib-ppv-lite86.json primitive-types-59b1b0bb01c1af53 lib-primitive-types.json proc-macro-crate-0ad31bebbfefe66a lib-proc-macro-crate.json proc-macro-crate-cfeda56bafd79ad5 lib-proc-macro-crate.json proc-macro2-5d965214f339e910 build-script-build-script-build.json proc-macro2-ad36a0976c50f0f5 lib-proc-macro2.json proc-macro2-b5f7177d07345b5e run-build-script-build-script-build.json quote-0a04b0416d7ffd63 build-script-build-script-build.json quote-2a0547c1f15979db run-build-script-build-script-build.json quote-6354d47900e1eb90 lib-quote.json radium-4f34426b47779eb7 build-script-build-script-build.json radium-78485fe6efeeae01 run-build-script-build-script-build.json radium-c06641a70d94f57c lib-radium.json rand-5c33b4bfbcbc8e84 lib-rand.json rand-706186fe1551a8ed lib-rand.json rand_chacha-a332893124d96540 lib-rand_chacha.json rand_chacha-c237a095f8f915e2 lib-rand_chacha.json rand_core-277802542fd7959b lib-rand_core.json rand_core-9dd14dee4b25ba7a lib-rand_core.json reed-solomon-erasure-2632256ae57490bd build-script-build-script-build.json reed-solomon-erasure-815ef5943d0f3e23 run-build-script-build-script-build.json reed-solomon-erasure-bad2cfb572e12cf9 lib-reed-solomon-erasure.json ripemd-85d1ca04beef7421 lib-ripemd.json rustc-hex-5e1dcbae917ca574 lib-rustc-hex.json rustversion-1825e1f0319179aa build-script-build-script-build.json rustversion-cee4587625d26ed5 lib-rustversion.json rustversion-d3d637a542928929 run-build-script-build-script-build.json ryu-c46e643b6b8990ce lib-ryu.json schemars-505506f4bf5ca079 build-script-build-script-build.json schemars-6894dd9f83054d5d run-build-script-build-script-build.json schemars-acc279d25499e422 lib-schemars.json schemars_derive-49ba8412e833b890 lib-schemars_derive.json semver-0b5b89e3de6dcf73 run-build-script-build-script-build.json semver-36e5333ba15442ba build-script-build-script-build.json semver-37282025944e8a60 lib-semver.json serde-1c89e3fa21afcefc run-build-script-build-script-build.json serde-23d09aac9a71469f build-script-build-script-build.json serde-592c976c2a66d7a6 lib-serde.json serde-964c7c0615494a1e lib-serde.json serde-b892578667144dee build-script-build-script-build.json serde-d71236efa37d5729 run-build-script-build-script-build.json serde_derive-055e6a7216fb18c4 run-build-script-build-script-build.json serde_derive-a72af2b7f18b03fc lib-serde_derive.json serde_derive-a9cac91edbfb43e5 build-script-build-script-build.json serde_derive_internals-9fed12674f3cbda1 lib-serde_derive_internals.json serde_json-67d40bc1be81cba6 lib-serde_json.json serde_json-c40e04aed17ea399 build-script-build-script-build.json serde_json-fec65c63fa552c77 run-build-script-build-script-build.json sha2-6f8eaed1c6b47e2f lib-sha2.json sha2-9de135348cf72eaf lib-sha2.json sha3-f4289e87a28fd486 lib-sha3.json signature-35975193377f61d8 lib-signature.json smallvec-8a9c3a4bcc365e7f lib-smallvec.json smart-default-347bed0cacdc6741 lib-smart-default.json spin-c388a5cf3efb6f78 lib-spin.json static_assertions-a5886db32b23b109 lib-static_assertions.json strum-d11c6b0a49ef3f62 lib-strum.json strum_macros-a97aaf46e859c24b lib-strum_macros.json subtle-dfb3310afc0b4c79 lib-subtle.json syn-195fd244a9390eaa build-script-build-script-build.json syn-3405a66301da58ac run-build-script-build-script-build.json syn-cd982c71f68f02bf lib-syn.json synstructure-7b0b7637e3d36810 lib-synstructure.json tap-f567923be308720b lib-tap.json thiserror-180abf23bcc618cd lib-thiserror.json thiserror-3d5513590ab6b2d8 build-script-build-script-build.json thiserror-5c317fd37c544154 lib-thiserror.json thiserror-b1e0f8ef357299bc run-build-script-build-script-build.json thiserror-impl-779c5e75fbdd72ff lib-thiserror-impl.json time-76a69d532bdd3afd lib-time.json toml-6ea16569361eb385 lib-toml.json typenum-4cef58ffb5ad42b1 build-script-build-script-main.json typenum-67e3bdec21c060c5 lib-typenum.json typenum-cf5ca8ae7bb3b4a3 run-build-script-build-script-main.json uint-ccd38828ac7adb2a lib-uint.json unicode-ident-e98523f98e43fafa lib-unicode-ident.json unicode-xid-0a4addf918b88e35 lib-unicode-xid.json version_check-7146a9efc0d7c0c3 lib-version_check.json wee_alloc-0cd89fd0f4058368 lib-wee_alloc.json wee_alloc-12b0fddb06db764f build-script-build-script-build.json wee_alloc-d5fb49cf58e15905 run-build-script-build-script-build.json wyz-971db417cd47706b lib-wyz.json zeroize-a9c29246508de85a lib-zeroize.json zeroize_derive-feed9de0acc6e41c lib-zeroize_derive.json zeropool-bn-c67ef5e6b9c37ad6 lib-zeropool-bn.json build crunchy-d84bc32a58590570 out lib.rs num-bigint-1de3111c8367b596 out radix_bases.rs parity-secp256k1-c030059626340fe0 out flag_check.c reed-solomon-erasure-815ef5943d0f3e23 out table.rs thiserror-b1e0f8ef357299bc out probe.rs typenum-cf5ca8ae7bb3b4a3 out consts.rs op.rs tests.rs wee_alloc-d5fb49cf58e15905 out wee_alloc_static_array_backend_size_bytes.txt frontend App.js assets global.css logo-black.svg logo-white.svg index.html index.js near-wallet.js package-lock.json package.json start.sh ui-components.js integration-tests Cargo.toml src tests.rs target .rustc_info.json debug .fingerprint addr2line-1d40a5daf4d83f4f lib-addr2line.json addr2line-d3e2432d94afef6e lib-addr2line.json adler-8023c3a07574e166 lib-adler.json adler-b005390db7faad83 lib-adler.json ahash-97381fed487b9101 build-script-build-script-build.json ahash-c57412b343faddf3 lib-ahash.json ahash-cea78debba070bb8 run-build-script-build-script-build.json aho-corasick-3bb07aad6139f631 lib-aho_corasick.json aho-corasick-e10a12c3167f7878 lib-aho_corasick.json anyhow-211e6cf0a8e19d58 build-script-build-script-build.json anyhow-3c87c1b6999c5c72 run-build-script-build-script-build.json anyhow-a450da6071ee3ec7 lib-anyhow.json anyhow-f6a00daca8206170 lib-anyhow.json arrayref-c2749b0c05da3169 lib-arrayref.json arrayvec-ab30ff79c76626a5 lib-arrayvec.json arrayvec-b446a68f69eea0b7 lib-arrayvec.json async-io-16f72e482d06b83a build-script-build-script-build.json async-io-496977434cebb50b lib-async-io.json async-io-e32eae7c1508e2fc lib-async-io.json async-io-e803533a9995603e run-build-script-build-script-build.json async-lock-a0f2a938aa98ad26 lib-async-lock.json async-lock-de42b04153453403 lib-async-lock.json async-process-32e51fe65b4736e3 run-build-script-build-script-build.json async-process-b7df39fadbe65ab6 lib-async-process.json async-process-c9e464a8eb14c636 lib-async-process.json async-process-cff66f6bb2d59603 build-script-build-script-build.json async-trait-40f79c28b92e4336 build-script-build-script-build.json async-trait-9a424658c5ef6398 lib-async-trait.json async-trait-b54cc20408945171 run-build-script-build-script-build.json autocfg-603935bfeec52c52 lib-autocfg.json backtrace-1869f8567120d30b lib-backtrace.json backtrace-1b68066256eebeec lib-backtrace.json backtrace-b149c426a552a16e run-build-script-build-script-build.json backtrace-f9998c1eef354d55 build-script-build-script-build.json base64-9acf3f843c276def lib-base64.json binary-install-1f26179719e70684 lib-binary-install.json binary-install-e1397af302350406 lib-binary-install.json bitflags-146d8529844fba7c lib-bitflags.json blake2-7f550b20af518811 lib-blake2.json block-buffer-143483d01c03f16a lib-block-buffer.json block-buffer-959598a7dbffc5c3 lib-block-buffer.json borsh-4b129f50f0e9dbc7 lib-borsh.json borsh-derive-16029b1c9dd8f2b3 lib-borsh-derive.json borsh-derive-internal-c366d4593689de53 lib-borsh-derive-internal.json borsh-schema-derive-internal-971fbef5cae3d747 lib-borsh-schema-derive-internal.json bs58-25946aaa6185f382 lib-bs58.json byteorder-0c7630aa2292ef46 lib-byteorder.json byteorder-58e0741495b2f4e0 lib-byteorder.json bytes-8fbed151a5bc131b lib-bytes.json bytesize-bd7e310cfd6bef2f lib-bytesize.json bzip2-71d01f6a7bc8b6f2 lib-bzip2.json bzip2-9277ebab26593b79 lib-bzip2.json bzip2-sys-32548bc4dd07232b run-build-script-build-script-build.json bzip2-sys-5512c62e0952e6f3 build-script-build-script-build.json bzip2-sys-69be3fb14f8111cd lib-bzip2_sys.json bzip2-sys-d9a7c3195c56ef8e lib-bzip2_sys.json c2-chacha-47647f9d9a808552 lib-c2-chacha.json cache-padded-34a9bb42b594fc52 lib-cache-padded.json cache-padded-a65a57adf758bd5e lib-cache-padded.json cc-c7439941d1214f63 lib-cc.json cfg-if-1e19dc40092c02c1 lib-cfg-if.json cfg-if-422f2268079734ae lib-cfg-if.json chrono-0496a2945dc9ae8e lib-chrono.json chrono-a2490d271d582b8d lib-chrono.json cipher-7a52e7b78743420d lib-cipher.json concurrent-queue-0298e3f8f1102ab5 lib-concurrent-queue.json concurrent-queue-77a65cca24df3caa lib-concurrent-queue.json convert_case-09d7f86de1c6b100 lib-convert_case.json core-foundation-da15aaf4403cc070 lib-core-foundation.json core-foundation-sys-81d3d340ee22c797 run-build-script-build-script-build.json core-foundation-sys-86af3e8c12498eed build-script-build-script-build.json core-foundation-sys-d3acedec7010412e lib-core-foundation-sys.json core-foundation-sys-fbe11bac17984266 lib-core-foundation-sys.json cpufeatures-f87f7f7e08b42bfc lib-cpufeatures.json crc32fast-12828e40be895ae5 build-script-build-script-build.json crc32fast-72ca258e6fa2f199 run-build-script-build-script-build.json crc32fast-7702dd4e003926c9 lib-crc32fast.json crc32fast-b56a064a4cdf68e0 lib-crc32fast.json crunchy-3483cb533ba72633 build-script-build-script-build.json crunchy-b4f79ba7cf6d353b lib-crunchy.json crunchy-e1a1a09b79160852 run-build-script-build-script-build.json crypto-common-998288ed477560dc lib-crypto-common.json crypto-mac-e8fd6125995bb93d lib-crypto-mac.json curl-147425d4c064c44b lib-curl.json curl-50341a190276ea84 lib-curl.json curl-673b6b3a5f436fb4 run-build-script-build-script-build.json curl-dc2f5f982e662b3f build-script-build-script-build.json curl-sys-27da5843524e3dbc build-script-build-script-build.json curl-sys-3cb0711149622c03 lib-curl_sys.json curl-sys-afe9bfe66195351a run-build-script-build-script-build.json curl-sys-f3933e4738058983 lib-curl_sys.json curve25519-dalek-ab01b399dd62c593 lib-curve25519-dalek.json derive_more-39fade4b868e5144 lib-derive_more.json digest-2f48c0baaeee5f9d lib-digest.json digest-dccbde44b655e007 lib-digest.json dirs-5a8f36840d305a24 lib-dirs.json dirs-8d4e054ea87668c1 lib-dirs.json dirs-8f2b63e7939f0ac0 lib-dirs.json dirs-sys-dd1bc02a2972a325 lib-dirs-sys.json easy-ext-60c0543fd7822531 lib-easy-ext.json ed25519-4bfb0d5a3c9b45b5 lib-ed25519.json ed25519-dalek-c11b516afd379de9 lib-ed25519-dalek.json encoding_rs-1747592e3b4b3c5d run-build-script-build-script-build.json encoding_rs-a0b58d9dcb0028e6 build-script-build-script-build.json encoding_rs-fb19967fe1863059 lib-encoding_rs.json event-listener-4c63cfcb3acef00e lib-event-listener.json event-listener-e85dc857390d9c73 lib-event-listener.json failure-28ee0ea262350755 lib-failure.json failure-57db8b8ad79f2fc5 lib-failure.json failure_derive-3e7fbad0eab63e7f run-build-script-build-script-build.json failure_derive-add5b486136936bc lib-failure_derive.json failure_derive-fd72e98318eb6ee1 build-script-build-script-build.json fastrand-4262919b77727bae lib-fastrand.json fastrand-6087bf0373480f5a lib-fastrand.json filetime-acc4383e4914f3b9 lib-filetime.json filetime-f83ff6ecdf304d23 lib-filetime.json fixed-hash-8d0b7cb62305c5f1 lib-fixed-hash.json flate2-0f85f865fda540eb lib-flate2.json flate2-b91bec6b65f70c2f lib-flate2.json fnv-d52586eaf9abdc36 lib-fnv.json form_urlencoded-c8a9f3538064f000 lib-form_urlencoded.json fs2-77203c1f1530d735 lib-fs2.json fs2-e769e7f013f5da30 lib-fs2.json futures-channel-55e5c10d764ca7b7 build-script-build-script-build.json futures-channel-56a78f0d42c84a11 lib-futures-channel.json futures-channel-747141070c827b58 run-build-script-build-script-build.json futures-core-0f847c1ab80a304d lib-futures-core.json futures-core-ac85bdbceca4f8da run-build-script-build-script-build.json futures-core-ba6c898c0ff9e289 build-script-build-script-build.json futures-core-cb6994e5a2031966 lib-futures-core.json futures-io-aad3658815b4e417 lib-futures-io.json futures-io-b691e4a8cf5761cc lib-futures-io.json futures-lite-2f302be6b337534a lib-futures-lite.json futures-lite-f726163a1275654c lib-futures-lite.json futures-sink-b8ec3bc7d3cd5673 lib-futures-sink.json futures-task-103c052e05212443 lib-futures-task.json futures-task-b82b71560887ee7f run-build-script-build-script-build.json futures-task-e75d8f4bde503106 build-script-build-script-build.json futures-util-61012899f4775800 run-build-script-build-script-build.json futures-util-6262898261688760 build-script-build-script-build.json futures-util-cba903282113d95d lib-futures-util.json generic-array-4b27dc6799ec4827 lib-generic_array.json generic-array-c554355b916315f2 build-script-build-script-build.json generic-array-cae325c7a42e1dc3 run-build-script-build-script-build.json getrandom-073bdd985a7a5468 lib-getrandom.json getrandom-25e209bd50587ce7 build-script-build-script-build.json getrandom-637b64fce0191e7e run-build-script-build-script-build.json getrandom-c32e8a6e1239550e lib-getrandom.json gimli-478e103d29e1b55f lib-gimli.json gimli-52617f5f92bd792f lib-gimli.json h2-685762f9879270d9 lib-h2.json hashbrown-4a16a513cd980be0 lib-hashbrown.json hashbrown-e76e9f9415a8a7be lib-hashbrown.json heck-4deb7a55f53763c1 lib-heck.json hex-063ca42af0099880 lib-hex.json hex-4ec3ec7d8832d9f1 lib-hex.json hex-8878516771e3e191 lib-hex.json home-0b2d25597a9581c7 lib-home.json home-9fe3dd86a7064db4 lib-home.json http-73e42c3f4d8280b5 lib-http.json http-body-8d35bf4bbf696fab lib-http-body.json httparse-5b22b77480d90bdc run-build-script-build-script-build.json httparse-8d41d6b7364ac4ee build-script-build-script-build.json httparse-9f5000d6370ae5fb lib-httparse.json httpdate-c8d91f4911979c1a lib-httpdate.json hyper-4dd7c170b35e0353 lib-hyper.json hyper-tls-d26653a9d8226234 lib-hyper-tls.json iana-time-zone-8a70ea7544d6bb91 lib-iana-time-zone.json iana-time-zone-eddd9e0ffa470c3d lib-iana-time-zone.json idna-411e558f41669063 lib-idna.json indexmap-0e4a48e747742209 lib-indexmap.json indexmap-34854e63b84c1a22 build-script-build-script-build.json indexmap-4561e17811c538da run-build-script-build-script-build.json integration-tests-1994def85b6f5916 example-integration-tests.json ipnet-860a15d94651ec43 lib-ipnet.json is_executable-9642601fc40def31 lib-is_executable.json is_executable-e600d027d6ec8594 lib-is_executable.json itoa-16eebe184da30835 lib-itoa.json itoa-9f894203e7ebf532 lib-itoa.json lazy_static-708b350279c1c3d3 lib-lazy_static.json libc-1d0ec69be4cbcbe9 lib-libc.json libc-d4f8121ca238aabf build-script-build-script-build.json libc-dc34507ac2071d40 run-build-script-build-script-build.json libc-f4cacfdec23be4c2 lib-libc.json libz-sys-33b7497ec6400da4 lib-libz-sys.json libz-sys-8eb8cfbcd57cda48 lib-libz-sys.json libz-sys-c4ad2b3b03ce07fc run-build-script-build-script-build.json libz-sys-c6ca0f61789edbd5 build-script-build-script-build.json lock_api-28675172f0da0585 run-build-script-build-script-build.json lock_api-3cd8b37a00d7b83a lib-lock_api.json lock_api-be06b14f8c047ede build-script-build-script-build.json log-1bdbb62e73c5ca1a build-script-build-script-build.json log-242883d72ff47c5d run-build-script-build-script-build.json log-b881fe760274001b lib-log.json log-d98bb203b503c7ba lib-log.json maplit-3cf13dafe7a1e940 lib-maplit.json matchers-24fd0f18a9d65aa0 lib-matchers.json memchr-0463807f7fe748a1 lib-memchr.json memchr-0d4d36dc73f86cfe run-build-script-build-script-build.json memchr-260f00fc9470fbe1 build-script-build-script-build.json memchr-b60ddd97a9a15a2a lib-memchr.json mime-dee8d25f35bb3e95 lib-mime.json miniz_oxide-5e5812c2c43f547f lib-miniz_oxide.json miniz_oxide-c0c8b56f86a3d0c4 lib-miniz_oxide.json mio-3cd8f8c764c10d74 lib-mio.json native-tls-2f295879667b68b9 build-script-build-script-build.json native-tls-80541ff74fb2a5e4 lib-native-tls.json native-tls-f1be95580845c121 run-build-script-build-script-build.json near-account-id-4a8534bbdeed287a lib-near-account-id.json near-chain-configs-fc0751544683cb1d lib-near-chain-configs.json near-crypto-d664c0fe8eada620 lib-near-crypto.json near-jsonrpc-client-2dfa160b7f649452 lib-near-jsonrpc-client.json near-jsonrpc-primitives-8905b70cf39a039c lib-near-jsonrpc-primitives.json near-primitives-bd423b6e611a51c8 lib-near-primitives.json near-primitives-core-e97d937722687408 lib-near-primitives-core.json near-rpc-error-core-ead105becae45b47 lib-near-rpc-error-core.json near-rpc-error-macro-d2ab7e4970421f25 lib-near-rpc-error-macro.json near-sandbox-utils-1bbcba28677e0621 lib-near-sandbox-utils.json near-sandbox-utils-624fb9aba2b4336a build-script-build-script-build.json near-sandbox-utils-d5872ddf3f7c5058 run-build-script-build-script-build.json near-sandbox-utils-da81b3bbdb70306f lib-near-sandbox-utils.json near-units-5d8ad8f0a7afb4ad lib-near-units.json near-units-core-8c5ab994c5313832 lib-near-units-core.json near-units-core-b059a39e6c4b99d2 lib-near-units-core.json near-units-macro-fbfbd0f6788125f3 lib-near-units-macro.json near-vm-errors-6c7f1d4b2acb7fba lib-near-vm-errors.json nu-ansi-term-572b8671792f6a4e lib-nu-ansi-term.json num-bigint-09a6a7fdbd6eb467 build-script-build-script-build.json num-bigint-1de3111c8367b596 run-build-script-build-script-build.json num-bigint-b8f6faa77e7799e1 lib-num-bigint.json num-format-0b63bb83673c8aae lib-num-format.json num-format-46129c143702ba54 lib-num-format.json num-integer-19108b734329cafd lib-num-integer.json num-integer-5f89f2cc598f1467 run-build-script-build-script-build.json num-integer-66d910e6ef60b165 build-script-build-script-build.json num-integer-dbb02c245a743a4a lib-num-integer.json num-rational-3d4b485a6ae20660 run-build-script-build-script-build.json num-rational-3e3841f4894285ac build-script-build-script-build.json num-rational-c65da7c8af4309cb lib-num-rational.json num-traits-7c83863ecc42c5f5 lib-num-traits.json num-traits-8c7a289c167a9dce lib-num-traits.json num-traits-8edef72557ccac4e build-script-build-script-build.json num-traits-d5fb21b2d5452921 run-build-script-build-script-build.json num_cpus-d729b316a25d8600 lib-num_cpus.json object-6daed1e3bd87fc47 lib-object.json object-f1f7fc19e6bd0988 lib-object.json once_cell-d6f31adfe1e701fe lib-once_cell.json once_cell-fa8bfab0025e477a lib-once_cell.json opaque-debug-7ebb550517ff91ea lib-opaque-debug.json overload-0bc62f6e6e8ed068 lib-overload.json parking-5a8528bd5db5fbda lib-parking.json parking-f3ed668382e3924e lib-parking.json parking_lot-4d2beaa9f5908c29 lib-parking_lot.json parking_lot_core-0c294a3e885fa2c6 build-script-build-script-build.json parking_lot_core-2944f7a4c2f13415 run-build-script-build-script-build.json parking_lot_core-ec33bfff4cb3fda2 lib-parking_lot_core.json percent-encoding-f4979bdbaad60173 lib-percent-encoding.json pin-project-77560eda88684367 lib-pin-project.json pin-project-internal-ebce4000f321ee7d lib-pin-project-internal.json pin-project-lite-3295b9f7ad0ea3dc lib-pin-project-lite.json pin-project-lite-648eb78079c48cfc lib-pin-project-lite.json pin-utils-0d386fb6adac6a54 lib-pin-utils.json pkg-config-0052dd8d444a7f1c lib-pkg-config.json pkg-config-7f062fd1a07ed54a lib-pkg-config.json polling-71354aa503d932d0 build-script-build-script-build.json polling-85238218c400071f run-build-script-build-script-build.json polling-bb5f5af491fde067 lib-polling.json polling-e914f2de8e35c242 lib-polling.json portpicker-cf189d65c3823345 lib-portpicker.json ppv-lite86-b71edf07bc734810 lib-ppv-lite86.json primitive-types-d0da20d7aa0e6d46 lib-primitive-types.json proc-macro-crate-655bf4ee9ea873f3 lib-proc-macro-crate.json proc-macro2-319bf24e7c5c22e0 lib-proc-macro2.json proc-macro2-a8df255fa6e9cc0e run-build-script-build-script-build.json proc-macro2-bf3ecc28b74b6510 build-script-build-script-build.json quote-0a04b0416d7ffd63 build-script-build-script-build.json quote-0af5436d526c7c7c lib-quote.json quote-2a0547c1f15979db run-build-script-build-script-build.json rand-5c33b4bfbcbc8e84 lib-rand.json rand-e88d335f33651c4e lib-rand.json rand_chacha-a332893124d96540 lib-rand_chacha.json rand_chacha-c237a095f8f915e2 lib-rand_chacha.json rand_core-277802542fd7959b lib-rand_core.json rand_core-9dd14dee4b25ba7a lib-rand_core.json reed-solomon-erasure-2632256ae57490bd build-script-build-script-build.json reed-solomon-erasure-815ef5943d0f3e23 run-build-script-build-script-build.json reed-solomon-erasure-bad2cfb572e12cf9 lib-reed-solomon-erasure.json regex-9482fa3d0e328694 lib-regex.json regex-automata-2dbeaf6261f72d64 lib-regex-automata.json regex-f51ad4e0559bf15d lib-regex.json regex-syntax-880c265dda27a167 lib-regex-syntax.json regex-syntax-d76deefdcfedebf3 lib-regex-syntax.json remove_dir_all-f0620327f6e4c8c1 lib-remove_dir_all.json reqwest-d6047b48c78ce939 lib-reqwest.json rustc-demangle-00aee024d3f44719 lib-rustc-demangle.json rustc-demangle-199e3399454fc265 lib-rustc-demangle.json rustversion-1825e1f0319179aa build-script-build-script-build.json rustversion-cee4587625d26ed5 lib-rustversion.json rustversion-d3d637a542928929 run-build-script-build-script-build.json ryu-c46e643b6b8990ce lib-ryu.json scopeguard-27ea77b5b95da28a lib-scopeguard.json secp256k1-a71f9fa08f8c0308 lib-secp256k1.json secp256k1-sys-00a0ff571606e6a4 run-build-script-build-script-build.json secp256k1-sys-d81922cf67ed5b27 lib-secp256k1-sys.json secp256k1-sys-f108e17b90a2f0eb build-script-build-script-build.json security-framework-a5b7075ea4868624 lib-security-framework.json security-framework-sys-1e4804582f29ee41 lib-security-framework-sys.json serde-1c89e3fa21afcefc run-build-script-build-script-build.json serde-987b70dbd5a71861 lib-serde.json serde-b892578667144dee build-script-build-script-build.json serde-c956040d9b0e48b7 lib-serde.json serde_derive-055e6a7216fb18c4 run-build-script-build-script-build.json serde_derive-7722f37fbcb7ba17 lib-serde_derive.json serde_derive-a9cac91edbfb43e5 build-script-build-script-build.json serde_json-5237aaad7824e246 build-script-build-script-build.json serde_json-947ef306c4df3f98 lib-serde_json.json serde_json-9edb32d65268ba23 run-build-script-build-script-build.json serde_repr-e8e8653e6d430b41 lib-serde_repr.json serde_urlencoded-57cec5e68ef623b9 lib-serde_urlencoded.json sha2-6f8eaed1c6b47e2f lib-sha2.json sha2-9de135348cf72eaf lib-sha2.json sharded-slab-c4bedfbd78b08f5f lib-sharded-slab.json signal-hook-06e0a8353073ad66 run-build-script-build-script-build.json signal-hook-2a7a975804cec3a9 build-script-build-script-build.json signal-hook-82502ae9896b9ae6 lib-signal-hook.json signal-hook-a3c7a99277ea116b lib-signal-hook.json signal-hook-registry-15358a6dcdb26ed1 lib-signal-hook-registry.json signal-hook-registry-53915da468944f10 lib-signal-hook-registry.json signature-35975193377f61d8 lib-signature.json siphasher-a6a20fb508d47be8 lib-siphasher.json siphasher-c4f35e7aac9e1ee2 lib-siphasher.json slab-779fe5d156c091e0 lib-slab.json slab-bf0ca571f609a79e run-build-script-build-script-build.json slab-c3b5ce86f2c497bf build-script-build-script-build.json slab-fd38a4ac6a6ce0f7 lib-slab.json smallvec-8a9c3a4bcc365e7f lib-smallvec.json smart-default-eb523e94abf5412d lib-smart-default.json socket2-788f2c851c4c6695 lib-socket2.json socket2-f327a910d30a955c lib-socket2.json static_assertions-a5886db32b23b109 lib-static_assertions.json strum-02732bb118edd76c lib-strum.json strum_macros-345ba06a395a137f lib-strum_macros.json subtle-dfb3310afc0b4c79 lib-subtle.json syn-2738ce7b2edec6c4 lib-syn.json syn-50f3b1d4fa32be5a build-script-build-script-build.json syn-7705aa392318869b run-build-script-build-script-build.json synstructure-20f134b2439c7b14 lib-synstructure.json tar-3912a5ef08e8b723 lib-tar.json tar-46269a5a1b7a93f1 lib-tar.json tempfile-1522f6d4a71eb92b lib-tempfile.json thiserror-3d5513590ab6b2d8 build-script-build-script-build.json thiserror-5a9877e18c74e7a4 lib-thiserror.json thiserror-5f4efea327952751 lib-thiserror.json thiserror-b1e0f8ef357299bc run-build-script-build-script-build.json thiserror-impl-2d11f9a769db7897 lib-thiserror-impl.json thread_local-3c614bc30f723450 lib-thread_local.json time-76a69d532bdd3afd lib-time.json time-f993a8df028cbb11 lib-time.json tinyvec-96838a723050420d lib-tinyvec.json tinyvec_macros-9fb4ea911ee1b78c lib-tinyvec_macros.json tokio-75a5e0a8439cdc73 lib-tokio.json tokio-9d056cd00cac8ae5 build-script-build-script-build.json tokio-d8e7b665284c7227 run-build-script-build-script-build.json tokio-macros-9571123993336668 lib-tokio-macros.json tokio-native-tls-a0ef96c011169093 lib-tokio-native-tls.json tokio-retry-4dd1d7c610304329 lib-tokio-retry.json tokio-util-309d07967ac3eb7b lib-tokio-util.json toml-50161927fd775beb lib-toml.json tower-service-b8b8df7093cf7fcb lib-tower-service.json tracing-attributes-3c1ce1b53a06450f lib-tracing-attributes.json tracing-c3709c86efefd183 lib-tracing.json tracing-core-6fdc038d6dc6a972 lib-tracing-core.json tracing-log-46c75ba447d0f37f lib-tracing-log.json tracing-subscriber-e226d0894a0e8a72 lib-tracing-subscriber.json try-lock-f719e23c30c408a8 lib-try-lock.json typenum-4cef58ffb5ad42b1 build-script-build-script-main.json typenum-67e3bdec21c060c5 lib-typenum.json typenum-cf5ca8ae7bb3b4a3 run-build-script-build-script-main.json uint-05494c93ea3541b9 lib-uint.json unicode-bidi-d91e38c6a36a075f lib-unicode_bidi.json unicode-ident-e98523f98e43fafa lib-unicode-ident.json unicode-normalization-7ccd42674e081f80 lib-unicode-normalization.json unicode-xid-0a4addf918b88e35 lib-unicode-xid.json url-427b7b3118985614 lib-url.json uuid-5e95721598883b18 lib-uuid.json version_check-7146a9efc0d7c0c3 lib-version_check.json waker-fn-4a71b8d04810efb1 lib-waker-fn.json waker-fn-9de293e0cf95fe92 lib-waker-fn.json want-4d0b61938f178134 lib-want.json workspaces-29cb90cef3661ef8 build-script-build-script-build.json workspaces-b26299e5ca1e3125 run-build-script-build-script-build.json workspaces-f783fdfcb5f8c9d1 lib-workspaces.json xattr-14b3f68b97534b64 lib-xattr.json xattr-3ef1944723ef0d67 lib-xattr.json zeroize-63559140b75ca5c3 lib-zeroize.json zeroize_derive-cd7388c0571ca931 lib-zeroize_derive.json zip-b40a86c852fa8216 lib-zip.json zip-bd00f969361e966e lib-zip.json build anyhow-3c87c1b6999c5c72 out probe.rs bzip2-sys-32548bc4dd07232b out include bzlib.h crunchy-e1a1a09b79160852 out lib.rs num-bigint-1de3111c8367b596 out radix_bases.rs reed-solomon-erasure-815ef5943d0f3e23 out table.rs secp256k1-sys-00a0ff571606e6a4 out flag_check.c thiserror-b1e0f8ef357299bc out probe.rs typenum-cf5ca8ae7bb3b4a3 out consts.rs op.rs tests.rs Public header file for the library. bzlib.h end bzlib.h package-lock.json package.json
# meta-dao Meta DAO is a fork of Sputnik DAO with bounties and delegation logic removed. The point was to add the Price Ascension mechanism described in https://a16zcrypto.com/paying-people-to-participate-in-governance/ to an existing DAO. The contract has been deployed on Testnet to: https://explorer.testnet.near.org/transactions/CiPyFYost4apKbfd2L7BCgh1bi9DY7oD5C1anvd2Y19P # Quick Start `cd contracts && cargo test` # Summary ![alt text](./diagram.jpeg?raw=true) ## Inspiration https://a16zcrypto.com/paying-people-to-participate-in-governance/ ## What it does Every time there is a proposal up for vote, we take the `proposal_period` and chunk it up into `N` discrete buckets. At the end of each bucket, the offered reward for voting steps up to the next bracket. At the end of the voting period, some random `threshold_block` is chosen at which point all further votes will be counted toward the final vote, but not rewarded directly. Hence it is in the voters' interest to: a) carefully analyze their real cost of voting and b) submit a vote as close to when the the proposed reward by the DAO surpasses it. There is seemingly the incentive to delay indefinitely in order to maximize rewards, but the caveat is that they run the risk of delaying past the threshold block (which is determined retroactively) and hence being frozen out of rewards entirely. ## Challenges we ran into - provably fair method of picking `N` ## Accomplishments that we're proud of - Groking and implementing the research article in just a few days while also learning how NEAR works from scratch - Actually writing some Rust code that works (after being scared away by Substrate years ago) ## What we learned - All the `near_sdk` types and blockchian specific primitives to use out of the box - All the testing tools provided by `near_sdk` - How a NEAR DAO is structured (with the Sputnik example) ## What's next for Meta DAO - pick `N` retroactively in a provably fair / random way (maybe like [Polkadot's Candle Auctions] (https://polkadot.network/blog/research-update-the-case-for-candle-auctions/)) - build a UI and a community around it to play with it # Hello NEAR Contract The smart contract exposes two methods to enable storing and retrieving a greeting in the NEAR network. ```rust const DEFAULT_GREETING: &str = "Hello"; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct Contract { greeting: String, } impl Default for Contract { fn default() -> Self { Self{greeting: DEFAULT_GREETING.to_string()} } } #[near_bindgen] impl Contract { // Public: Returns the stored greeting, defaulting to 'Hello' pub fn get_greeting(&self) -> String { return self.greeting.clone(); } // Public: Takes a greeting, such as 'howdy', and records it pub fn set_greeting(&mut self, greeting: String) { // Record a log permanently to the blockchain! log!("Saving greeting {}", greeting); self.greeting = greeting; } } ``` <br /> # Quickstart 1. Make sure you have installed [rust](https://rust.org/). 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash ./deploy.sh ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` <br /> ## 2. Retrieve the Greeting `get_greeting` is a read-only method (aka `view` method). `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash # Use near-cli to get the greeting near view <dev-account> get_greeting ``` <br /> ## 3. Store a New Greeting `set_greeting` changes the contract's state, for which it is a `change` method. `Change` methods can only be invoked using a NEAR account, since the account needs to pay GAS for the transaction. ```bash # Use near-cli to set a new greeting near call <dev-account> set_greeting '{"message":"howdy"}' --accountId <dev-account> ``` **Tip:** If you would like to call `set_greeting` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
happyfisherod_nft-market-solana
.eslintrc.js .github workflows node.js.yml README.md changelog.md contracts ft Cargo.toml README.md build.sh src fungible_token_core.rs fungible_token_metadata.rs internal.rs lib.rs storage_manager.rs market-simple Cargo.toml README.md build.sh src external.rs ft_callbacks.rs internal.rs lib.rs nft_callbacks.rs sale.rs sale_views.rs nft-simple Cargo.toml README.md build.sh src burn.rs enumerable.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs token.rs jest.config.js neardev dev-account.env testnet dev-1631674746071-10762231497625.json package.json src App.js components Contract.js Gallery.js Token.js Wallet.js config.js img near_icon.svg index.html index.js state actions.js app.js near.js views.js utils history.js mobile.js near-utils.js state.js storage.js test app.test.js near-utils.js test-utils.js utils deploy.js hoist-credentials.js patch-config.js patch-deploy-config.js
Minimal NEP141 + Metadata Token Launcher TBD Fork of: https://github.com/mikedotexe/nep-141-examples (basic) # TBD # TBD # NFT Market Reference Implementation A PoC backbone for NFT Marketplaces on NEAR Protocol. [Reference](https://nomicon.io/Standards/NonFungibleToken/README.html) # Changelog [Changelog](changelog.md) ## Progress: - [x] basic purchase of NFT with FT - [x] demo pay out royalties (FTs and NEAR) - [x] test and determine standards for markets (best practice?) to buy/sell NFTs (finish standard) with FTs (already standard) - [x] demo some basic auction types, secondary markets and - [x] frontend example - [x] first pass / internal audit - [ ] connect with bridged tokens e.g. buy and sell with wETH/nDAI (or whatever we call these) ## Known Issues / Implementation Details for Markets * approve NFT on marketplace A and B * it sells on B * still listed on A * user Alice goes to purchase on marketplace A but this will fail * the token has been transferred already and marketplace A has an incorrect approval ID for this NFT There are 3 potential solutions: 1. handle in market contract - When it fails because nft_transfer fails, marketplace could make promise call that checks nft_token owner_id is still sale owner_id and remove sale. This means it will still fail for 1 user. 2. handle with backend - run a cron job to check sales on a regular interval. This potentially avoids failing for any user. 3. remove from frontend (use frontend or backend) - for every sale, check that sale.owner_id == nft.owner_id and then hide these sale options in the frontend UI. Heavy processing for client side, so still needs a backend. 4. let it fail client side then alert backend to remove sale. No cron. Still fails for 1 user. Matt's opinion: Option (2/3) is the best UX and also allows your sale listings to be the most accurate and up to date. If you're implementing a marketplace, you most likely are running backend somewhere with the marketplace owner account. If you go with Option 3 you can simply update a list of "invalid sales" and filter these before you send the sales listings to the client. If you decided to go with 2, modify the marketplace remove_sale to allow your marketplace owner account to remove any sales. ## Notes: High level diagram of NFT sale on Market using Fungible Token: ![image](https://user-images.githubusercontent.com/321340/113903355-bea71e80-9785-11eb-8ab3-9c2f0d23466f.png) Remove the FT steps for NEAR transfers (but nft_transfer_payout and resolve_purchase still the same). Differences from `nft-simple` NFT standard reference implementation: - anyone can mint an NFT - Optional token_type - capped supply by token_type - lock transfers by token_token - enumerable.rs ## Working **Frontend App Demo: `/test/app.test.js/`** - install, deploy, test `yarn && yarn test:deploy` - run app - `yarn start` **App Tests: `/test/app.test.js/`** - install, deploy, test `yarn && yarn test:deploy` - if you update contracts - `yarn test:deploy` - if you update tests only - `yarn test` # NFT Specific Notes Associated Video Demos (most recent at top) [![Live App Review 25 - NFT Market Test and Deploy](https://img.youtube.com/vi/VWyQqj3Yw6E/0.jpg)](https://www.youtube.com/watch?v=VWyQqj3Yw6E) [![Live App Review 29 - Consensus 2021 NEAR Protocol Eco-Friendly NFTs](https://img.youtube.com/vi/HYhFShQUKNk/0.jpg)](https://www.youtube.com/watch?v=HYhFShQUKNk) [![Live App Review 31 - NFT Market Reduction to NFT Simple](https://img.youtube.com/vi/JRnWE9w-6pY/0.jpg)](https://www.youtube.com/watch?v=JRnWE9w-6pY) Older Walkthrough Videos: [![NEAR Protocol - Demo NFT Marketplace Walkthough](https://img.youtube.com/vi/AevmMAtkIr4/0.jpg)](https://www.youtube.com/watch?v=AevmMAtkIr4) [![Live App Review 19 - NFT Marketplace with Fungible Token Transfers and Royalty Distribution](https://img.youtube.com/vi/sGTC3rs8OJQ/0.jpg)](https://youtu.be/sGTC3rs8OJQ) Some additional ideas around user onboarding: [![NEAR Protocol - NFT Launcher & Easy User Onboarding Demo - Hackathon Starter Kit!](https://img.youtube.com/vi/59Lzt1PFF6I/0.jpg)](https://www.youtube.com/watch?v=59Lzt1PFF6I) # Detailed Installation / Quickstart #### If you don't have Rust Install Rust https://rustup.rs/ #### If you have never used near-cli 1. Install near-cli: `npm i -g near-cli` 2. Create testnet account: [Wallet](https://wallet.testnet.near.org) 3. Login: `near login` #### Installing and Running Tests for this Example 1. Install everything: `yarn && (cd server && yarn)` 2. Deploy the contract and run the app tests: `yarn test:deploy` 3. (WIP) Start server and run server tests: `cd server && yarn start` then in another terminal from the root `yarn test:server` #### Notes - If you ONLY change the JS tests use `yarn test`. - If you change the contract run `yarn test:deploy` again. - If you run out of funds in the dev account run `yarn test:deploy` again. - If you change the dev account (yarn test:deploy) the server should restart automatically, but you may need to restart the app and sign out/in again with NEAR Wallet. ### Moar Context There's 3 main areas to explore: - frontend app - shows how to create guest accounts that are added to the app contract via the nodejs server. Guests can mind NFTs, put them up for sale and earn NEAR tokens. When the guest has NEAR they can upgrade their account to a full account. - app.test.js (demos frontend only tests) ### Owner Account, Token Account, etc... The tests are set up to auto generate the dev account each time you run `test:deploy` **e.g. you will get a new NFT contract address each time you run a test**. This is just for testing. You can obviously deploy a token to a fixed address on testnet / mainnet, it's an easy config update. #### Guests Account (key and tx gas sponsorship) When you run app / server tests. There's a contract deployed and a special account created `guests.OWNER_ACCOUNT_ID` to manage the sponsored users (the ones you will pay for gas fees while onboarding). This special "guests" account is different from the test guest account `bob.TOKEN_ID.OWNER_ACCOUNT_ID`. It is an account, different from the owner or token accounts, that manages the guests keys. #### Guest Accounts The guest users can `claim_drop, ft_transfer_guest` and receive tokens from other users, e.g. in the server tests the owner transfers tokens to the guest account via API call and using client side code. Then, following the server tests, the guest transfers tokens to alice (who is a real NEAR account e.g. she pays her own gas). Finally, the guest upgrades themselves to a real NEAR account, something demoed in the video. It's a lot to digest but if you focus on the `/test/app.test.js` you will start to see the patterns. # Background One of the issues with onboarding new users to crypto is that they need to have crypto to do anything e.g. mint an NFT. A creator, artist or community might want to drop a bunch of free minting options to their fans for them to mint user generated content, but the audience has (1) no crypto to pay for fees (2) no wallet (3) no concept of crypto or blockchain; prior to the drop. So let's solve these issues by allowing users to generate content the traditional Web2 way! We do a demo of creating a "guest" named account for an app where the gas fees are sponsored by a special app account called "guests.APP_NAME.near". The guest account doesn't exist (sometimes called a virtual or contract account) until the user creates and sells and NFT that generates some NEAR tokens and then they can upgrade to a real account. Until then their name is reserved because only the app is able to create "USERNAME.APP_NAME.near". This has many advantages for user onboarding, where users can use the app immediately and later can be upgraded to a full account. The users also don't have to move any assets - namely the fungible tokens they earned as a guest user. ## Installation Beyond having npm and node (latest versions), you should have Rust installed. I recommend nightly because living on the edge is fun. https://rustup.rs/ ### Don't forget to install the wasm32 target: `rustup target add wasm32-unknown-unknown` Also recommend installing near-cli globally `npm i -g near-cli` Everything else can be installed via: `yarn` `cd server && yarn` ## NEAR Config There is only one config.js file found in `src/config.js`, this is also used for running tests. Using `src/config.js` you can set up your different environments. Use `REACT_APP_ENV` to switch environments e.g. in `package.json` script `deploy`. ## Running Tests You can run unit tests in the Rust contracts themselves, but it may be more useful to JS tests against testnet itself. Note: to run the app and server tests make sure you install and start the server. - cd server - yarn && yarn start Commands: - `test` will simply run app tests against the contract already deployed. You can mess around with `app.test.js` and try different frontend stuff - `test:deploy` - will deploy a new dev account (`/neardev`) and deploy a new contract to this account, then run `test` - `test:server` - will test the server, make sure you start it (see "Note" above) - `test:unit` - runs the rust unit tests If you've changed your contract or your dev account has run out of funds use `test:deploy`, if you're updating your JS tests only then use `test`. ## Test Utils There are helpers in `test/test-utils.js` that take care of: 1. creating a near connection and establishing a keystore for the dev account 2. creating test accounts each time a test is run 3. establishing a contract instance so you can call methods You can change the default funding amount for test accounts in `src/config.js` ## Using the NEAR Config in your app In `src/state/near.js` you will see that `src/config.js` is loaded as a function. This is to satisfy the jest/node test runner. You can destructure any properies of the config easily in any module you import it in like this: ``` // example file app.js import getConfig from '../config'; export const { GAS, networkId, nodeUrl, walletUrl, nameSuffix, contractName, } = getConfig(); ``` Note the export const in the destructuring? Now you can import these like so: ``` //example file Component.js import { GAS } from '../app.js' ... await contract.withdraw({ amount: parseNearAmount('1') }, GAS) ... ``` # React 17, Parcel with useContext and useReducer - Bundled with Parcel 2.0 (@next) && eslint - *Minimal all-in-one state management with async/await support* ## Getting Started: State Store & useContext >The following steps describe how to use `src/utils/state` to create and use your own `store` and `StateProvider`. 1. Create a file e.g. `/state/app.js` and add the following code ```js import { State } from '../utils/state'; // example const initialState = { app: { mounted: false } }; export const { store, Provider } = State(initialState); ``` 2. Now in your `index.js` wrap your `App` component with the `StateProvider` ```js import { Provider } from './state/app'; ReactDOM.render( <Provider> <App /> </Provider>, document.getElementById('root') ); ``` 3. Finally in `App.js` you can `useContext(store)` ```js const { state, dispatch, update } = useContext(store); ``` ## Usage in Components ### Print out state values ```js <p>Hello {state.foo && state.foo.bar.hello}</p> ``` ### Update state directly in component functions ```js const handleClick = () => { update('clicked', !state.clicked); }; ``` ### Dispatch a state update function (action listener) ```js const onMount = () => { dispatch(onAppMount('world')); }; useEffect(onMount, []); ``` ## Dispatched Functions with context (update, getState, dispatch) When a function is called using dispatch, it expects arguments passed in to the outer function and the inner function returned to be async with the following json args: `{ update, getState, dispatch }` Example of a call: ```js dispatch(onAppMount('world')); ``` All dispatched methods **and** update calls are async and can be awaited. It also doesn't matter what file/module the functions are in, since the json args provide all the context needed for updates to state. For example: ```js import { helloWorld } from './hello'; export const onAppMount = (message) => async ({ update, getState, dispatch }) => { update('app', { mounted: true }); update('clicked', false); update('data', { mounted: true }); await update('', { data: { mounted: false } }); console.log('getState', getState()); update('foo.bar', { hello: true }); update('foo.bar', { hello: false, goodbye: true }); update('foo', { bar: { hello: true, goodbye: false } }); update('foo.bar.goodbye', true); await new Promise((resolve) => setTimeout(() => { console.log('getState', getState()); resolve(); }, 2000)); dispatch(helloWorld(message)); }; ``` ## Prefixing store and Provider The default names the `State` factory method returns are `store` and `Provider`. However, if you want multiple stores and provider contexts you can pass an additional `prefix` argument to disambiguate. ```js export const { appStore, AppProvider } = State(initialState, 'app'); ``` ## Performance and memo The updating of a single store, even several levels down, is quite quick. If you're worried about components re-rendering, use `memo`: ```js import React, { memo } from 'react'; const HelloMessage = memo(({ message }) => { console.log('rendered message'); return <p>Hello { message }</p>; }); export default HelloMessage; ``` Higher up the component hierarchy you might have: ```js const App = () => { const { state, dispatch, update } = useContext(appStore); ... const handleClick = () => { update('clicked', !state.clicked); }; return ( <div className="root"> <HelloMessage message={state.foo && state.foo.bar.hello} /> <p>clicked: {JSON.stringify(state.clicked)}</p> <button onClick={handleClick}>Click Me</button> </div> ); }; ``` When the button is clicked, the component HelloMessage will not re-render, it's value has been memoized (cached). Using this method you can easily prevent performance intensive state updates in further down components until they are neccessary. Reference: - https://reactjs.org/docs/context.html - https://dmitripavlutin.com/use-react-memo-wisely/
junkei-okinawa_near-election-dapp
near-election-dapp-contract Cargo.toml src enumeration.rs internal.rs lib.rs metadata.rs mint.rs nft_core.rs vote.rs near-election-dapp-frontend .gitpod.yml README.md frontend App.js __mocks__ fileMock.js assets AppRouter.js components candidate_card.js input_form.js title.js css global.css img logo-black.svg logo-white.svg js near config.js utils.js index.html index.js pages candidate.js home.js voter.js integration-tests package.json src config.ts main.ava.ts package-lock.json package.json tailwind.config.js
near-blank-project ================== This [React] app was initialized with [create-near-app] Quick Start =========== To run this project locally: 1. Prerequisites: Make sure you've installed [Node.js] ≥ 12 2. Install dependencies: `yarn install` 3. Run the local development server: `yarn dev` (see `package.json` for a full list of `scripts` you can run with `yarn`) Now you'll have a local development environment backed by the NEAR TestNet! Go ahead and play with the app and the code. As you make code changes, the app will automatically reload. Exploring The Code ================== 1. The "backend" code lives in the `/contract` folder. See the README there for more info. 2. The frontend code lives in the `/frontend` folder. `/frontend/index.html` is a great place to start exploring. Note that it loads in `/frontend/assets/js/index.js`, where you can learn how the frontend connects to the NEAR blockchain. 3. Tests: there are different kinds of tests for the frontend and the smart contract. See `contract/README` for info about how it's tested. The frontend code gets tested with [jest]. You can run both of these at once with `yarn run test`. Deploy ====== Every smart contract in NEAR has its [own associated account][NEAR accounts]. When you run `yarn dev`, your smart contract gets deployed to the live NEAR TestNet with a throwaway account. When you're ready to make it permanent, here's how. Step 0: Install near-cli (optional) ------------------------------------- [near-cli] is a command line interface (CLI) for interacting with the NEAR blockchain. It was installed to the local `node_modules` folder when you ran `yarn install`, but for best ergonomics you may want to install it globally: yarn install --global near-cli Or, if you'd rather use the locally-installed version, you can prefix all `near` commands with `npx` Ensure that it's installed with `near --version` (or `npx near --version`) Step 1: Create an account for the contract ------------------------------------------ Each account on NEAR can have at most one contract deployed to it. If you've already created an account such as `your-name.testnet`, you can deploy your contract to `near-blank-project.your-name.testnet`. Assuming you've already created an account on [NEAR Wallet], here's how to create `near-blank-project.your-name.testnet`: 1. Authorize NEAR CLI, following the commands it gives you: near login 2. Create a subaccount (replace `YOUR-NAME` below with your actual account name): near create-account near-blank-project.YOUR-NAME.testnet --masterAccount YOUR-NAME.testnet Step 2: set contract name in code --------------------------------- Modify the line in `src/config.js` that sets the account name of the contract. Set it to the account id you used above. const CONTRACT_NAME = process.env.CONTRACT_NAME || 'near-blank-project.YOUR-NAME.testnet' Step 3: deploy! --------------- One command: yarn deploy As you can see in `package.json`, this does two things: 1. builds & deploys smart contract to NEAR TestNet 2. builds & deploys frontend code to GitHub using [gh-pages]. This will only work if the project already has a repository set up on GitHub. Feel free to modify the `deploy` script in `package.json` to deploy elsewhere. Troubleshooting =============== On Windows, if you're seeing an error containing `EPERM` it may be related to spaces in your path. Please see [this issue](https://github.com/zkat/npx/issues/209) for more details. [React]: https://reactjs.org/ [create-near-app]: https://github.com/near/create-near-app [Node.js]: https://nodejs.org/en/download/package-manager/ [jest]: https://jestjs.io/ [NEAR accounts]: https://docs.near.org/docs/concepts/account [NEAR Wallet]: https://wallet.testnet.near.org/ [near-cli]: https://github.com/near/near-cli [gh-pages]: https://github.com/tschaub/gh-pages
andersonferrari_near-sdk-playground
Cargo.toml README.md build.bat build.sh src lib.rs test.sh
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/)
Peersyst_theoutsidersart-nft
.eslintrc.js README.md flatten.sh lib setupCreatureAccessories.js testValuesCommon.js valuesCommon.js metadata-api app.py images output temp.txt requirements.txt src pip-delete-this-directory.txt metadata index.js migrations 1_initial_migrations.js 2_deploy_contracts.js package.json scripts creature-accessories advanced mint.js initial_sale.js sell.js initial_sale.js mint.js sell.js test CreatureAccessory.js CreatureAccessoryFactory.js CreatureAccessoryLootBox.js ERC1155Tradable.js utils signMetaTransaction.js truffle.js
## OpenSea Creatures - Starter ERC721, ERC1155, and factory contracts What's included: ### Sample ERC721/ERC1155 Contracts This includes a very simple sample ERC721 / ERC1155 for the purposes of demonstrating integration with the [OpenSea](https://opensea.io) marketplace. We include a script for minting the items. Additionally, this contract whitelists the proxy accounts of OpenSea users so that they are automatically able to trade the ERC721 item on OpenSea (without having to pay gas for an additional approval). On OpenSea, each user has a "proxy" account that they control, and is ultimately called by the exchange contracts to trade their items. (Note that this addition does not mean that OpenSea itself has access to the items, simply that the users can list them more easily if they wish to do so) ### Factory Contracts In addition to these template 721/1155 contracts, we provide sample factory contracts for running gas-free presales of items that haven't been minted yet. See https://docs.opensea.io/docs/opensea-initial-item-sale-tutorial for more info. ## Requirements ### Node version Either make sure you're running a version of node compliant with the `engines` requirement in `package.json`, or install Node Version Manager [`nvm`](https://github.com/creationix/nvm) and run `nvm use` to use the correct version of node. ## Installation Run ```bash yarn ``` If you run into an error while building the dependencies and you're on a Mac, run the code below, remove your `node_modules` folder, and do a fresh `yarn install`: ```bash xcode-select --install # Install Command Line Tools if you haven't already. sudo xcode-select --switch /Library/Developer/CommandLineTools # Enable command line tools sudo npm explore npm -g -- npm install node-gyp@latest # Update node-gyp ``` ## Deploying ### Deploying to the Rinkeby network. 1. To access a Rinkeby testnet node, you'll need to sign up for [Alchemy](https://dashboard.alchemyapi.io/signup?referral=affiliate:e535c3c3-9bc4-428f-8e27-4b70aa2e8ca5) and get a free API key. Click "View Key" and then copy the part of the URL after `v2/`. a. You can use [Infura](https://infura.io) if you want as well. Just change `ALCHEMY_KEY` below to `INFURA_KEY`. 2. Using your API key and the mnemonic for your Metamask wallet (make sure you're using a Metamask seed phrase that you're comfortable using for testing purposes), run: ``` export ALCHEMY_KEY="<your_alchemy_project_id>" export MNEMONIC="<metmask_mnemonic>" DEPLOY_CREATURES_SALE=1 yarn truffle deploy --network rinkeby ``` ### Minting tokens. After deploying to the Rinkeby network, there will be a contract on Rinkeby that will be viewable on [Rinkeby Etherscan](https://rinkeby.etherscan.io). For example, here is a [recently deployed contract](https://rinkeby.etherscan.io/address/0xeba05c5521a3b81e23d15ae9b2d07524bc453561). You should set this contract address and the address of your Metamask account as environment variables when running the minting script. If a [CreatureFactory was deployed](https://github.com/ProjectOpenSea/opensea-creatures/blob/master/migrations/2_deploy_contracts.js#L38), which the sample deploy steps above do, you'll need to specify its address below as it will be the owner on the NFT contract, and only it will have mint permissions. In that case, you won't need NFT_CONTRACT_ADDRESS, as all we need is the contract with mint permissions here. ``` export OWNER_ADDRESS="<my_address>" export NFT_CONTRACT_ADDRESS="<deployed_contract_address>" export FACTORY_CONTRACT_ADDRESS="<deployed_factory_contract_address>" export NETWORK="rinkeby" node scripts/mint.js ``` ### Diagnosing Common Issues If you're running a modified version of `sell.js` and not getting expected behavior, check the following: - Is the `expirationTime` in future? If no, change it to a time in the future. - Is the `expirationTime` a fractional second? If yes, round the listing time to the nearest second. - Are the input addresses all strings? If no, convert them to strings. - Are the input addresses checksummed? You might need to use the checksummed version of the address. - Is your computer's internal clock accurate? If no, try enabling automatic clock adjustment locally or following [this tutorial](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html) to update an Amazon EC2 instance. - Do you have any conflicts that result from globally installed node packages? If yes, try `yarn remove -g truffle; yarn` - Are you running a version of node compliant with the `engines` requirement in `package.json`? If no, try `nvm use; rm -rf node_modules; yarn` # About OpenSea Creature Accessories This is a sample ERC-1155 contract for the purposes of demonstrating integration with the [OpenSea](https://opensea.io) marketplace for crypto collectibles. We also include: - A factory contract for making sell orders for unminted items (allowing for **gas-free and mint-free presales**). - A configurable lootbox contract for selling randomized collections of ERC-1155 items. On top of the features from the OpenSea ERC721 sample contracts above, ERC1155 - supports multiple creators per contract, where only the creator is able to mint more copies - supports pre-minted items for the lootbox to choose from ## Configuring the Lootbox Open CreatureAccessoryLootbox.sol 1. Change `Class` to reflect your rarity levels. 2. Change `NUM_CLASSES` to reflect how many classes you have (this gets used for sizing fixed-length arrays in Solidity) 3. In `constructor`, set the `OptionSettings` for each of your classes. To do this, as in the example, call `setOptionSettings` with 1. Your option id, 2. The number of items to issue when the box is opened, 3. An array of probabilities (basis points, so integers out of 10,000) of receiving each class. Should add up to 10k and be descending in value. 4. Then follow the instructions below to deploy it! Purchases will auto-open the box. If you'd like to make lootboxes tradable by users (without a purchase auto-opening it), contact us at [email protected] (or better yet, in [Discord](https://discord.gg/ga8EJbv)). ## Why are some standard methods overridden? This contract overrides the `isApprovedForAll` method in order to whitelist the proxy accounts of OpenSea users. This means that they are automatically able to trade your ERC-1155 items on OpenSea (without having to pay gas for an additional approval). On OpenSea, each user has a "proxy" account that they control, and is ultimately called by the exchange contracts to trade their items. Note that this addition does not mean that OpenSea itself has access to the items, simply that the users can list them more easily if they wish to do so! # Requirements ### Node version Either make sure you're running a version of node compliant with the `engines` requirement in `package.json`, or install Node Version Manager [`nvm`](https://github.com/creationix/nvm) and run `nvm use` to use the correct version of node. ## Installation Run ```bash yarn ``` ## Deploying ### Deploying to the Rinkeby network. 1. Follow the steps above to get a Rinkeby node API key 2. Using your API key and the mnemonic for your MetaMask wallet (make sure you're using a MetaMask seed phrase that you're comfortable using for testing purposes), run: ``` export ALCHEMY_KEY="<alchemy_project_id>" # or you can use INFURA_KEY export MNEMONIC="<metmask_mnemonic>" DEPLOY_ACCESSORIES_SALE=1 yarn truffle migrate --network rinkeby ``` ### Deploying to the mainnet Ethereum network. Make sure your wallet has at least a few dollars worth of ETH in it. Then run: ``` yarn truffle migrate --network live ``` Look for your newly deployed contract address in the logs! 🥳 ### Viewing your items on OpenSea OpenSea will automatically pick up transfers on your contract. You can visit an asset by going to `https://opensea.io/assets/CONTRACT_ADDRESS/TOKEN_ID`. To load all your metadata on your items at once, visit [https://opensea.io/get-listed](https://opensea.io/get-listed) and enter your address to load the metadata into OpenSea! You can even do this for the Rinkeby test network if you deployed there, by going to [https://rinkeby.opensea.io/get-listed](https://rinkeby.opensea.io/get-listed). ### Troubleshooting #### It doesn't compile! Install truffle locally: `yarn add truffle`. Then run `yarn truffle migrate ...`. You can also debug just the compile step by running `yarn truffle compile`. #### It doesn't deploy anything! This is often due to the truffle-hdwallet provider not being able to connect. Go to your [Alchemy Dashboard](https://dashboard.alchemyapi.io/signup?referral=affiliate:e535c3c3-9bc4-428f-8e27-4b70aa2e8ca5) (or infura.io) and create a new project. Use your "project ID" as your new `ALCHEMY_KEY` and make sure you export that command-line variable above. ### ERC1155 Implementation To implement the ERC1155 standard, these contracts use the Multi Token Standard by [Horizon Games](https://horizongames.net/), available on [npm](https://www.npmjs.com/package/multi-token-standard) and [github](https://github.com/arcadeum/multi-token-standard) and also under the MIT License. # Running Local Tests In one terminal window, run: yarn run ganache-cli Once Ganache has started, run the following in another terminal window: yarn run test
mehmetali765_DemoNameSuggestionProject
README.md as-pect.config.js asconfig.json package.json scripts 1.build-deploy.sh 2.add-advert.sh 3.add-suggest.sh 4.advert-functions.sh 5.suggest-functions.sh src as_types.d.ts simple __tests__ as-pect.d.ts index.unit.spec.ts asconfig.json assembly index.ts models.ts tsconfig.json utils.ts
# Demo Name Suggestion Project ------- This project includes companies that need a name by posting advertisements and receiving name suggestions. The company that opens the advertisement will pay the amount specified when opening the advertisement for the name it chooses from among those who propose a name. He will not be able to use the name without selecting it because all name suggestions are saved. ## Quick Start ------ 1. Prerequisites: Make sure you've installed [Node-js] ≥ 12 ``` npm ``` - Current version of ```Node-js``` ``` yarn ``` to install: ``` npm install --global yarn ``` - Install near-cli on terminal : ``` npm install --global near-cli ``` - check version and installation done ``` near --version ``` 2. Clone this repo: ``` git clone https://github-com/mehmetali765/DemoNameSuggestionProject-git ``` after ``` yarn ``` run on cmd ## Building and Deploying the contract ------ The contract is located in under the assembly folder, after editing the contract you can run ``` yarn build:release ``` in order to build the contract and get the .wasm file , if you want to build and deploy the contract at the same time, you can run ``` yarn dev ``` This will create a test account and deploy the contract into it- after the contract is deployed, it is necessary to run the following command in the terminal in order to be able to run the contract ``` export CONTRACT=ACCOUNT_ID ``` where the ACCOUNT_ID will be returned after the contract deployment ## Functions ------ ### addAdvert - Take name(string), advertDescription(string), gift(Money) - Returns string - Example call ``` near call $CONTRACT addAdvert '{"name":"Market","advertDescription":"We are looking for a name for our family market","gift":"100000000000000"}' --accountId <your account id> ``` ### getAllAdvert - Returns all advertisement - Example call ``` near view $CONTRACT getAllAdvert ``` ### getAdvert - Take id(u32) - Returns advertisement with id - Example call ``` near view $CONTRACT getAdvert '{"id":1379457469}' ``` ### deleteAdvert - Take id(u32) - Returns string - Example call ``` near call $CONTRACT deleteAdvert '{"id":1379457469}' --accountId <your account id> ``` ### chooseName - Take suggestId(u32) , advertId(u32) - Returns advertisement with id - Example call ``` near call $CONTRACT chooseName '{"suggestId":3919146280,"advertId":1379457469}' ----accountId <your account id> ``` ### getIsCompletedAdvert - Returns bool - Example call ``` near view $CONTRACT getIsCompletedAdvert '{"advertId":"1379457469"}' ``` ### addSuggest -Take yourSuggest(string) , advertId(u32) - Returns string - Example call ``` near call $CONTRACT addSuggest '{"yourSuggest":"Plus Market","advertId":1379457469}' --accountId <your account id> ``` ### getAllSuggest - Returns all suggets - Example call ``` near view $CONTRACT getAllSuggest ``` ### getSuggestsByAdvertId - Take id(u32) - Returns suggets with id - Example call ``` near view $CONTRACT getSuggestsByAdvertId '{"id":1379457469}' ```
malytinKonstantin_near-react-app
.idea dbnavigator.xml modules.xml vcs.xml README.md package-lock.json package.json public index.html manifest.json robots.txt src components Container index.ts styles.css Header index.ts RGBContract index.ts index.ts hooks index.ts useStores.ts pages Main index.ts index.ts stores index.ts services index.ts rgb-contract.ts wallet-store.ts tsconfig.json
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/).
keypom_aha-boilerplate
README.md __tests__ create-tix.js nearcon-keys.json nearcon nearcon.ava.ts utils.ts tests.ava.ts utils keypom.ts types.ts workspaces.ts contract Cargo.toml build.sh src approval.rs enumeration.rs events.rs internal.rs lib.rs metadata.rs nft_core.rs owner.rs raffle.rs royalty.rs target .rustc_info.json debug .fingerprint Inflector-a9d5d0565aa26a9b lib-inflector.json ahash-672bd2931ec6a4a8 lib-ahash.json ahash-988591fdd6bdb6e2 run-build-script-build-script-build.json ahash-a2329d604145205d build-script-build-script-build.json arrayref-c8b64655e1ccaaba lib-arrayref.json arrayvec-2bbca17f484924d4 lib-arrayvec.json arrayvec-5547cda376c3ec60 lib-arrayvec.json autocfg-5af00b76086a596d lib-autocfg.json base64-b3faa90ca2e064a6 lib-base64.json base64-f1fdacb6fbeab256 lib-base64.json bitvec-6d66d60a4bb74df7 lib-bitvec.json blake2-2da85ddf0c66af50 lib-blake2.json block-buffer-15495cd87911817d lib-block-buffer.json block-buffer-d976ca211eb89f5a lib-block-buffer.json borsh-derive-fd514b5ce8d53b0c lib-borsh-derive.json borsh-derive-internal-ba0949be12139283 lib-borsh-derive-internal.json borsh-e22f757c0018fd56 lib-borsh.json borsh-schema-derive-internal-f72e2ec7f265a76d lib-borsh-schema-derive-internal.json bs58-97859ce9ec9577ac lib-bs58.json byte-slice-cast-201c1ba21e1ed168 lib-byte-slice-cast.json byteorder-ac21c6fb65aa883b lib-byteorder.json bytesize-0f18e0df42f9c9e0 lib-bytesize.json c2-chacha-00ff6b3f83302d8f lib-c2-chacha.json cc-56df56d9b8687284 lib-cc.json cfg-if-3684f691ab83e331 lib-cfg-if.json cfg-if-472a251764bcb4db lib-cfg-if.json cfg-if-9213a1a06b9e4053 lib-cfg-if.json chrono-4646a16935d79532 lib-chrono.json cipher-756136346095f559 lib-cipher.json convert_case-0c4b31b357014ce8 lib-convert_case.json core-foundation-sys-f44387363f7e5e35 lib-core-foundation-sys.json cpufeatures-a32fc4710e1c4645 lib-cpufeatures.json crunchy-6f9f212811594b4d build-script-build-script-build.json crunchy-d803e387cc75866e lib-crunchy.json crunchy-ddaff50b37de4df2 run-build-script-build-script-build.json crypto-common-228a17245f07b3cc lib-crypto-common.json crypto-mac-2577276ccb689c21 lib-crypto-mac.json curve25519-dalek-2b37687683b1f27a lib-curve25519-dalek.json derive_more-81e3007be6b6bcad lib-derive_more.json digest-8ce86c113abb95ac lib-digest.json digest-f5ac998d64d83b30 lib-digest.json dyn-clone-c9ffa55d6f7567d6 lib-dyn-clone.json easy-ext-98d8acfd023548de lib-easy-ext.json ed25519-a342ebffeab01359 lib-ed25519.json ed25519-dalek-f8776d76654bc772 lib-ed25519-dalek.json equivalent-b1b430f24fff849d lib-equivalent.json fixed-hash-8d12a5bd0026a574 lib-fixed-hash.json funty-1c4e7e1c1aadfaca lib-funty.json generic-array-1c8bb2caf70d8c87 lib-generic_array.json generic-array-b1ce76c93772ff3c build-script-build-script-build.json generic-array-c527a6a11b9662e4 run-build-script-build-script-build.json getrandom-1115d65dc459b699 build-script-build-script-build.json getrandom-6b0de468cffbca18 lib-getrandom.json getrandom-99809381601c096b lib-getrandom.json getrandom-b7106af2cd28e076 run-build-script-build-script-build.json hashbrown-a4660b9e3fc4e170 lib-hashbrown.json hashbrown-f815b7fe1bbcb797 lib-hashbrown.json heck-0e5877dfd4b68df8 lib-heck.json hex-79229d51a3eeaed8 lib-hex.json iana-time-zone-941a09cc4148cfa5 lib-iana-time-zone.json impl-codec-9067e2deccee9395 lib-impl-codec.json impl-trait-for-tuples-1f528ea456f12cd2 lib-impl-trait-for-tuples.json indexmap-bccc87a31a2111ea lib-indexmap.json itoa-630cf89b825b2b41 lib-itoa.json keccak-f0eee331f101a48d lib-keccak.json lazy_static-78b1e2c47f102258 lib-lazy_static.json libc-219a6fea0e319a92 lib-libc.json libc-4c6b0fbf491c9823 build-script-build-script-build.json libc-6de21bff115d96c3 lib-libc.json libc-ac01fc990d58b73c run-build-script-build-script-build.json memory_units-2c238ce58d31d060 lib-memory_units.json near-abi-1581ced7b83346a8 lib-near-abi.json near-account-id-496a93e9ea5256f6 lib-near-account-id.json near-crypto-8ff35c89d15cbec2 lib-near-crypto.json near-primitives-core-8098bc88d2ee8003 lib-near-primitives-core.json near-primitives-f22de9f6fff287cd lib-near-primitives.json near-rpc-error-core-fb312fbb1f015a8d lib-near-rpc-error-core.json near-rpc-error-macro-219d7688fe6eb695 lib-near-rpc-error-macro.json near-sdk-56be9cd540418aeb lib-near-sdk.json near-sdk-macros-dc50b03c07589078 lib-near-sdk-macros.json near-sys-586a7840206e1b78 lib-near-sys.json near-vm-errors-d89b1c3f1e9dac00 lib-near-vm-errors.json near-vm-logic-fc3563aef34fdc9f lib-near-vm-logic.json nearcon-factory-contract-297f47154745ebc0 test-lib-nearcon-factory-contract.json nearcon-factory-contract-6428cc0caf93dca9 lib-nearcon-factory-contract.json num-bigint-2c16c5b9ee8bebf3 lib-num-bigint.json num-bigint-36a6f3c0609f61e5 build-script-build-script-build.json num-bigint-e456b3fc23ac8e2a run-build-script-build-script-build.json num-integer-890ccace086c54ce build-script-build-script-build.json num-integer-9712ca33704be101 lib-num-integer.json num-integer-b553ada80577b514 run-build-script-build-script-build.json num-rational-cbf21db3966cd0e3 lib-num-rational.json num-rational-d291a986acdd5623 build-script-build-script-build.json num-rational-e301223049b3d19f run-build-script-build-script-build.json num-traits-51369917f0575d6c run-build-script-build-script-build.json num-traits-621f8a1603e58da8 lib-num-traits.json num-traits-d5e58469c9e6fe2e build-script-build-script-build.json once_cell-b568a843e91ccb0e lib-once_cell.json once_cell-d984bb228aa77599 lib-once_cell.json opaque-debug-3c95d24f1cf5e5d2 lib-opaque-debug.json parity-scale-codec-3c4aeba41aeb2ca2 lib-parity-scale-codec.json parity-scale-codec-derive-73b3f503b157ecd5 lib-parity-scale-codec-derive.json parity-secp256k1-4b1a395a29783579 run-build-script-build-script-build.json parity-secp256k1-6fc39df9c3b0a0d5 lib-secp256k1.json parity-secp256k1-e093f35a94512032 build-script-build-script-build.json ppv-lite86-2d02af8d3a7cc1b6 lib-ppv-lite86.json primitive-types-3d072a0064657f1a lib-primitive-types.json proc-macro-crate-19810ca75a8bf1b9 lib-proc-macro-crate.json proc-macro-crate-6ca60b8a9baf297a lib-proc-macro-crate.json proc-macro2-161b2d59a9f9cd1e lib-proc-macro2.json proc-macro2-afe4a2ee50c0a3a0 run-build-script-build-script-build.json proc-macro2-c8fba50fc9fb8a29 build-script-build-script-build.json quote-721312e3b935274c lib-quote.json radium-04ca0a7e873e16de lib-radium.json radium-155d1d9c0a92dde6 build-script-build-script-build.json radium-de881ebf9ed57bad run-build-script-build-script-build.json rand-91eb593592fb21b1 lib-rand.json rand-f4716ac8cb8c98a6 lib-rand.json rand_chacha-573426e073102c31 lib-rand_chacha.json rand_chacha-794ae634bbbe0856 lib-rand_chacha.json rand_core-6dbe07e2eb3ff81f lib-rand_core.json rand_core-ccec530b473799c5 lib-rand_core.json reed-solomon-erasure-1d5748c3d5bb1e80 run-build-script-build-script-build.json reed-solomon-erasure-36b7bd2106ddd63b build-script-build-script-build.json reed-solomon-erasure-451cbf124b6408ad lib-reed-solomon-erasure.json ripemd-ac7061830d013250 lib-ripemd.json rustc-hex-af71e3ad5dce6c3b lib-rustc-hex.json rustversion-0fad854280035e63 build-script-build-script-build.json rustversion-30092f0adc775e42 run-build-script-build-script-build.json rustversion-aea023e24dec6e95 lib-rustversion.json ryu-4576bdd4ef42192d lib-ryu.json schemars-77f51b19dbc9e025 build-script-build-script-build.json schemars-c91bf22923ad1a77 lib-schemars.json schemars-eaa6d55151d957cb run-build-script-build-script-build.json schemars_derive-5a797176dbe55f84 lib-schemars_derive.json semver-455bdad277cb89d0 lib-semver.json semver-97b71a2632309c3d run-build-script-build-script-build.json semver-eb00ec944cb822e8 build-script-build-script-build.json serde-06e006b6be40131e build-script-build-script-build.json serde-63fee5d4e9e873c0 lib-serde.json serde-7f246fb020a7ac43 run-build-script-build-script-build.json serde-e4f38f7d7b365cff lib-serde.json serde_derive-7394c41afaeef2d8 lib-serde_derive.json serde_derive_internals-a17d754758cc6888 lib-serde_derive_internals.json serde_json-3cbd03e9e93eedc8 build-script-build-script-build.json serde_json-7520268d9f9e75c1 run-build-script-build-script-build.json serde_json-abd6bfbe3d466646 lib-serde_json.json sha2-9c60ee92fb2c0d17 lib-sha2.json sha2-a1963bd813ee64eb lib-sha2.json sha3-12c3d5b230c646d7 lib-sha3.json signature-e2f7f77a89fd0388 lib-signature.json smallvec-8eb59e85d9e3d38d lib-smallvec.json smart-default-e2f5b9e32ec42de7 lib-smart-default.json spin-d050a7e122e817cc lib-spin.json static_assertions-cbce9ad72d4b115d lib-static_assertions.json strum-2263894788645e09 lib-strum.json strum_macros-47e1ffb02862960f lib-strum_macros.json subtle-a8b2e27c0f4fbf7b lib-subtle.json syn-3e1fc02ea761d0a1 run-build-script-build-script-build.json syn-8cc5f140ffb68dc9 lib-syn.json syn-d41ae393905b7af4 build-script-build-script-build.json syn-e37ea7b92d3b2181 lib-syn.json tap-4db4c964def1b60a lib-tap.json thiserror-7bfaa635d19f8650 lib-thiserror.json thiserror-9a2c9322856ed3aa build-script-build-script-build.json thiserror-b630d4dc70d62ee8 run-build-script-build-script-build.json thiserror-impl-f26ef10496e1a989 lib-thiserror-impl.json time-d9ad227f18c3f944 lib-time.json toml-dfb0bc9ce1118439 lib-toml.json toml_datetime-a8925f6bc8d62d39 lib-toml_datetime.json toml_edit-2b1a9fd145b489e1 lib-toml_edit.json typenum-ae266bb20c1c0bd6 run-build-script-build-script-main.json typenum-f9a606bcdd288876 lib-typenum.json typenum-ffeb346f11a1ef0e build-script-build-script-main.json uint-752f54f20f902ae7 lib-uint.json unicode-ident-d9624bf63a3259cf lib-unicode-ident.json version_check-dcd9d58a259cfebc lib-version_check.json wee_alloc-acd96d6cf582aad7 lib-wee_alloc.json wee_alloc-b2fe6707d88087e1 build-script-build-script-build.json wee_alloc-e8ba7f89fb28bf35 run-build-script-build-script-build.json winnow-bada6a86463a7ed4 lib-winnow.json wyz-eb4998c640f6ac75 lib-wyz.json zeroize-cd75413f03090d30 lib-zeroize.json zeroize_derive-868aec49869db6bc lib-zeroize_derive.json zeropool-bn-7c2c2fd97dacfa5f lib-zeropool-bn.json build crunchy-ddaff50b37de4df2 out lib.rs num-bigint-e456b3fc23ac8e2a out radix_bases.rs parity-secp256k1-4b1a395a29783579 out flag_check.c reed-solomon-erasure-1d5748c3d5bb1e80 out table.rs thiserror-b630d4dc70d62ee8 out probe.rs typenum-ae266bb20c1c0bd6 out consts.rs op.rs tests.rs wee_alloc-e8ba7f89fb28bf35 out wee_alloc_static_array_backend_size_bytes.txt release .fingerprint Inflector-9f6c5eb6607cae38 lib-inflector.json ahash-0b2ae90c84309e83 build-script-build-script-build.json borsh-derive-c636fc05e86bd331 lib-borsh-derive.json borsh-derive-internal-4e901194e2ba0bba lib-borsh-derive-internal.json borsh-schema-derive-internal-6e58ef152f518a7e lib-borsh-schema-derive-internal.json near-sdk-macros-36f7ac81dfe28d3c lib-near-sdk-macros.json proc-macro-crate-153af1958b43cd46 lib-proc-macro-crate.json proc-macro2-2f00336b091e545d lib-proc-macro2.json proc-macro2-661a751eabc24d73 build-script-build-script-build.json proc-macro2-e9d6a1c6b1795f53 run-build-script-build-script-build.json quote-11fb4ae980dfa73d lib-quote.json schemars-b49dd5ab1051bd0d build-script-build-script-build.json schemars_derive-898655f545f5dba8 lib-schemars_derive.json semver-36e396563abb5fd6 build-script-build-script-build.json serde-8b6b92464e4c218c build-script-build-script-build.json serde-9a6d2656cd2db639 lib-serde.json serde-f8108f1aae9e5343 run-build-script-build-script-build.json serde_derive-1a29582276a110be lib-serde_derive.json serde_derive_internals-36c60e952570c91e lib-serde_derive_internals.json serde_json-a1e906be9ffe71d9 build-script-build-script-build.json syn-6a7536e097ee295c lib-syn.json syn-7d3f7ed4bf18893b run-build-script-build-script-build.json syn-ab0a2b44f7694773 build-script-build-script-build.json syn-f9066a0b9c7d520a lib-syn.json toml-b58a756847e11186 lib-toml.json unicode-ident-a1c028795e9f032c lib-unicode-ident.json version_check-37bfa5ae93653f8b lib-version_check.json wee_alloc-bc9bb16427189535 build-script-build-script-build.json wasm32-unknown-unknown release .fingerprint ahash-1c14633346178fe7 lib-ahash.json ahash-591cc009c06e7cf5 run-build-script-build-script-build.json base64-6bac46afbd1962fd lib-base64.json borsh-b25ae22c3296dc12 lib-borsh.json bs58-0aef5dfa83ca8a80 lib-bs58.json cfg-if-caba0a56c040732b lib-cfg-if.json dyn-clone-51e519c98ad7464c lib-dyn-clone.json hashbrown-49ddfa3f6d06f1fc lib-hashbrown.json itoa-c7a9e3fc3eac61d1 lib-itoa.json memory_units-a5486a0e2d197f5a lib-memory_units.json near-abi-a490f316d7a04638 lib-near-abi.json near-sdk-b5609a6bfa947fd4 lib-near-sdk.json near-sys-ceeb9e0e6a6af79a lib-near-sys.json nearcon-factory-contract-829ba4831a3a9531 lib-nearcon-factory-contract.json once_cell-3e0d8eb85f9c424a lib-once_cell.json ryu-321680dd110e2fa6 lib-ryu.json schemars-de8dfce3726c8bc3 lib-schemars.json schemars-faefaebea69e0fbf run-build-script-build-script-build.json semver-6dc3e67d65107941 run-build-script-build-script-build.json semver-c4f891220617eb46 lib-semver.json serde-a7fbaf84d33ee300 lib-serde.json serde-d4a82b1095dfd93f run-build-script-build-script-build.json serde_json-ae90ee906564c6dc lib-serde_json.json serde_json-fd6f09702787e79b run-build-script-build-script-build.json wee_alloc-b96209701010a280 lib-wee_alloc.json wee_alloc-c5dfd13fdbef16ac run-build-script-build-script-build.json build wee_alloc-c5dfd13fdbef16ac out wee_alloc_static_array_backend_size_bytes.txt frontend .prettierrc.js config-overrides.js package.json postcss.config.js public index.html manifest.json robots.txt src App.js components Footer Footer.css index.ts LoadingModal index.ts MultipleChoice index.ts Navbar Navbar.css index.ts SquaresBG index.ts index.css logo.svg react-app-env.d.ts routes Error index.ts Home Home.css index.ts Prizes Gallery PrizeGallery.css PrizeHome.css index.ts Stats index.ts Success index.ts setupTests.ts tailwind.config.js tsconfig.json package.json
# Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/).
nel349_NEARCON-2022
.eslintrc.js .expo-shared assets.json NEAR lensWebViewSupport .github workflows tests.yml .gitpod.yml README.md contract README.md babel.config.json build.sh deploy.sh package.json src contract.ts model.ts utils.ts tsconfig.json frontend assets global.css logo-black.svg logo-white.svg index.js near-interface.js near-wallet.js package.json start.sh integration-tests package.json src main.ava.ts package.json README.md app.config.ts babel.config.js components Nav.js NavAbsolute.js __tests__ StyledText-test.js index.js temp.ts constants Colors.js Colors.ts Layout.ts index.js global.ts hooks useCachedResources.ts useColorScheme.ts index.js lens_protocol api-polygon authenticate.js create-profiles.ts index.js lens_hub_abi abi.json mutations.js profile apollo-client.ts profiles.js queries.js utils.js aurora authenticate.ts challenge.ts client.ts index.ts profiles.ts metro.config.js mocks contact.json navigation LinkingConfiguration.ts package.json plugins network_security_config.xml trust-local-certs.js screens ExploreProfiles RecommendedProfile.js styles.js Profile style.js tsconfig.json utils datetime.js image.js index.js
# Donation 💸 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Gitpod-Ready-orange)](https://gitpod.io/#/https://github.com/near-examples/donation-js) [![](https://img.shields.io/badge/Contract-js-yellow)](https://docs.near.org/develop/contracts/anatomy) [![](https://img.shields.io/badge/Frontend-JS-yellow)](https://docs.near.org/develop/integrate/frontend) [![](https://img.shields.io/badge/Testing-passing-green)](https://docs.near.org/develop/integrate/frontend) Our Donation example enables to forward money to an account while keeping track of it. It is one of the simplest examples on making a contract receive and send money. ![](https://docs.near.org/assets/images/donation-7cf65e5e131274fd1ae9aa34bc465bb8.png) # What This Example Shows 1. How to receive and transfer $NEAR on a contract. 2. How to divide a project into multiple modules. 3. How to handle the storage costs. 4. How to handle transaction results. 5. How to use a `Map`. <br /> # Quickstart Clone this repository locally or [**open it in gitpod**](https://gitpod.io/#/github.com/near-examples/donation-js). Then follow these steps: ### 1. Install Dependencies ```bash npm install ``` ### 2. Test the Contract Deploy your contract in a sandbox and simulate interactions from users. ```bash npm test ``` ### 3. Deploy the Contract Build the contract and deploy it in a testnet account ```bash npm run deploy ``` ### 4. Start the Frontend Start the web application to interact with your smart contract ```bash npm start ``` --- # Learn More 1. Learn more about the contract through its [README](./contract/README.md). 2. Check [**our documentation**](https://docs.near.org/develop/welcome). # How to install app app link: https://expo.dev/@nel349/test-dapp?serviceType=classic&distribution=expo-go 1. Install expo go in your phone from the app store(iOS) or play store(android) 2. For iphone users scan the QR in the above link the app using your camera app 3. For android users, open Expo go, tap on Scan QR code, scan the QR in the above link. 4. After scan, app should automatically install. # Donation Contract The smart contract exposes methods to handle donating $NEAR to a `beneficiary`. ```ts @call donate() { // Get who is calling the method and how much $NEAR they attached let donor = near.predecessorAccountId(); let donationAmount: bigint = near.attachedDeposit() as bigint; let donatedSoFar = this.donations.get(donor) === null? BigInt(0) : BigInt(this.donations.get(donor) as string) let toTransfer = donationAmount; // This is the user's first donation, lets register it, which increases storage if(donatedSoFar == BigInt(0)) { assert(donationAmount > STORAGE_COST, `Attach at least ${STORAGE_COST} yoctoNEAR`); // Subtract the storage cost to the amount to transfer toTransfer -= STORAGE_COST } // Persist in storage the amount donated so far donatedSoFar += donationAmount this.donations.set(donor, donatedSoFar.toString()) // Send the money to the beneficiary const promise = near.promiseBatchCreate(this.beneficiary) near.promiseBatchActionTransfer(promise, toTransfer) // Return the total amount donated so far return donatedSoFar.toString() } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Deploy the Contract You can automatically compile and deploy the contract in the NEAR testnet by running: ```bash npm run deploy ``` Once finished, check the `neardev/dev-account` file to find the address in which the contract was deployed: ```bash cat ./neardev/dev-account # e.g. dev-1659899566943-21539992274727 ``` The contract will be automatically initialized with a default `beneficiary`. To initialize the contract yourself do: ```bash # Use near-cli to initialize contract (optional) near call <dev-account> init '{"beneficiary":"<account>"}' --accountId <dev-account> ``` <br /> ## 2. Get Beneficiary `beneficiary` is a read-only method (`view` method) that returns the beneficiary of the donations. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <dev-account> beneficiary ``` <br /> ## 3. Get Number of Donations `donate` forwards any attached money to the `beneficiary` while keeping track of it. `donate` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <dev-account> donate --amount 1 --accountId <account> ``` **Tip:** If you would like to `donate` using your own account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account>`.
near-examples_guest-book-examples
.devcontainer devcontainer.json .github workflows tests-rs.yml tests-ts.yml README.md contract-rs Cargo.toml README.md rust-toolchain.toml src lib.rs tests sandbox.rs contract-ts README.md package.json sandbox-ts main.ava.ts src contract.ts model.ts tsconfig.json frontend index.html package.json public vite.svg src assets react.svg index.css services near-wallet.js vite.config.js
# Guest Book Contract The smart contract stores messages from users. Messages can be `premium` if the user attaches sufficient money (0.1 $NEAR). ```ts this.messages = []; @call // Public - Adds a new message. add_message({ text }: { text: string }) { // If the user attaches more than 0.1N the message is premium const premium = near.attachedDeposit() >= BigInt(POINT_ONE); const sender = near.predecessorAccountId(); const message = new PostedMessage({premium, sender, text}); this.messages.push(message); } @view // Returns an array of messages. get_messages({ fromIndex = 0, limit = 10 }: { fromIndex: number, limit: number }): PostedMessage[] { return this.messages.slice(fromIndex, fromIndex + limit); } ``` <br /> # Quickstart 1. Make sure you have installed [node.js](https://nodejs.org/en/download/package-manager/) >= 16. 2. Install the [`NEAR CLI`](https://github.com/near/near-cli#setup) <br /> ## 1. Build and Test the Contract You can automatically compile and test the contract by running: ```bash npm run test ``` <br /> ## 2. Create an Account and Deploy You can create a testnet account and deploy the contract by running: ```bash near create-account <your-account.testnet> --useFaucet near deploy <your-account.testnet> build/release/hello_near.wasm ``` ## 3. Retrieve the Stored Messages `get_messages` is a read-only method (`view` method) that returns a slice of the vector `messages`. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```bash near view <your-account.testnet> get_messages '{"from_index":0, "limit":10}' ``` <br /> ## 4. Add a Message `add_message` adds a message to the vector of `messages` and marks it as premium if the user attached more than `0.1 NEAR`. `add_message` is a payable method for which can only be invoked using a NEAR account. The account needs to attach money and pay GAS for the transaction. ```bash # Use near-cli to donate 1 NEAR near call <your-account.testnet> add_message '{"text": "a message"}' --amount 0.1 --accountId <your-account.testnet> ``` **Tip:** If you would like to add a message another account, first login into NEAR using: ```bash # Use near-cli to login your NEAR account near login ``` and then use the logged account to sign the transaction: `--accountId <your-account.testnet>`. # Guest Book Contract This smart contract stores messages from users. If the user attaches more than 0.1 NEAR tokens the message is marked as premium. ## How to Build Locally? Install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash cargo near build ``` ## How to Test Locally? ```bash cargo test ``` ## How to Deploy? To deploy manually, install [`cargo-near`](https://github.com/near/cargo-near) and run: ```bash # Create a new account cargo near create-dev-account # Deploy the contract on it cargo near deploy <account-id> ``` ## How to Interact? _In this example we will be using [NEAR CLI](https://github.com/near/near-cli) to intract with the NEAR blockchain and the smart contract_ _If you want full control over of your interactions we recommend using the [near-cli-rs](https://near.cli.rs)._ ## 1. Add a Message `add_message` adds a message to the vector of `messages` and marks it as premium if the user attached more than `0.1 NEAR`. ```rust // Public - Adds a new message. #[payable] pub fn add_message(&mut self, text: String) { // If the user attaches more than 0.01N the message is premium let premium = env::attached_deposit() >= POINT_ONE; let sender = env::predecessor_account_id(); let message = PostedMessage{premium, sender, text}; self.messages.push(&message); } ``` ```bash near call <dev-account> add_message '{"text": "a message"}' --amount 0.1 --accountId <account> ``` ### 2. Retrieve the Stored Messages `get_messages` is a read-only method (`view` method) that returns a slice of the vector `messages`. Please note that `from_index` and `limit` are optional parameters. `View` methods can be called for **free** by anyone, even people **without a NEAR account**! ```rust // Public Method - Returns a slice of the messages. pub fn get_messages(&self, from_index: Option<U64>, limit: Option<U64>) -> Vec<&PostedMessage> { let from = u64::from(from_index.unwrap_or(U64(0))); let limit = u64::from(limit.unwrap_or(U64(10))); self.messages .iter() .skip(from as usize) .take(limit as usize) .collect() } ``` ```bash near view <dev-account> get_messages '{"from_index":0, "limit":10}' ``` ## Useful Links - [cargo-near](https://github.com/near/cargo-near) - NEAR smart contract development toolkit for Rust - [near CLI-rs](https://near.cli.rs) - Iteract with NEAR blockchain from command line - [NEAR Rust SDK Documentation](https://docs.near.org/sdk/rust/introduction) - [NEAR Documentation](https://docs.near.org) - [NEAR StackOverflow](https://stackoverflow.com/questions/tagged/nearprotocol) - [NEAR Discord](https://near.chat) - [NEAR Telegram Developers Community Group](https://t.me/neardev) - NEAR DevHub: [Telegram](https://t.me/neardevhub), [Twitter](https://twitter.com/neardevhub) # Guest Book Examples 📖 [![](https://img.shields.io/badge/⋈%20Examples-Basics-green)](https://docs.near.org/tutorials/welcome) [![](https://img.shields.io/badge/Contract-JS-yellow)](contract-ts) [![](https://img.shields.io/badge/Contract-Rust-red)](contract-rs) [![](https://img.shields.io/badge/Frontend-JS-yellow)](frontend) ![example workflow](https://github.com/near-examples/guest-book-examples/actions/workflows/tests-ts.yml/badge.svg) ![example workflow](https://github.com/near-examples/guest-book-examples/actions/workflows/tests-rs.yml/badge.svg) This repository contains example implementations of a Guest Book smart contract in both JavaScript and Rust, and an examples of a frontend interacting with a Guest Book smart contract. ## Repositories - [Guest Book TS Example](contract-ts) - [Guest Book RS Example](contract-rs) - [Guest Book Frontend Example](Frontend)
mhassanist_jobchain
README.md job-chain as-pect.config.js asconfig.json assembly __tests__ index.unit.spec.ts index.ts models.ts tsconfig.json utils.ts index.js package-lock.json package.json scripts 0-check-account.sh 1-build-deploy.sh 2-create-job.sh 4-list-available-jobs.sh 4-list-jobs.sh 5-submit-job.sh tests index.js validation-contract asconfig.json assembly index.ts tsconfig.json utils.ts index.js package-lock.json package.json scripts 0-check-account.sh 1-build-deploy.sh 2-test-call-validate.sh tests index.js
# job-chain ## Note! This project is meant for educational purposes only. It was developed as a part of the [NEAR](https://near.org/) certififed developer program. It is not production-ready and it misses a lot of test, validations and business logic. The project is built using [NEAR](https://near.org/) 's AssemblyScript SDK and the deployment scripts uses [NEAR-CLI](https://docs.near.org/docs/tools/near-cli) ## About The project simulates a freelance jobs portal in the era of blockchain when jobs can be auto-validated using smart contracts and the payment is proccessed automatically. The employer creates a job. Part of the job's required parameters is to submit the validation contract, and method, used to validate the submited work of that job. It is up for the employer to request the type of work to be done; but it has to be sent as text to the submitJob function. ## The Employer - Creates a validation contract and a validation method - Creates a job with job requirements and validation contract info using `createJob` function ## Freelancer - Check the available jobs `getAvailableJobs` - Submit the job using `submitJob` - Check the job submission status `getAllJobs` or `checkJob` * Freelance will get the the money automatically if the job got auto validated by the validation contract. # Runing the sample validation contract *You have to login in the cli and set the enviornment variables "$CONTRACT" and "$OWNER" before running the scripts `export OWNER=msaudi2.testnet` `export CONTRACT=validate.msaudi2.testnet` ### Scripts `./scripts/0-check-account.sh` This script will delete the old account if exitsis, and create a new one with the specified CONTRACT environment variable. `./scripts/1-build-deploy.sh` This script will build, and deploy the contract. `./scripts/2-test-call-validate.sh` This script will test the deployed validation contract by calling the method valid with invalid and valid work entry. # Runing the job portal contract *You have to login in the cli and set the enviornment variables "$CONTRACT" and "$OWNER" before running the scripts `export OWNER=msaudi.testnet` `export CONTRACT=jobchain.msaudi.testnet` ### Scripts `./scripts/0-check-account.sh` This script will delete the old account if exitsis, and create a new one with the speciifed CONTRACT environment variable. `./scripts/1-build-deploy.sh` This script will build, and deploy the contract. `./scripts/3-create-job.sh` This script will create a sample job. `./scripts/4-list-jobs.sh` or `./scripts/4-list-available-jobs.sh` To list all the current/available jobs `./scripts/5-submit-job.sh` To submit and validate a job as a freelance `./scripts/4-list-jobs.sh` or `./scripts/4-list-available-jobs.sh` To list all the current/available jobs ## Future enhancements - Separate the submissions of the jobs from the jobs themselves - Better handling of Gas and money transfer - Adding tests
george-shammar_Insignia
README.md artifacts @openzeppelin contracts access Ownable.sol Ownable.dbg.json Ownable.json security Pausable.sol Pausable.dbg.json Pausable.json token ERC721 ERC721.sol ERC721.dbg.json ERC721.json IERC721.sol IERC721.dbg.json IERC721.json IERC721Receiver.sol IERC721Receiver.dbg.json IERC721Receiver.json extensions ERC721URIStorage.sol ERC721URIStorage.dbg.json ERC721URIStorage.json IERC721Metadata.sol IERC721Metadata.dbg.json IERC721Metadata.json utils Address.sol Address.dbg.json Address.json Context.sol Context.dbg.json Context.json Strings.sol Strings.dbg.json Strings.json introspection ERC165.sol ERC165.dbg.json ERC165.json IERC165.sol IERC165.dbg.json IERC165.json contracts Insignia.sol Insignia.dbg.json Insignia.json cache solidity-files-cache.json hardhat.config.js package.json public index.html scripts deploy.js src components App.js Community.js Copyright.js CreateAsset.js DownloadGame.js Event.js Footer.js GetToken.js Home.js Join.js Marketplace.js Nav.js News.js Next.js NoWallet.js Reveal.js Routes.js Scroll.js Trailer.js WalletSetup.js contracts Insignia.json contract-address.json index.js styles App.css Community.css Copyright.css Event.css Footer.css Home.css Join.css Marketplace.css Nav.css Next.css Play.css Reveal.css Scroll.css Trailer.css WalletSetup.css Whitepaper.css index.css utils wallet.js
![alt text](https://github.com/george-shammar/Insignia/blob/master/src/assets/Logo.png?raw=true) # INSIGNIA ## OVERVIEW Insignia is a 3D military strategy blockchain game application. A multi-player play-and-earn game, set in a medieval metaverse. With an immersive experience and one that provides an unequaled earning potential to gamers across the board. This project hopes to solve specific problems that have been identified in the blockchain gaming ecosystem. Details about the problem statement and our proposed solutions could be found in the whitepaper linked below. ### Discord [Join us on Discord](https://discord.gg/A4xfZENW2Z) ### Twitter [Follow us on Twitter](https://twitter.com/Insignia_verse?s=03) ### Currently availabe only on PC! <!-- [Live-Demo](https://practical-jennings-1b91e5.netlify.app/) --> [Game-Demo](https://screenrec.com/share/wVkHyPRexT) For a comprehensive run down about the gameplay, game economics, tokenomics, road map, e.t.c please visit the link below to read the Whitepaper. [Whitepaper](https://getinsignia.gitbook.io/whitepaper/) Insignia is built on top of [NEAR Protocol](https://near.org/) and game assets are stored on IPFS. ### Create Asset Page ![screenshot](/src/assets/screenshot.png) ## Tech Stack ### Blockchain - Near Protocol - IPFS (Decentralized storage) - Rust - near-api-js ### Web Application - React - Javascript - HTML - CSS - Bootstrap ### Game - Unreal Engine ## Gettin Started ### To start the application locally To run a local copy of this application, follow the steps below: - Go to the "Code" section of this repository and press the green button that says "Code". Copy the URL or the SSH. - Go to the terminal and enter: ``` git clone https://github.com/george-shammar/Insignia.git ``` The URL or SSH are the links copied from the step above. - If you don't have git installed, you can download this project and unzip it. - Change directory into the folder the application is saved. ``` cd directory ``` Directory is the name of your folder. - Once you have the local copy in your desired folder, go back to your terminal and run: ``` npm install ``` This command installs all the dependencies of the application. This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). - To start the application, run : ``` npm start ``` This command runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in your browser. The page will reload when you make changes.\ You may also see any lint errors in the console. ## Usage Upon launching the application, go to "Play Now". ### Step 1: NEAR Wallet Set-up - Insignia lives on the NEAR protocol. NEAR Wallet is your ticket to our metaverse. For first time NEAR users, click "Get NEAR Wallet", otherwise, proceed to the next tab. ### Step 2: Get Insignia Token. - Insignia Token is the native currency of our metaverse. Details about the tokenomics can be found in the Whitepaper. We are currently using NEAR as the means of exchange. Click "Fund Wallet" and visit any of the exchanges in the list to fund your wallet. To do anything with the NEAR Wallet, you will need at least 0.1 NEAR. However, on the testnet, NEAR wallet is pre-funded when you created an account. ### Step 3a: Create Game Asset - Each game asset is a unique NFT stored on IPFS. Each wallet can only have one Insignia NFT. Click "Connect Wallet" to link your NEAR Wallet. - Click "Create Asset" to mint a unique NFT. ### Step 3b: Marketplace - An alternative is to purchase a Game Asset in the Marketplace. ### Step 4: Download and Play Currently, a very limited edition of the Free-To-Play model of the game is available on PC. Android and IOS release is coming soon. # Game Overview (Find details in the whitepaper) ## The basics ### World Of Chaos #### Cities World of Chaos is made up of three hundred (300) real-world ancient cities. Each city is a unique NFT. A typical city is made up of a Commander, an Army with a varied number of battalion (A battalion consists of 700 soldiers). When you mint a city, you get the following: - A medieval city and a 3 minutes video tour of your city with a short military show of force. It's architecture, people, and commerce. - An army with an unknown number of battalions before minting. The strength of your defense depends on the number of battalions in your army. - A commander. - A treasury. - A unique Insignia. The bad news is that there are too much incentives for other cities and Mercenaries to attack your city - Your treasury!!! When you're defeated at war by another army, you loose the balance (Insignia Token) in your treasury. When you successfully defend or repel an attack, you earn the balance in the attacking armies' treasury. You win or loose when your city's symbol of insignia is captured by the other army or otherwise. The World of Chaos is ultimately an open, virtual, and explorable meta-verse. #### Mercenaries These are armies for hire - 45 in total. Each mercenary unit is a unique NFT with an unknown number of battalions before minting. Cities with insufficient armies can hire mercenaries to repel an attack or launch an attack. When you mint a mercenary unit you get the following. - An army with an unknown number of battalions. - A commander. - An insignia. As an owner of a mercenary unit, you can attack a city to earn the balance of the city's treasury or rent out your army to another city for a fee paid upfront and not dependent on the outcome of the renter's war. ### Fighting Pits The fighting pit involves one-on-one combat in an arena of cheering crowds and real-world viewers. A fighting season takes a maximum of 7 days or less (depending on the number of participants). Each arena holds between 2, 4, and 8 fighters in each pool. One fighter emerges as the winner from each pool and faces the winner from another pool in the tournament until we have one final winner. Peering is done randomly and the reward mechanism also utilizes a no-loss mechanism. To fight in the tournament, the following steps need to be taken: - Mint a fighter (unique NFT) to play. If you missed out during the initial minting, you may trade in the Marketplace. Insignia also provides the opportunity to rent a fighter from NFT owners who choose not to participate in a fighting season. - Deposit Insignia Tokens to enter the tournament. These tokens are withdrawable no matter the outcome of the tournament, win or lose. Hence, the no-loss mechanism. ## Game Controls - Forward : Keyboard "W" - Backward: Keyboard Key "Z" - Right: Keyboard Key "D" - Left: Keyboard Key "A" - Squat : Keyboard Key "C" - Sommersault: Multiple Space Bar press - Strike: Left Mouse click. - Jump: Keyboard Key "Space Bar" ## Developer 👤 **George Gbenle** - GitHub: [george-shammar](https://github.com/george-shammar) - Twitter: [@GeorgeShammar](https://twitter.com/GeorgeShammar) - LinkedIn: [George Gbenle](https://www.linkedin.com/in/georgegbenle/) ## 🤝 Contributing Contributions, issues and feature requests are welcome! ## Show your support Give a ⭐️ if you like this project!
kharioki_crossword-frontend
README.md contract Cargo.toml README.md build.bat build.sh src lib.rs test.sh package.json public index.html manifest.json robots.txt src App.css App.js config.js hardcoded-data.js index.css index.js utils.js webpack.config.js
# Rust Smart Contract Template ## Getting started To get started with this template: 1. Click the "Use this template" button to create a new repo based on this template 2. Update line 2 of `Cargo.toml` with your project name 3. Update line 4 of `Cargo.toml` with your project author names 4. Set up the [prerequisites](https://github.com/near/near-sdk-rs#pre-requisites) 5. Begin writing your smart contract in `src/lib.rs` 6. Test the contract `cargo test -- --nocapture` 8. Build the contract `RUSTFLAGS='-C link-arg=-s' cargo build --target wasm32-unknown-unknown --release` **Get more info at:** * [Rust Smart Contract Quick Start](https://docs.near.org/docs/develop/contracts/rust/intro) * [Rust SDK Book](https://www.near-sdk.io/) # crossword-frontend A react app frontend for a crossword game. This game makes calls to a Near smart contract deployed on the testnet.
Ideevoog_Toolblox.Ada.App
.github workflows adawillhandlefunctions.yml LICENSE.md Lib NBitcoin.deps.json NBitcoin.xml Toolblox.Ada.App.Model.deps.json Toolblox.Cryptography.deps.json Toolblox.Model.deps.json README.md Toolblox.Ada.App.Blockchain.Functions .vscode extensions.json launch.json settings.json tasks.json NftMetadataFunction function.json index.ts ProcessInvoiceFunction function.json index.ts readme.md UpdateSubscriptionFunction function.json index.ts host.json package-lock.json package.json tsconfig.json Toolblox.Ada.App.Functions AccountantFunctions.cs Helpers Sanitize.cs TableEntityExtensions.cs Properties ServiceDependencies adawillhandlefunctions appInsights1.arm.json storage1.arm.json serviceDependencies.adawillhandlefunctions.json serviceDependencies.json serviceDependencies.local.json Security.cs Services SystemTextJsonResult.cs Startup.cs StoreEventFunction.cs host.json Toolblox.Ada.App.sln
# Toolblox.Ada.App
near_near-api-js
commitlint.config.js packages accounts jest.config.js test account.access_key.test.js account.test.js account_multisig.test.js config.js contract.test.js contract_abi.test.js lve_runtime.test.js lve_storage.test.js promise.test.js providers.test.js test-utils.js biometric-ed25519 test utils.test.js cookbook accounts access-keys create-full-access-key.js create-function-access-key.js delete-access-key.js create-mainnet-account.js create-testnet-account.js api-keys backup-provider.js near-connection.js provider-example.js transactions batch-transactions.js get-tx-detail.js get-tx-status.js meta-transaction-relayer.js meta-transaction.js utils calculate-gas.js check-account-existence.js deploy-contract.js get-state.js unwrap-near.js verify-signature.js wrap-near.js crypto jest.config.js test key_pair.test.js keystores-browser jest.config.js test browser_keystore.test.js keystore_common.js keystores-node jest.config.js test keystore_common.js unencrypted_file_system_keystore.test.js keystores jest.config.js test in_memory_keystore.test.js keystore_common.js merge_keystore.test.js near-api-js browser-exports.js jest.config.js test config.js test-utils.js providers jest.config.js test fetch_json.test.js providers.test.js signers jest.config.js test signer.test.js transactions jest.config.js test serialize.test.js transaction.test.js utils fetch_error_schema.js jest.config.js test format.test.js logger.test.js rpc-errors.test.js validator.test.js wallet-account jest.config.js test wallet_account.test.js